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/tests/JIT/Directed/Arrays/simple2.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; internal class Simple2_Array_Test { public static int Main(String[] args) { Console.WriteLine("Starting..."); int SIZE = 10; Int32[,,,] foo = new Int32[SIZE, SIZE, SIZE, SIZE]; int i, j, k, l, m; Int64 sum = 0; for (i = 0; i < SIZE; i++) for (j = 0; j < SIZE; j++) for (k = 0; k < SIZE; k++) for (l = 0; l < SIZE; l++) { foo[i, j, k, l] = i * j * k * l; } for (i = 0; i < SIZE; i++) for (j = 0; j < i; j++) for (k = 0; k < j; k++) for (l = 0; l < k; l++) for (m = 0; m < l; m++) { sum += foo[i, j, k, l]; } if (sum == 197163) { Console.WriteLine("Everything Worked!"); return 100; } else { Console.WriteLine("Something is broken!"); 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; internal class Simple2_Array_Test { public static int Main(String[] args) { Console.WriteLine("Starting..."); int SIZE = 10; Int32[,,,] foo = new Int32[SIZE, SIZE, SIZE, SIZE]; int i, j, k, l, m; Int64 sum = 0; for (i = 0; i < SIZE; i++) for (j = 0; j < SIZE; j++) for (k = 0; k < SIZE; k++) for (l = 0; l < SIZE; l++) { foo[i, j, k, l] = i * j * k * l; } for (i = 0; i < SIZE; i++) for (j = 0; j < i; j++) for (k = 0; k < j; k++) for (l = 0; l < k; l++) for (m = 0; m < l; m++) { sum += foo[i, j, k, l]; } if (sum == 197163) { Console.WriteLine("Everything Worked!"); return 100; } else { Console.WriteLine("Something is broken!"); 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)
./src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.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.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)] public sealed class TypeForwardedToAttribute : Attribute { public TypeForwardedToAttribute(Type destination) { Destination = destination; } public Type Destination { get; } } }
// 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.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)] public sealed class TypeForwardedToAttribute : Attribute { public TypeForwardedToAttribute(Type destination) { Destination = destination; } public Type Destination { get; } } }
-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/Common/src/Interop/OSX/System.Native/Interop.SearchPath.iOS.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.InteropServices; internal static partial class Interop { internal static partial class Sys { [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SearchPath_TempDirectory", StringMarshalling = StringMarshalling.Utf8)] internal static partial string SearchPathTempDirectory(); } }
// 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.InteropServices; internal static partial class Interop { internal static partial class Sys { [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SearchPath_TempDirectory", StringMarshalling = StringMarshalling.Utf8)] internal static partial string SearchPathTempDirectory(); } }
-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/WaitCallback/thread01.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.Threading; class Gen<T> { public void Target(object p) { ManualResetEvent evt = (ManualResetEvent) p; Interlocked.Increment(ref Test_thread01.Xcounter); evt.Set(); } public static void ThreadPoolTest() { ManualResetEvent[] evts = new ManualResetEvent[Test_thread01.nThreads]; WaitHandle[] hdls = new WaitHandle[Test_thread01.nThreads]; for (int i=0; i<Test_thread01.nThreads; i++) { evts[i] = new ManualResetEvent(false); hdls[i] = (WaitHandle) evts[i]; } Gen<T> obj = new Gen<T>(); for (int i = 0; i < Test_thread01.nThreads; i++) { WaitCallback cb = new WaitCallback(obj.Target); ThreadPool.QueueUserWorkItem(cb,evts[i]); } WaitHandle.WaitAll(hdls); Test_thread01.Eval(Test_thread01.Xcounter==Test_thread01.nThreads); Test_thread01.Xcounter = 0; } } public class Test_thread01 { public static int nThreads = 50; public static int counter = 0; public static int Xcounter = 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() { Gen<int>.ThreadPoolTest(); Gen<double>.ThreadPoolTest(); Gen<string>.ThreadPoolTest(); Gen<object>.ThreadPoolTest(); Gen<Guid>.ThreadPoolTest(); Gen<int[]>.ThreadPoolTest(); Gen<double[,]>.ThreadPoolTest(); Gen<string[][][]>.ThreadPoolTest(); Gen<object[,,,]>.ThreadPoolTest(); Gen<Guid[][,,,][]>.ThreadPoolTest(); 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; using System.Threading; class Gen<T> { public void Target(object p) { ManualResetEvent evt = (ManualResetEvent) p; Interlocked.Increment(ref Test_thread01.Xcounter); evt.Set(); } public static void ThreadPoolTest() { ManualResetEvent[] evts = new ManualResetEvent[Test_thread01.nThreads]; WaitHandle[] hdls = new WaitHandle[Test_thread01.nThreads]; for (int i=0; i<Test_thread01.nThreads; i++) { evts[i] = new ManualResetEvent(false); hdls[i] = (WaitHandle) evts[i]; } Gen<T> obj = new Gen<T>(); for (int i = 0; i < Test_thread01.nThreads; i++) { WaitCallback cb = new WaitCallback(obj.Target); ThreadPool.QueueUserWorkItem(cb,evts[i]); } WaitHandle.WaitAll(hdls); Test_thread01.Eval(Test_thread01.Xcounter==Test_thread01.nThreads); Test_thread01.Xcounter = 0; } } public class Test_thread01 { public static int nThreads = 50; public static int counter = 0; public static int Xcounter = 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() { Gen<int>.ThreadPoolTest(); Gen<double>.ThreadPoolTest(); Gen<string>.ThreadPoolTest(); Gen<object>.ThreadPoolTest(); Gen<Guid>.ThreadPoolTest(); Gen<int[]>.ThreadPoolTest(); Gen<double[,]>.ThreadPoolTest(); Gen<string[][][]>.ThreadPoolTest(); Gen<object[,,,]>.ThreadPoolTest(); Gen<Guid[][,,,][]>.ThreadPoolTest(); 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)
./src/libraries/System.Private.CoreLib/src/System/MissingFieldException.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; namespace System { [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class MissingFieldException : MissingMemberException, ISerializable { public MissingFieldException() : base(SR.Arg_MissingFieldException) { HResult = HResults.COR_E_MISSINGFIELD; } public MissingFieldException(string? message) : base(message) { HResult = HResults.COR_E_MISSINGFIELD; } public MissingFieldException(string? message, Exception? inner) : base(message, inner) { HResult = HResults.COR_E_MISSINGFIELD; } public MissingFieldException(string? className, string? fieldName) { ClassName = className; MemberName = fieldName; } protected MissingFieldException(SerializationInfo info, StreamingContext context) : base(info, context) { } public override string Message { get { if (ClassName == null) { return base.Message; } else { // do any desired fixups to classname here. return SR.Format(SR.MissingField_Name, (Signature != null ? FormatSignature(Signature) + " " : "") + ClassName + "." + MemberName); } } } } }
// 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; namespace System { [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class MissingFieldException : MissingMemberException, ISerializable { public MissingFieldException() : base(SR.Arg_MissingFieldException) { HResult = HResults.COR_E_MISSINGFIELD; } public MissingFieldException(string? message) : base(message) { HResult = HResults.COR_E_MISSINGFIELD; } public MissingFieldException(string? message, Exception? inner) : base(message, inner) { HResult = HResults.COR_E_MISSINGFIELD; } public MissingFieldException(string? className, string? fieldName) { ClassName = className; MemberName = fieldName; } protected MissingFieldException(SerializationInfo info, StreamingContext context) : base(info, context) { } public override string Message { get { if (ClassName == null) { return base.Message; } else { // do any desired fixups to classname here. return SR.Format(SR.MissingField_Name, (Signature != null ? FormatSignature(Signature) + " " : "") + ClassName + "." + MemberName); } } } } }
-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/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDsa/ECDsaSignatureFormatTests.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.Security.Cryptography.Algorithms.Tests; using System.Security.Cryptography.Tests; using Xunit; namespace System.Security.Cryptography.EcDsa.Tests { [SkipOnPlatform(TestPlatforms.Browser, "Not supported on Browser")] public abstract class ECDsaSignatureFormatTests : DsaFamilySignatureFormatTests { protected override bool SupportsSha2 => true; private static KeyDescription CreateKey(ECCurve curve) { ECDsa dsa = ECDsaFactory.Create(curve); return new KeyDescription( dsa, $"{dsa.KeySize}-bit random key", dsa.KeySize); } private static KeyDescription OpenKey(in ECParameters ecParameters) { ECDsa dsa = ECDsaFactory.Create(); dsa.ImportParameters(ecParameters); return new KeyDescription( dsa, $"{dsa.KeySize}-bit static key", dsa.KeySize); } protected static IEnumerable<KeyDescription> LocalGenerateTestKeys() { if (ECDsaFactory.IsCurveValid(EccTestData.BrainpoolP160r1Key1.Curve.Oid)) { yield return OpenKey(EccTestData.BrainpoolP160r1Key1); } if (ECDsaFactory.IsCurveValid(ECCurve.NamedCurves.nistP384.Oid)) { yield return CreateKey(ECCurve.NamedCurves.nistP384); } yield return OpenKey(EccTestData.GetNistP521DiminishedCoordsParameters()); if (ECDsaFactory.ExplicitCurvesSupported) { yield return OpenKey(EccTestData.GetNistP256ReferenceKeyExplicit()); } } } public sealed class ECDsaArraySignatureFormatTests : ECDsaSignatureFormatTests { private static readonly KeyDescription[] s_keys = LocalGenerateTestKeys().ToArray(); protected override KeyDescription[] GenerateTestKeys() => s_keys; protected override bool IsArrayBased => true; protected override byte[] SignHash( KeyDescription key, byte[] hash, DSASignatureFormat signatureFormat) { return ((ECDsa)key.Key).SignHash(hash, signatureFormat); } protected override bool VerifyHash( KeyDescription key, byte[] hash, byte[] signature, DSASignatureFormat signatureFormat) { return ((ECDsa)key.Key).VerifyHash(hash, signature, signatureFormat); } protected override byte[] SignData( KeyDescription key, byte[] data, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { return ((ECDsa)key.Key).SignData(data, hashAlgorithm, signatureFormat); } protected override bool VerifyData( KeyDescription key, byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { return ((ECDsa)key.Key).VerifyData(data, signature, hashAlgorithm, signatureFormat); } } public sealed class ECDsaArrayOffsetSignatureFormatTests : ECDsaSignatureFormatTests { private static readonly KeyDescription[] s_keys = LocalGenerateTestKeys().ToArray(); protected override KeyDescription[] GenerateTestKeys() => s_keys; protected override bool IsArrayBased => true; protected override byte[] SignHash( KeyDescription key, byte[] hash, DSASignatureFormat signatureFormat) { return ((ECDsa)key.Key).SignHash(hash, signatureFormat); } protected override bool VerifyHash( KeyDescription key, byte[] hash, byte[] signature, DSASignatureFormat signatureFormat) { return ((ECDsa)key.Key).VerifyHash(hash, signature, signatureFormat); } protected override byte[] SignData( KeyDescription key, byte[] data, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { int offset = 0; int count = 0; if (data != null) { offset = 2; count = data.Length; byte[] bigger = new byte[count + 7]; Buffer.BlockCopy(data, 0, bigger, offset, count); data = bigger; } return ((ECDsa)key.Key).SignData(data, offset, count, hashAlgorithm, signatureFormat); } protected override bool VerifyData( KeyDescription key, byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { int offset = 0; int count = 0; if (data != null) { offset = 2; count = data.Length; byte[] bigger = new byte[count + 7]; Buffer.BlockCopy(data, 0, bigger, offset, count); data = bigger; } return ((ECDsa)key.Key).VerifyData(data, offset, count, signature, hashAlgorithm, signatureFormat); } [Fact] public void OffsetAndCountOutOfRange() { KeyDescription keyDescription = GetKey(); ECDsa key = (ECDsa)keyDescription.Key; HashAlgorithmName hash = HashAlgorithmName.SHA256; byte[] buffer = new byte[10]; foreach (DSASignatureFormat format in Enum.GetValues(typeof(DSASignatureFormat))) { AssertExtensions.Throws<ArgumentOutOfRangeException>( "offset", () => key.SignData(buffer, -1, buffer.Length, hash, format)); AssertExtensions.Throws<ArgumentOutOfRangeException>( "offset", () => key.SignData(buffer, buffer.Length + 1, 0, hash, format)); AssertExtensions.Throws<ArgumentOutOfRangeException>( "offset", () => key.VerifyData(buffer, -1, buffer.Length, buffer, hash, format)); AssertExtensions.Throws<ArgumentOutOfRangeException>( "offset", () => key.VerifyData(buffer, buffer.Length + 1, 0, buffer, hash, format)); AssertExtensions.Throws<ArgumentOutOfRangeException>( "count", () => key.SignData(buffer, 1, buffer.Length, hash, format)); AssertExtensions.Throws<ArgumentOutOfRangeException>( "count", () => key.SignData(buffer, 0, buffer.Length + 1, hash, format)); AssertExtensions.Throws<ArgumentOutOfRangeException>( "count", () => key.SignData(buffer, buffer.Length, 1, hash, format)); AssertExtensions.Throws<ArgumentOutOfRangeException>( "count", () => key.VerifyData(buffer, 1, buffer.Length, buffer, hash, format)); AssertExtensions.Throws<ArgumentOutOfRangeException>( "count", () => key.VerifyData(buffer, 0, buffer.Length + 1, buffer, hash, format)); AssertExtensions.Throws<ArgumentOutOfRangeException>( "count", () => key.VerifyData(buffer, buffer.Length, 1, buffer, hash, format)); } } } public sealed class ECDsaSpanSignatureFormatTests : ECDsaSignatureFormatTests { private static readonly KeyDescription[] s_keys = LocalGenerateTestKeys().ToArray(); protected override KeyDescription[] GenerateTestKeys() => s_keys; protected override bool IsArrayBased => false; protected override byte[] SignHash( KeyDescription key, byte[] hash, DSASignatureFormat signatureFormat) { ECDsa dsa = (ECDsa)key.Key; byte[] predictedMax = new byte[dsa.GetMaxSignatureSize(signatureFormat)]; Assert.True( dsa.TrySignHash(hash, predictedMax, signatureFormat, out int written), "TrySignHash with a GetMaxSignatureSize buffer"); if (signatureFormat == DSASignatureFormat.IeeeP1363FixedFieldConcatenation) { // GetMaxSignatureSize should be exactly accurate for P1363. Assert.Equal(predictedMax.Length, written); } if (written == predictedMax.Length) { return predictedMax; } return predictedMax.AsSpan(0, written).ToArray(); } protected override bool VerifyHash( KeyDescription key, byte[] hash, byte[] signature, DSASignatureFormat signatureFormat) { ReadOnlySpan<byte> readOnlyHash = hash; ReadOnlySpan<byte> readOnlySignature = signature; return ((ECDsa)key.Key).VerifyHash(readOnlyHash, readOnlySignature, signatureFormat); } protected override byte[] SignData( KeyDescription key, byte[] data, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { ECDsa dsa = (ECDsa)key.Key; byte[] predictedMax = new byte[dsa.GetMaxSignatureSize(signatureFormat)]; Assert.True( dsa.TrySignData(data, predictedMax, hashAlgorithm, signatureFormat, out int written), "TrySignData with a GetMaxSignatureSize buffer"); if (signatureFormat == DSASignatureFormat.IeeeP1363FixedFieldConcatenation) { // GetMaxSignatureSize should be exactly accurate for P1363. Assert.Equal(predictedMax.Length, written); } if (written == predictedMax.Length) { return predictedMax; } return predictedMax.AsSpan(0, written).ToArray(); } protected override bool VerifyData( KeyDescription key, byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { ReadOnlySpan<byte> readOnlyData = data; ReadOnlySpan<byte> readOnlySignature = signature; return ((ECDsa)key.Key).VerifyData(readOnlyData, readOnlySignature, hashAlgorithm, signatureFormat); } private static int GetExpectedSize(int fieldSizeInBits) { // In ECDSA field sizes aren't always byte-aligned (e.g. secp521r1). int fullBytes = Math.DivRem(fieldSizeInBits, 8, out int spareBits) + 1; int wiggle = 0; if (spareBits == 1) { // If there's only one spare bit (e.g. 521r1), we have a 50% chance to // drop a byte (then a 50% chance to gain it back), predict a byte loss. wiggle = -1; } else if (spareBits == 0) { // If we're byte aligned, then if the high bit is set (~50%) we gain a padding // byte, so predict a byte gain. wiggle = 1; // Also, as byte aligned, reduce the +1 from the original calculation fullBytes--; } int field1 = 2 + GetDerLengthLength(fullBytes) + fullBytes; int field2 = 2 + GetDerLengthLength(fullBytes + wiggle) + fullBytes + wiggle; int payload = field1 + field2; return 2 + GetDerLengthLength(payload) + payload; } [Fact] public void Rfc23279TrySignHashUnderMax() { KeyDescription keyDescription = GetKey(); ECDsa key = (ECDsa)keyDescription.Key; const DSASignatureFormat SignatureFormat = DSASignatureFormat.Rfc3279DerSequence; // Make secp521r1 (7/16 chance of being smaller) and mod-8 keys (3/4 chance of being smaller) // have the same 1-in-a-billion chance of failure. int retryCount = keyDescription.FieldSizeInBits % 8 == 1 ? 36 : 15; byte[] hash = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; int expectedSize = GetExpectedSize(keyDescription.FieldSizeInBits); int maxSize = key.GetMaxSignatureSize(DSASignatureFormat.Rfc3279DerSequence); Assert.True(expectedSize < maxSize, "expectedSize < maxSize"); byte[] signature = new byte[expectedSize]; for (int i = 0; i < retryCount; i++) { if (key.TrySignHash(hash, signature, SignatureFormat, out int written)) { return; } Assert.Equal(0, written); } Assert.True(false, $"TrySignHash eventually succeeds with a {expectedSize}/{maxSize}-byte destination"); } [Fact] public void Rfc23279TrySignDataUnderMax() { KeyDescription keyDescription = GetKey(); ECDsa key = (ECDsa)keyDescription.Key; const DSASignatureFormat SignatureFormat = DSASignatureFormat.Rfc3279DerSequence; // Make secp521r1 (7/16 chance of being smaller) and mod-8 keys (3/4 chance of being smaller) // have the same 1-in-a-billion chance of failure. int retryCount = keyDescription.FieldSizeInBits % 8 == 1 ? 36 : 15; HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA1; int expectedSize = GetExpectedSize(keyDescription.FieldSizeInBits); int maxSize = key.GetMaxSignatureSize(DSASignatureFormat.Rfc3279DerSequence); Assert.True(expectedSize < maxSize, "expectedSize < maxSize"); byte[] signature = new byte[expectedSize]; for (int i = 0; i < retryCount; i++) { if (key.TrySignData(Array.Empty<byte>(), signature, hashAlgorithm, SignatureFormat, out int written)) { return; } Assert.Equal(0, written); } Assert.True(false, $"TrySignData eventually succeeds with a {expectedSize}/{maxSize}-byte destination"); } } }
// 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.Security.Cryptography.Algorithms.Tests; using System.Security.Cryptography.Tests; using Xunit; namespace System.Security.Cryptography.EcDsa.Tests { [SkipOnPlatform(TestPlatforms.Browser, "Not supported on Browser")] public abstract class ECDsaSignatureFormatTests : DsaFamilySignatureFormatTests { protected override bool SupportsSha2 => true; private static KeyDescription CreateKey(ECCurve curve) { ECDsa dsa = ECDsaFactory.Create(curve); return new KeyDescription( dsa, $"{dsa.KeySize}-bit random key", dsa.KeySize); } private static KeyDescription OpenKey(in ECParameters ecParameters) { ECDsa dsa = ECDsaFactory.Create(); dsa.ImportParameters(ecParameters); return new KeyDescription( dsa, $"{dsa.KeySize}-bit static key", dsa.KeySize); } protected static IEnumerable<KeyDescription> LocalGenerateTestKeys() { if (ECDsaFactory.IsCurveValid(EccTestData.BrainpoolP160r1Key1.Curve.Oid)) { yield return OpenKey(EccTestData.BrainpoolP160r1Key1); } if (ECDsaFactory.IsCurveValid(ECCurve.NamedCurves.nistP384.Oid)) { yield return CreateKey(ECCurve.NamedCurves.nistP384); } yield return OpenKey(EccTestData.GetNistP521DiminishedCoordsParameters()); if (ECDsaFactory.ExplicitCurvesSupported) { yield return OpenKey(EccTestData.GetNistP256ReferenceKeyExplicit()); } } } public sealed class ECDsaArraySignatureFormatTests : ECDsaSignatureFormatTests { private static readonly KeyDescription[] s_keys = LocalGenerateTestKeys().ToArray(); protected override KeyDescription[] GenerateTestKeys() => s_keys; protected override bool IsArrayBased => true; protected override byte[] SignHash( KeyDescription key, byte[] hash, DSASignatureFormat signatureFormat) { return ((ECDsa)key.Key).SignHash(hash, signatureFormat); } protected override bool VerifyHash( KeyDescription key, byte[] hash, byte[] signature, DSASignatureFormat signatureFormat) { return ((ECDsa)key.Key).VerifyHash(hash, signature, signatureFormat); } protected override byte[] SignData( KeyDescription key, byte[] data, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { return ((ECDsa)key.Key).SignData(data, hashAlgorithm, signatureFormat); } protected override bool VerifyData( KeyDescription key, byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { return ((ECDsa)key.Key).VerifyData(data, signature, hashAlgorithm, signatureFormat); } } public sealed class ECDsaArrayOffsetSignatureFormatTests : ECDsaSignatureFormatTests { private static readonly KeyDescription[] s_keys = LocalGenerateTestKeys().ToArray(); protected override KeyDescription[] GenerateTestKeys() => s_keys; protected override bool IsArrayBased => true; protected override byte[] SignHash( KeyDescription key, byte[] hash, DSASignatureFormat signatureFormat) { return ((ECDsa)key.Key).SignHash(hash, signatureFormat); } protected override bool VerifyHash( KeyDescription key, byte[] hash, byte[] signature, DSASignatureFormat signatureFormat) { return ((ECDsa)key.Key).VerifyHash(hash, signature, signatureFormat); } protected override byte[] SignData( KeyDescription key, byte[] data, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { int offset = 0; int count = 0; if (data != null) { offset = 2; count = data.Length; byte[] bigger = new byte[count + 7]; Buffer.BlockCopy(data, 0, bigger, offset, count); data = bigger; } return ((ECDsa)key.Key).SignData(data, offset, count, hashAlgorithm, signatureFormat); } protected override bool VerifyData( KeyDescription key, byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { int offset = 0; int count = 0; if (data != null) { offset = 2; count = data.Length; byte[] bigger = new byte[count + 7]; Buffer.BlockCopy(data, 0, bigger, offset, count); data = bigger; } return ((ECDsa)key.Key).VerifyData(data, offset, count, signature, hashAlgorithm, signatureFormat); } [Fact] public void OffsetAndCountOutOfRange() { KeyDescription keyDescription = GetKey(); ECDsa key = (ECDsa)keyDescription.Key; HashAlgorithmName hash = HashAlgorithmName.SHA256; byte[] buffer = new byte[10]; foreach (DSASignatureFormat format in Enum.GetValues(typeof(DSASignatureFormat))) { AssertExtensions.Throws<ArgumentOutOfRangeException>( "offset", () => key.SignData(buffer, -1, buffer.Length, hash, format)); AssertExtensions.Throws<ArgumentOutOfRangeException>( "offset", () => key.SignData(buffer, buffer.Length + 1, 0, hash, format)); AssertExtensions.Throws<ArgumentOutOfRangeException>( "offset", () => key.VerifyData(buffer, -1, buffer.Length, buffer, hash, format)); AssertExtensions.Throws<ArgumentOutOfRangeException>( "offset", () => key.VerifyData(buffer, buffer.Length + 1, 0, buffer, hash, format)); AssertExtensions.Throws<ArgumentOutOfRangeException>( "count", () => key.SignData(buffer, 1, buffer.Length, hash, format)); AssertExtensions.Throws<ArgumentOutOfRangeException>( "count", () => key.SignData(buffer, 0, buffer.Length + 1, hash, format)); AssertExtensions.Throws<ArgumentOutOfRangeException>( "count", () => key.SignData(buffer, buffer.Length, 1, hash, format)); AssertExtensions.Throws<ArgumentOutOfRangeException>( "count", () => key.VerifyData(buffer, 1, buffer.Length, buffer, hash, format)); AssertExtensions.Throws<ArgumentOutOfRangeException>( "count", () => key.VerifyData(buffer, 0, buffer.Length + 1, buffer, hash, format)); AssertExtensions.Throws<ArgumentOutOfRangeException>( "count", () => key.VerifyData(buffer, buffer.Length, 1, buffer, hash, format)); } } } public sealed class ECDsaSpanSignatureFormatTests : ECDsaSignatureFormatTests { private static readonly KeyDescription[] s_keys = LocalGenerateTestKeys().ToArray(); protected override KeyDescription[] GenerateTestKeys() => s_keys; protected override bool IsArrayBased => false; protected override byte[] SignHash( KeyDescription key, byte[] hash, DSASignatureFormat signatureFormat) { ECDsa dsa = (ECDsa)key.Key; byte[] predictedMax = new byte[dsa.GetMaxSignatureSize(signatureFormat)]; Assert.True( dsa.TrySignHash(hash, predictedMax, signatureFormat, out int written), "TrySignHash with a GetMaxSignatureSize buffer"); if (signatureFormat == DSASignatureFormat.IeeeP1363FixedFieldConcatenation) { // GetMaxSignatureSize should be exactly accurate for P1363. Assert.Equal(predictedMax.Length, written); } if (written == predictedMax.Length) { return predictedMax; } return predictedMax.AsSpan(0, written).ToArray(); } protected override bool VerifyHash( KeyDescription key, byte[] hash, byte[] signature, DSASignatureFormat signatureFormat) { ReadOnlySpan<byte> readOnlyHash = hash; ReadOnlySpan<byte> readOnlySignature = signature; return ((ECDsa)key.Key).VerifyHash(readOnlyHash, readOnlySignature, signatureFormat); } protected override byte[] SignData( KeyDescription key, byte[] data, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { ECDsa dsa = (ECDsa)key.Key; byte[] predictedMax = new byte[dsa.GetMaxSignatureSize(signatureFormat)]; Assert.True( dsa.TrySignData(data, predictedMax, hashAlgorithm, signatureFormat, out int written), "TrySignData with a GetMaxSignatureSize buffer"); if (signatureFormat == DSASignatureFormat.IeeeP1363FixedFieldConcatenation) { // GetMaxSignatureSize should be exactly accurate for P1363. Assert.Equal(predictedMax.Length, written); } if (written == predictedMax.Length) { return predictedMax; } return predictedMax.AsSpan(0, written).ToArray(); } protected override bool VerifyData( KeyDescription key, byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { ReadOnlySpan<byte> readOnlyData = data; ReadOnlySpan<byte> readOnlySignature = signature; return ((ECDsa)key.Key).VerifyData(readOnlyData, readOnlySignature, hashAlgorithm, signatureFormat); } private static int GetExpectedSize(int fieldSizeInBits) { // In ECDSA field sizes aren't always byte-aligned (e.g. secp521r1). int fullBytes = Math.DivRem(fieldSizeInBits, 8, out int spareBits) + 1; int wiggle = 0; if (spareBits == 1) { // If there's only one spare bit (e.g. 521r1), we have a 50% chance to // drop a byte (then a 50% chance to gain it back), predict a byte loss. wiggle = -1; } else if (spareBits == 0) { // If we're byte aligned, then if the high bit is set (~50%) we gain a padding // byte, so predict a byte gain. wiggle = 1; // Also, as byte aligned, reduce the +1 from the original calculation fullBytes--; } int field1 = 2 + GetDerLengthLength(fullBytes) + fullBytes; int field2 = 2 + GetDerLengthLength(fullBytes + wiggle) + fullBytes + wiggle; int payload = field1 + field2; return 2 + GetDerLengthLength(payload) + payload; } [Fact] public void Rfc23279TrySignHashUnderMax() { KeyDescription keyDescription = GetKey(); ECDsa key = (ECDsa)keyDescription.Key; const DSASignatureFormat SignatureFormat = DSASignatureFormat.Rfc3279DerSequence; // Make secp521r1 (7/16 chance of being smaller) and mod-8 keys (3/4 chance of being smaller) // have the same 1-in-a-billion chance of failure. int retryCount = keyDescription.FieldSizeInBits % 8 == 1 ? 36 : 15; byte[] hash = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; int expectedSize = GetExpectedSize(keyDescription.FieldSizeInBits); int maxSize = key.GetMaxSignatureSize(DSASignatureFormat.Rfc3279DerSequence); Assert.True(expectedSize < maxSize, "expectedSize < maxSize"); byte[] signature = new byte[expectedSize]; for (int i = 0; i < retryCount; i++) { if (key.TrySignHash(hash, signature, SignatureFormat, out int written)) { return; } Assert.Equal(0, written); } Assert.True(false, $"TrySignHash eventually succeeds with a {expectedSize}/{maxSize}-byte destination"); } [Fact] public void Rfc23279TrySignDataUnderMax() { KeyDescription keyDescription = GetKey(); ECDsa key = (ECDsa)keyDescription.Key; const DSASignatureFormat SignatureFormat = DSASignatureFormat.Rfc3279DerSequence; // Make secp521r1 (7/16 chance of being smaller) and mod-8 keys (3/4 chance of being smaller) // have the same 1-in-a-billion chance of failure. int retryCount = keyDescription.FieldSizeInBits % 8 == 1 ? 36 : 15; HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA1; int expectedSize = GetExpectedSize(keyDescription.FieldSizeInBits); int maxSize = key.GetMaxSignatureSize(DSASignatureFormat.Rfc3279DerSequence); Assert.True(expectedSize < maxSize, "expectedSize < maxSize"); byte[] signature = new byte[expectedSize]; for (int i = 0; i < retryCount; i++) { if (key.TrySignData(Array.Empty<byte>(), signature, hashAlgorithm, SignatureFormat, out int written)) { return; } Assert.Equal(0, written); } Assert.True(false, $"TrySignData eventually succeeds with a {expectedSize}/{maxSize}-byte destination"); } } }
-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/Variance/IL/IsInst003.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 Base {} public class Sub : Base {} public class GBase<T> {} public class GSubT<T> : GBase<T> {} public class GTU<T,U> : IPlusT<T>, IMinusT<U>, IPlusTMinusU<T,U> {} public class GTArrUArr<T,U> : IPlusT<T[]>, IMinusT<U[]>, IPlusTMinusU<T[],U[]> {} public class GRefTRefU<T,U> : IPlusT<IPlusT<T>>, IPlusT<IMinusT<U>>, IPlusTMinusU<IPlusT<T>, IPlusT<U>> {} public class GRefTArrRefUArr<T,U> : IPlusT<IPlusT<T[]>>, IPlusT<IMinusT<U[]>>, IPlusTMinusU<IPlusT<T[]>,IPlusT<U[]>> {} public class GArrRefTArrRefU<T,U> : IPlusT<IPlusT<T>[]>, IPlusT<IMinusT<U>[]>, IPlusTMinusU<IPlusT<T>[],IPlusT<U>[]> {} public class TestClass { static int iTestCount= 0; static int iErrorCount= 0; static int iExitCode = 101; public static void Eval(string location, bool exp) { ++iTestCount; if ( !(exp)) { iErrorCount++; Console.WriteLine("Test Failed at location: {0} @ count {1} ", location, iTestCount); } } public static bool UIsInstT<T,U>(bool expected) { try { return (expected == (Activator.CreateInstance(typeof(U)) is T)); } catch(Exception E) { Console.WriteLine("Unexpected Exception {0}, with T = {1} and U = {2}", E, typeof(T).Name, typeof(U).Name); return false; } } private static bool RunTests() { Eval("Test001", UIsInstT<IPlusT<Sub>, GTU<Base,Sub>>(false)); Eval("Test002", UIsInstT<IMinusT<Base>, GTU<Base,Sub>>(false)); Eval("Test003", UIsInstT<IPlusTMinusU<Sub,Base>, GTU<Base,Sub>>(false)); Eval("Test004", UIsInstT<IPlusT<Sub[]>, GTU<Base[],Sub[]>>(false)); Eval("Test005", UIsInstT<IMinusT<Base[]>, GTU<Base[],Sub[]>>(false)); Eval("Test006", UIsInstT<IPlusTMinusU<Sub[],Base[]>, GTU<Base[],Sub[]>>(false)); Eval("Test007", UIsInstT<IPlusT<GSubT<int>>, GTU<GBase<int>,GSubT<string>>>(false)); Eval("Test008", UIsInstT<IMinusT<GBase<string>>, GTU<GBase<int>,GSubT<string>>>(false)); Eval("Test009", UIsInstT<IPlusTMinusU<GSubT<int>,GBase<string>>, GTU<GBase<int>,GSubT<string>>>(false)); Eval("Test010", UIsInstT<IPlusT<GSubT<int>[]>, GTU<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test011", UIsInstT<IMinusT<GBase<string>[]>, GTU<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test012", UIsInstT<IPlusTMinusU<GSubT<int>[],GBase<string>[]>, GTU<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test101", UIsInstT<IPlusT<Sub[]>, GTArrUArr<Base,Sub>>(false)); Eval("Test102", UIsInstT<IMinusT<Base[]>, GTArrUArr<Base,Sub>>(false)); Eval("Test103", UIsInstT<IPlusTMinusU<Sub[],Base[]>, GTArrUArr<Base,Sub>>(false)); Eval("Test104", UIsInstT<IPlusT<Sub[][]>, GTArrUArr<Base[],Sub[]>>(false)); Eval("Test105", UIsInstT<IMinusT<Base[][]>, GTArrUArr<Base[],Sub[]>>(false)); Eval("Test106", UIsInstT<IPlusTMinusU<Sub[][],Base[][]>, GTArrUArr<Base[],Sub[]>>(false)); Eval("Test107", UIsInstT<IPlusT<GSubT<int>[]>, GTArrUArr<GBase<int>,GSubT<string>>>(false)); Eval("Test108", UIsInstT<IMinusT<GBase<string>[]>, GTArrUArr<GBase<int>,GSubT<string>>>(false)); Eval("Test109", UIsInstT<IPlusTMinusU<GSubT<int>[],GBase<string>[]>, GTArrUArr<GBase<int>,GSubT<string>>>(false)); Eval("Test110", UIsInstT<IPlusT<GSubT<int>[][]>, GTArrUArr<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test111", UIsInstT<IMinusT<GBase<string>[][]>, GTArrUArr<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test112", UIsInstT<IPlusTMinusU<GSubT<int>[][],GBase<string>[][]>, GTArrUArr<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test201", UIsInstT<IPlusT<IPlusT<Sub>>, GRefTRefU<Base,Sub>>(false)); Eval("Test202", UIsInstT<IPlusT<IMinusT<Base>>, GRefTRefU<Base,Sub>>(false)); Eval("Test203", UIsInstT<IPlusTMinusU<IPlusT<Sub>,IPlusT<Base>>, GRefTRefU<Base,Sub>>(false)); Eval("Test204", UIsInstT<IPlusT<IPlusT<Sub[]>>, GRefTRefU<Base[],Sub[]>>(false)); Eval("Test205", UIsInstT<IPlusT<IMinusT<Base[]>>, GRefTRefU<Base[],Sub[]>>(false)); Eval("Test206", UIsInstT<IPlusTMinusU<IPlusT<Sub[]>,IPlusT<Base[]>>, GRefTRefU<Base[],Sub[]>>(false)); Eval("Test207", UIsInstT<IPlusT<IPlusT<GSubT<int>>>, GRefTRefU<GBase<int>,GSubT<string>>>(false)); Eval("Test208", UIsInstT<IPlusT<IMinusT<GBase<string>>>, GRefTRefU<GBase<int>,GSubT<string>>>(false)); Eval("Test209", UIsInstT<IPlusTMinusU<IPlusT<GSubT<int>>,IPlusT<GBase<string>>>, GRefTRefU<GBase<int>,GSubT<string>>>(false)); Eval("Test210", UIsInstT<IPlusT<IPlusT<GSubT<int>[]>>, GRefTRefU<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test211", UIsInstT<IPlusT<IMinusT<GBase<string>[]>>, GRefTRefU<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test212", UIsInstT<IPlusTMinusU<IPlusT<GSubT<int>[]>,IPlusT<GBase<string>[]>>, GRefTRefU<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test301", UIsInstT<IPlusT<IPlusT<Sub[]>>, GRefTArrRefUArr<Base,Sub>>(false)); Eval("Test302", UIsInstT<IPlusT<IMinusT<Base[]>>, GRefTArrRefUArr<Base,Sub>>(false)); Eval("Test303", UIsInstT<IPlusTMinusU<IPlusT<Sub[]>,IPlusT<Base[]>>, GRefTArrRefUArr<Base,Sub>>(false)); Eval("Test304", UIsInstT<IPlusT<IPlusT<Sub[][]>>, GRefTArrRefUArr<Base[],Sub[]>>(false)); Eval("Test305", UIsInstT<IPlusT<IMinusT<Base[][]>>, GRefTArrRefUArr<Base[],Sub[]>>(false)); Eval("Test306", UIsInstT<IPlusTMinusU<IPlusT<Sub[][]>,IPlusT<Base[][]>>, GRefTArrRefUArr<Base[],Sub[]>>(false)); Eval("Test307", UIsInstT<IPlusT<IPlusT<GSubT<int>[]>>, GRefTArrRefUArr<GBase<int>,GSubT<string>>>(false)); Eval("Test308", UIsInstT<IPlusT<IMinusT<GBase<string>[]>>, GRefTArrRefUArr<GBase<int>,GSubT<string>>>(false)); Eval("Test309", UIsInstT<IPlusTMinusU<IPlusT<GSubT<int>[]>,IPlusT<GBase<string>[]>>, GRefTArrRefUArr<GBase<int>,GSubT<string>>>(false)); Eval("Test310", UIsInstT<IPlusT<IPlusT<GSubT<int>[][]>>, GRefTArrRefUArr<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test311", UIsInstT<IPlusT<IMinusT<GBase<string>[][]>>, GRefTArrRefUArr<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test312", UIsInstT<IPlusTMinusU<IPlusT<GSubT<int>[][]>,IPlusT<GBase<string>[][]>>, GRefTArrRefUArr<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test401", UIsInstT<IPlusT<IPlusT<Sub>[]>, GArrRefTArrRefU<Base,Sub>>(false)); Eval("Test402", UIsInstT<IPlusT<IMinusT<Base>[]>, GArrRefTArrRefU<Base,Sub>>(false)); Eval("Test403", UIsInstT<IPlusTMinusU<IPlusT<Sub>[],IPlusT<Base>[]>, GArrRefTArrRefU<Base,Sub>>(false)); Eval("Test404", UIsInstT<IPlusT<IPlusT<Sub[,]>[]>, GArrRefTArrRefU<Base[,],Sub[,]>>(false)); Eval("Test405", UIsInstT<IPlusT<IMinusT<Base[,]>[]>, GArrRefTArrRefU<Base[,],Sub[,]>>(false)); Eval("Test406", UIsInstT<IPlusTMinusU<IPlusT<Sub[,]>[],IPlusT<Base[,]>[]>, GArrRefTArrRefU<Base[,],Sub[,]>>(false)); Eval("Test407", UIsInstT<IPlusT<IPlusT<GSubT<int>>[]>, GArrRefTArrRefU<GBase<int>,GSubT<string>>>(false)); Eval("Test408", UIsInstT<IPlusT<IMinusT<GBase<string>>[]>, GArrRefTArrRefU<GBase<int>,GSubT<string>>>(false)); Eval("Test409", UIsInstT<IPlusTMinusU<IPlusT<GSubT<int>>[],IPlusT<GBase<string>>[]>, GArrRefTArrRefU<GBase<int>,GSubT<string>>>(false)); Eval("Test410", UIsInstT<IPlusT<IPlusT<GSubT<int>[]>[]>, GArrRefTArrRefU<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test411", UIsInstT<IPlusT<IMinusT<GBase<string>[]>[]>, GArrRefTArrRefU<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test412", UIsInstT<IPlusTMinusU<IPlusT<GSubT<int>[]>[],IPlusT<GBase<string>[]>[]>, GArrRefTArrRefU<GBase<int>[],GSubT<string>[]>>(false)); if( iErrorCount > 0 ) { Console.WriteLine( "Total test cases: " + iTestCount + " Failed test cases: " + iErrorCount ); return false; } else { Console.WriteLine( "Total test cases: " + iTestCount ); return true; } } public static int Main(String [] args) { if( RunTests() ) { iExitCode = 100; Console.WriteLine( "All test cases passed" ); } else { iExitCode = 101; Console.WriteLine( "Test failed" ); } return iExitCode; } }
// 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 Base {} public class Sub : Base {} public class GBase<T> {} public class GSubT<T> : GBase<T> {} public class GTU<T,U> : IPlusT<T>, IMinusT<U>, IPlusTMinusU<T,U> {} public class GTArrUArr<T,U> : IPlusT<T[]>, IMinusT<U[]>, IPlusTMinusU<T[],U[]> {} public class GRefTRefU<T,U> : IPlusT<IPlusT<T>>, IPlusT<IMinusT<U>>, IPlusTMinusU<IPlusT<T>, IPlusT<U>> {} public class GRefTArrRefUArr<T,U> : IPlusT<IPlusT<T[]>>, IPlusT<IMinusT<U[]>>, IPlusTMinusU<IPlusT<T[]>,IPlusT<U[]>> {} public class GArrRefTArrRefU<T,U> : IPlusT<IPlusT<T>[]>, IPlusT<IMinusT<U>[]>, IPlusTMinusU<IPlusT<T>[],IPlusT<U>[]> {} public class TestClass { static int iTestCount= 0; static int iErrorCount= 0; static int iExitCode = 101; public static void Eval(string location, bool exp) { ++iTestCount; if ( !(exp)) { iErrorCount++; Console.WriteLine("Test Failed at location: {0} @ count {1} ", location, iTestCount); } } public static bool UIsInstT<T,U>(bool expected) { try { return (expected == (Activator.CreateInstance(typeof(U)) is T)); } catch(Exception E) { Console.WriteLine("Unexpected Exception {0}, with T = {1} and U = {2}", E, typeof(T).Name, typeof(U).Name); return false; } } private static bool RunTests() { Eval("Test001", UIsInstT<IPlusT<Sub>, GTU<Base,Sub>>(false)); Eval("Test002", UIsInstT<IMinusT<Base>, GTU<Base,Sub>>(false)); Eval("Test003", UIsInstT<IPlusTMinusU<Sub,Base>, GTU<Base,Sub>>(false)); Eval("Test004", UIsInstT<IPlusT<Sub[]>, GTU<Base[],Sub[]>>(false)); Eval("Test005", UIsInstT<IMinusT<Base[]>, GTU<Base[],Sub[]>>(false)); Eval("Test006", UIsInstT<IPlusTMinusU<Sub[],Base[]>, GTU<Base[],Sub[]>>(false)); Eval("Test007", UIsInstT<IPlusT<GSubT<int>>, GTU<GBase<int>,GSubT<string>>>(false)); Eval("Test008", UIsInstT<IMinusT<GBase<string>>, GTU<GBase<int>,GSubT<string>>>(false)); Eval("Test009", UIsInstT<IPlusTMinusU<GSubT<int>,GBase<string>>, GTU<GBase<int>,GSubT<string>>>(false)); Eval("Test010", UIsInstT<IPlusT<GSubT<int>[]>, GTU<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test011", UIsInstT<IMinusT<GBase<string>[]>, GTU<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test012", UIsInstT<IPlusTMinusU<GSubT<int>[],GBase<string>[]>, GTU<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test101", UIsInstT<IPlusT<Sub[]>, GTArrUArr<Base,Sub>>(false)); Eval("Test102", UIsInstT<IMinusT<Base[]>, GTArrUArr<Base,Sub>>(false)); Eval("Test103", UIsInstT<IPlusTMinusU<Sub[],Base[]>, GTArrUArr<Base,Sub>>(false)); Eval("Test104", UIsInstT<IPlusT<Sub[][]>, GTArrUArr<Base[],Sub[]>>(false)); Eval("Test105", UIsInstT<IMinusT<Base[][]>, GTArrUArr<Base[],Sub[]>>(false)); Eval("Test106", UIsInstT<IPlusTMinusU<Sub[][],Base[][]>, GTArrUArr<Base[],Sub[]>>(false)); Eval("Test107", UIsInstT<IPlusT<GSubT<int>[]>, GTArrUArr<GBase<int>,GSubT<string>>>(false)); Eval("Test108", UIsInstT<IMinusT<GBase<string>[]>, GTArrUArr<GBase<int>,GSubT<string>>>(false)); Eval("Test109", UIsInstT<IPlusTMinusU<GSubT<int>[],GBase<string>[]>, GTArrUArr<GBase<int>,GSubT<string>>>(false)); Eval("Test110", UIsInstT<IPlusT<GSubT<int>[][]>, GTArrUArr<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test111", UIsInstT<IMinusT<GBase<string>[][]>, GTArrUArr<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test112", UIsInstT<IPlusTMinusU<GSubT<int>[][],GBase<string>[][]>, GTArrUArr<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test201", UIsInstT<IPlusT<IPlusT<Sub>>, GRefTRefU<Base,Sub>>(false)); Eval("Test202", UIsInstT<IPlusT<IMinusT<Base>>, GRefTRefU<Base,Sub>>(false)); Eval("Test203", UIsInstT<IPlusTMinusU<IPlusT<Sub>,IPlusT<Base>>, GRefTRefU<Base,Sub>>(false)); Eval("Test204", UIsInstT<IPlusT<IPlusT<Sub[]>>, GRefTRefU<Base[],Sub[]>>(false)); Eval("Test205", UIsInstT<IPlusT<IMinusT<Base[]>>, GRefTRefU<Base[],Sub[]>>(false)); Eval("Test206", UIsInstT<IPlusTMinusU<IPlusT<Sub[]>,IPlusT<Base[]>>, GRefTRefU<Base[],Sub[]>>(false)); Eval("Test207", UIsInstT<IPlusT<IPlusT<GSubT<int>>>, GRefTRefU<GBase<int>,GSubT<string>>>(false)); Eval("Test208", UIsInstT<IPlusT<IMinusT<GBase<string>>>, GRefTRefU<GBase<int>,GSubT<string>>>(false)); Eval("Test209", UIsInstT<IPlusTMinusU<IPlusT<GSubT<int>>,IPlusT<GBase<string>>>, GRefTRefU<GBase<int>,GSubT<string>>>(false)); Eval("Test210", UIsInstT<IPlusT<IPlusT<GSubT<int>[]>>, GRefTRefU<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test211", UIsInstT<IPlusT<IMinusT<GBase<string>[]>>, GRefTRefU<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test212", UIsInstT<IPlusTMinusU<IPlusT<GSubT<int>[]>,IPlusT<GBase<string>[]>>, GRefTRefU<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test301", UIsInstT<IPlusT<IPlusT<Sub[]>>, GRefTArrRefUArr<Base,Sub>>(false)); Eval("Test302", UIsInstT<IPlusT<IMinusT<Base[]>>, GRefTArrRefUArr<Base,Sub>>(false)); Eval("Test303", UIsInstT<IPlusTMinusU<IPlusT<Sub[]>,IPlusT<Base[]>>, GRefTArrRefUArr<Base,Sub>>(false)); Eval("Test304", UIsInstT<IPlusT<IPlusT<Sub[][]>>, GRefTArrRefUArr<Base[],Sub[]>>(false)); Eval("Test305", UIsInstT<IPlusT<IMinusT<Base[][]>>, GRefTArrRefUArr<Base[],Sub[]>>(false)); Eval("Test306", UIsInstT<IPlusTMinusU<IPlusT<Sub[][]>,IPlusT<Base[][]>>, GRefTArrRefUArr<Base[],Sub[]>>(false)); Eval("Test307", UIsInstT<IPlusT<IPlusT<GSubT<int>[]>>, GRefTArrRefUArr<GBase<int>,GSubT<string>>>(false)); Eval("Test308", UIsInstT<IPlusT<IMinusT<GBase<string>[]>>, GRefTArrRefUArr<GBase<int>,GSubT<string>>>(false)); Eval("Test309", UIsInstT<IPlusTMinusU<IPlusT<GSubT<int>[]>,IPlusT<GBase<string>[]>>, GRefTArrRefUArr<GBase<int>,GSubT<string>>>(false)); Eval("Test310", UIsInstT<IPlusT<IPlusT<GSubT<int>[][]>>, GRefTArrRefUArr<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test311", UIsInstT<IPlusT<IMinusT<GBase<string>[][]>>, GRefTArrRefUArr<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test312", UIsInstT<IPlusTMinusU<IPlusT<GSubT<int>[][]>,IPlusT<GBase<string>[][]>>, GRefTArrRefUArr<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test401", UIsInstT<IPlusT<IPlusT<Sub>[]>, GArrRefTArrRefU<Base,Sub>>(false)); Eval("Test402", UIsInstT<IPlusT<IMinusT<Base>[]>, GArrRefTArrRefU<Base,Sub>>(false)); Eval("Test403", UIsInstT<IPlusTMinusU<IPlusT<Sub>[],IPlusT<Base>[]>, GArrRefTArrRefU<Base,Sub>>(false)); Eval("Test404", UIsInstT<IPlusT<IPlusT<Sub[,]>[]>, GArrRefTArrRefU<Base[,],Sub[,]>>(false)); Eval("Test405", UIsInstT<IPlusT<IMinusT<Base[,]>[]>, GArrRefTArrRefU<Base[,],Sub[,]>>(false)); Eval("Test406", UIsInstT<IPlusTMinusU<IPlusT<Sub[,]>[],IPlusT<Base[,]>[]>, GArrRefTArrRefU<Base[,],Sub[,]>>(false)); Eval("Test407", UIsInstT<IPlusT<IPlusT<GSubT<int>>[]>, GArrRefTArrRefU<GBase<int>,GSubT<string>>>(false)); Eval("Test408", UIsInstT<IPlusT<IMinusT<GBase<string>>[]>, GArrRefTArrRefU<GBase<int>,GSubT<string>>>(false)); Eval("Test409", UIsInstT<IPlusTMinusU<IPlusT<GSubT<int>>[],IPlusT<GBase<string>>[]>, GArrRefTArrRefU<GBase<int>,GSubT<string>>>(false)); Eval("Test410", UIsInstT<IPlusT<IPlusT<GSubT<int>[]>[]>, GArrRefTArrRefU<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test411", UIsInstT<IPlusT<IMinusT<GBase<string>[]>[]>, GArrRefTArrRefU<GBase<int>[],GSubT<string>[]>>(false)); Eval("Test412", UIsInstT<IPlusTMinusU<IPlusT<GSubT<int>[]>[],IPlusT<GBase<string>[]>[]>, GArrRefTArrRefU<GBase<int>[],GSubT<string>[]>>(false)); if( iErrorCount > 0 ) { Console.WriteLine( "Total test cases: " + iTestCount + " Failed test cases: " + iErrorCount ); return false; } else { Console.WriteLine( "Total test cases: " + iTestCount ); return true; } } public static int Main(String [] args) { if( RunTests() ) { iExitCode = 100; Console.WriteLine( "All test cases passed" ); } else { iExitCode = 101; Console.WriteLine( "Test failed" ); } return iExitCode; } }
-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.Parallel/src/System/Linq/Parallel/Utils/ReverseComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ReverseComparer.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace System.Linq.Parallel { /// <summary> /// Comparer that wraps another comparer, and flips the result of each comparison to the /// opposite answer. /// </summary> /// <typeparam name="T"></typeparam> internal sealed class ReverseComparer<T> : IComparer<T> { private readonly IComparer<T> _comparer; internal ReverseComparer(IComparer<T> comparer) { _comparer = comparer; } public int Compare(T? x, T? y) { return _comparer.Compare(y, x); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ReverseComparer.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace System.Linq.Parallel { /// <summary> /// Comparer that wraps another comparer, and flips the result of each comparison to the /// opposite answer. /// </summary> /// <typeparam name="T"></typeparam> internal sealed class ReverseComparer<T> : IComparer<T> { private readonly IComparer<T> _comparer; internal ReverseComparer(IComparer<T> comparer) { _comparer = comparer; } public int Compare(T? x, T? y) { return _comparer.Compare(y, x); } } }
-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/tests/FunctionalTests/Regex.Count.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.Diagnostics; using System.Threading.Tasks; using Xunit; namespace System.Text.RegularExpressions.Tests { public class RegexCountTests { [Theory] [MemberData(nameof(Count_ReturnsExpectedCount_TestData))] public async Task Count_ReturnsExpectedCount(RegexEngine engine, string pattern, string input, RegexOptions options, int expectedCount) { Regex r = await RegexHelpers.GetRegexAsync(engine, pattern, options); Assert.Equal(expectedCount, r.Count(input)); Assert.Equal(r.Count(input), r.Matches(input).Count); if (options == RegexOptions.None && engine == RegexEngine.Interpreter) { Assert.Equal(expectedCount, Regex.Count(input, pattern)); } switch (engine) { case RegexEngine.Interpreter: case RegexEngine.Compiled: case RegexEngine.NonBacktracking: RegexOptions engineOptions = RegexHelpers.OptionsFromEngine(engine); Assert.Equal(expectedCount, Regex.Count(input, pattern, options | engineOptions)); Assert.Equal(expectedCount, Regex.Count(input, pattern, options | engineOptions, Regex.InfiniteMatchTimeout)); break; } } public static IEnumerable<object[]> Count_ReturnsExpectedCount_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, @"", "", RegexOptions.None, 1 }; yield return new object[] { engine, @"", "a", RegexOptions.None, 2 }; yield return new object[] { engine, @"", "ab", RegexOptions.None, 3 }; yield return new object[] { engine, @"\w", "", RegexOptions.None, 0 }; yield return new object[] { engine, @"\w", "a", RegexOptions.None, 1 }; yield return new object[] { engine, @"\w", "ab", RegexOptions.None, 2 }; yield return new object[] { engine, @"\b\w+\b", "abc def ghi jkl", RegexOptions.None, 4 }; yield return new object[] { engine, @"A", "", RegexOptions.IgnoreCase, 0 }; yield return new object[] { engine, @"A", "a", RegexOptions.IgnoreCase, 1 }; yield return new object[] { engine, @"A", "aAaA", RegexOptions.IgnoreCase, 4 }; yield return new object[] { engine, @".", "\n\n\n", RegexOptions.None, 0 }; yield return new object[] { engine, @".", "\n\n\n", RegexOptions.Singleline, 3 }; } } [Fact] public void Count_InvalidArguments_Throws() { // input is null AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Count(null)); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Count(null, @"pattern")); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Count(null, @"pattern", RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Count(null, @"pattern", RegexOptions.None, TimeSpan.FromMilliseconds(1))); // pattern is null AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Count("input", null)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Count("input", null, RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Count("input", null, RegexOptions.None, TimeSpan.FromMilliseconds(1))); // pattern is invalid #pragma warning disable RE0001 // invalid regex pattern AssertExtensions.Throws<RegexParseException>(() => Regex.Count("input", @"[abc")); AssertExtensions.Throws<RegexParseException>(() => Regex.Count("input", @"[abc", RegexOptions.None)); AssertExtensions.Throws<RegexParseException>(() => Regex.Count("input", @"[abc", RegexOptions.None, TimeSpan.FromMilliseconds(1))); #pragma warning restore RE0001 // options is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => Regex.Count("input", @"[abc]", (RegexOptions)(-1))); AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => Regex.Count("input", @"[abc]", (RegexOptions)(-1), TimeSpan.FromMilliseconds(1))); // matchTimeout is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("matchTimeout", () => Regex.Count("input", @"[abc]", RegexOptions.None, TimeSpan.FromMilliseconds(-2))); } [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Count_Timeout_ThrowsAfterTooLongExecution(RegexEngine engine) { if (RegexHelpers.IsNonBacktracking(engine)) { // Test relies on backtracking taking a long time return; } const string Pattern = @"^(\w+\s?)*$"; const string Input = "An input string that takes a very very very very very very very very very very very long time!"; Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern, RegexOptions.None, TimeSpan.FromMilliseconds(1)); Stopwatch sw = Stopwatch.StartNew(); Assert.Throws<RegexMatchTimeoutException>(() => r.Count(Input)); Assert.InRange(sw.Elapsed.TotalSeconds, 0, 10); // arbitrary upper bound that should be well above what's needed with a 1ms timeout switch (engine) { case RegexEngine.Interpreter: case RegexEngine.Compiled: sw = Stopwatch.StartNew(); Assert.Throws<RegexMatchTimeoutException>(() => Regex.Count(Input, Pattern, RegexHelpers.OptionsFromEngine(engine), TimeSpan.FromMilliseconds(1))); Assert.InRange(sw.Elapsed.TotalSeconds, 0, 10); // arbitrary upper bound that should be well above what's needed with a 1ms timeout break; } } } }
// 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.Threading.Tasks; using Xunit; namespace System.Text.RegularExpressions.Tests { public class RegexCountTests { [Theory] [MemberData(nameof(Count_ReturnsExpectedCount_TestData))] public async Task Count_ReturnsExpectedCount(RegexEngine engine, string pattern, string input, RegexOptions options, int expectedCount) { Regex r = await RegexHelpers.GetRegexAsync(engine, pattern, options); Assert.Equal(expectedCount, r.Count(input)); Assert.Equal(r.Count(input), r.Matches(input).Count); if (options == RegexOptions.None && engine == RegexEngine.Interpreter) { Assert.Equal(expectedCount, Regex.Count(input, pattern)); } switch (engine) { case RegexEngine.Interpreter: case RegexEngine.Compiled: case RegexEngine.NonBacktracking: RegexOptions engineOptions = RegexHelpers.OptionsFromEngine(engine); Assert.Equal(expectedCount, Regex.Count(input, pattern, options | engineOptions)); Assert.Equal(expectedCount, Regex.Count(input, pattern, options | engineOptions, Regex.InfiniteMatchTimeout)); break; } } public static IEnumerable<object[]> Count_ReturnsExpectedCount_TestData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { yield return new object[] { engine, @"", "", RegexOptions.None, 1 }; yield return new object[] { engine, @"", "a", RegexOptions.None, 2 }; yield return new object[] { engine, @"", "ab", RegexOptions.None, 3 }; yield return new object[] { engine, @"\w", "", RegexOptions.None, 0 }; yield return new object[] { engine, @"\w", "a", RegexOptions.None, 1 }; yield return new object[] { engine, @"\w", "ab", RegexOptions.None, 2 }; yield return new object[] { engine, @"\b\w+\b", "abc def ghi jkl", RegexOptions.None, 4 }; yield return new object[] { engine, @"A", "", RegexOptions.IgnoreCase, 0 }; yield return new object[] { engine, @"A", "a", RegexOptions.IgnoreCase, 1 }; yield return new object[] { engine, @"A", "aAaA", RegexOptions.IgnoreCase, 4 }; yield return new object[] { engine, @".", "\n\n\n", RegexOptions.None, 0 }; yield return new object[] { engine, @".", "\n\n\n", RegexOptions.Singleline, 3 }; } } [Fact] public void Count_InvalidArguments_Throws() { // input is null AssertExtensions.Throws<ArgumentNullException>("input", () => new Regex("pattern").Count(null)); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Count(null, @"pattern")); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Count(null, @"pattern", RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("input", () => Regex.Count(null, @"pattern", RegexOptions.None, TimeSpan.FromMilliseconds(1))); // pattern is null AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Count("input", null)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Count("input", null, RegexOptions.None)); AssertExtensions.Throws<ArgumentNullException>("pattern", () => Regex.Count("input", null, RegexOptions.None, TimeSpan.FromMilliseconds(1))); // pattern is invalid #pragma warning disable RE0001 // invalid regex pattern AssertExtensions.Throws<RegexParseException>(() => Regex.Count("input", @"[abc")); AssertExtensions.Throws<RegexParseException>(() => Regex.Count("input", @"[abc", RegexOptions.None)); AssertExtensions.Throws<RegexParseException>(() => Regex.Count("input", @"[abc", RegexOptions.None, TimeSpan.FromMilliseconds(1))); #pragma warning restore RE0001 // options is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => Regex.Count("input", @"[abc]", (RegexOptions)(-1))); AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => Regex.Count("input", @"[abc]", (RegexOptions)(-1), TimeSpan.FromMilliseconds(1))); // matchTimeout is invalid AssertExtensions.Throws<ArgumentOutOfRangeException>("matchTimeout", () => Regex.Count("input", @"[abc]", RegexOptions.None, TimeSpan.FromMilliseconds(-2))); } [Theory] [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Count_Timeout_ThrowsAfterTooLongExecution(RegexEngine engine) { if (RegexHelpers.IsNonBacktracking(engine)) { // Test relies on backtracking taking a long time return; } const string Pattern = @"^(\w+\s?)*$"; const string Input = "An input string that takes a very very very very very very very very very very very long time!"; Regex r = await RegexHelpers.GetRegexAsync(engine, Pattern, RegexOptions.None, TimeSpan.FromMilliseconds(1)); Stopwatch sw = Stopwatch.StartNew(); Assert.Throws<RegexMatchTimeoutException>(() => r.Count(Input)); Assert.InRange(sw.Elapsed.TotalSeconds, 0, 10); // arbitrary upper bound that should be well above what's needed with a 1ms timeout switch (engine) { case RegexEngine.Interpreter: case RegexEngine.Compiled: sw = Stopwatch.StartNew(); Assert.Throws<RegexMatchTimeoutException>(() => Regex.Count(Input, Pattern, RegexHelpers.OptionsFromEngine(engine), TimeSpan.FromMilliseconds(1))); Assert.InRange(sw.Elapsed.TotalSeconds, 0, 10); // arbitrary upper bound that should be well above what's needed with a 1ms timeout break; } } } }
-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.Configuration.ConfigurationManager/src/System/Configuration/OverrideMode.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.Configuration { // This is the public type of the override mode enum visible to the API users // The override mode is an attribute of a <location> tag and controls if the sections inside this tag // can be defined in child web.config files public enum OverrideMode { // Default ( aka Indiferent ) - When specified on a location tag means the location tag will not alter // the locking mode ( locked or unlocked ). Rather, the locking mode should be picked // from the <location> tag with the closest parent path in the current file, or the parent file if no such location in the current one, // or the default for the specific section ( section.OverrideModeDefault ) Inherit = 0, // Allow overriding in child config files. I.e. unlock the settings for overridiing Allow = 1, // Deny overriding of the settings defined in the <location> tag. It is an error for the sections in the <location> tag // to appear in a child config file. It is not an error for them to appear in another <lcoation> tag in the current file Deny = 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.Configuration { // This is the public type of the override mode enum visible to the API users // The override mode is an attribute of a <location> tag and controls if the sections inside this tag // can be defined in child web.config files public enum OverrideMode { // Default ( aka Indiferent ) - When specified on a location tag means the location tag will not alter // the locking mode ( locked or unlocked ). Rather, the locking mode should be picked // from the <location> tag with the closest parent path in the current file, or the parent file if no such location in the current one, // or the default for the specific section ( section.OverrideModeDefault ) Inherit = 0, // Allow overriding in child config files. I.e. unlock the settings for overridiing Allow = 1, // Deny overriding of the settings defined in the <location> tag. It is an error for the sections in the <location> tag // to appear in a child config file. It is not an error for them to appear in another <lcoation> tag in the current file Deny = 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/tests/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b31748/b31748.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // namespace Test { using System; class AA { public static int[] m_anStatic4 = new int[7]; public static void Static1(object[] param1, ref bool param2) { float local8 = 0.0f; AA[] local9 = new AA[7]; while (param2) { #pragma warning disable 1717 param1 = param1; #pragma warning restore 1717 do { m_anStatic4[0] = m_anStatic4[2] - 50; #pragma warning disable 1718 } while (local8 > local8); #pragma warning restore 1718 do { } while ((uint)param1[2] < 0); } } static int Main() { bool b = false; Static1(null, ref b); return 100; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // namespace Test { using System; class AA { public static int[] m_anStatic4 = new int[7]; public static void Static1(object[] param1, ref bool param2) { float local8 = 0.0f; AA[] local9 = new AA[7]; while (param2) { #pragma warning disable 1717 param1 = param1; #pragma warning restore 1717 do { m_anStatic4[0] = m_anStatic4[2] - 50; #pragma warning disable 1718 } while (local8 > local8); #pragma warning restore 1718 do { } while ((uint)param1[2] < 0); } } static int Main() { bool b = false; Static1(null, ref b); 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/tests/JIT/Regression/CLR-x86-JIT/V1-M09/b14367/b14367.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // namespace DefaultNamespace { //@BEGINRENAME; Verify this renames //@ENDRENAME; Verify this renames using System; internal interface IV2 { } internal struct V2 : IV2 { //public V2() {} ANDREIS: commented due compiler error SC0568 public override bool Equals(Object o) { return false; } public override int GetHashCode() { return 0; } } // The legendary 37-byte value class. /* value class V3 { long a; long b; long c; long d; int e; short f; ubyte g; public V3() { a = 1; b = -2; c = 3; d = -4; e = 5; f = (short)-6; g = 7; } public boolean Validate() { return a==1 && b==-2 && c==3 && d==-4 && e==5 && f==-6 && g==7; } public boolean Equals(Object o) { return false; } public int GetHashCode() { return 0; } } */ public class jitAssert { internal const int Length = 3; internal static V2[] V2Array = new V2[Length]; // static V3[] V3Array = new V3[Length]; public static int Main(String[] args) { for (int i = 0; i < Length; i++) { V2Array[i] = new V2(); // V3Array[i] = new V3(); } return 100; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // namespace DefaultNamespace { //@BEGINRENAME; Verify this renames //@ENDRENAME; Verify this renames using System; internal interface IV2 { } internal struct V2 : IV2 { //public V2() {} ANDREIS: commented due compiler error SC0568 public override bool Equals(Object o) { return false; } public override int GetHashCode() { return 0; } } // The legendary 37-byte value class. /* value class V3 { long a; long b; long c; long d; int e; short f; ubyte g; public V3() { a = 1; b = -2; c = 3; d = -4; e = 5; f = (short)-6; g = 7; } public boolean Validate() { return a==1 && b==-2 && c==3 && d==-4 && e==5 && f==-6 && g==7; } public boolean Equals(Object o) { return false; } public int GetHashCode() { return 0; } } */ public class jitAssert { internal const int Length = 3; internal static V2[] V2Array = new V2[Length]; // static V3[] V3Array = new V3[Length]; public static int Main(String[] args) { for (int i = 0; i < Length; i++) { V2Array[i] = new V2(); // V3Array[i] = new V3(); } 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/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/StorePairNonTemporal.Vector64.Int64.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.Reflection; 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 StorePairNonTemporal_Vector64_Int64() { var test = new StoreBinaryOpTest__StorePairNonTemporal_Vector64_Int64(); 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 StoreBinaryOpTest__StorePairNonTemporal_Vector64_Int64 { 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(Int64[] inArray1, Int64[] inArray2, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); if ((alignment != 16 && alignment != 32) || (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<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, 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<Int64> _fld1; public Vector64<Int64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); return testStruct; } public void RunStructFldScenario(StoreBinaryOpTest__StorePairNonTemporal_Vector64_Int64 testClass) { AdvSimd.Arm64.StorePairNonTemporal((Int64*)testClass._dataTable.outArrayPtr, _fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(StoreBinaryOpTest__StorePairNonTemporal_Vector64_Int64 testClass) { fixed (Vector64<Int64>* pFld1 = &_fld1) fixed (Vector64<Int64>* pFld2 = &_fld2) { AdvSimd.Arm64.StorePairNonTemporal( (Int64*)testClass._dataTable.outArrayPtr, AdvSimd.LoadVector64((Int64*)(pFld1)), AdvSimd.LoadVector64((Int64*)(pFld2)) ); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Op1ElementCount + Op2ElementCount; private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector64<Int64> _clsVar1; private static Vector64<Int64> _clsVar2; private Vector64<Int64> _fld1; private Vector64<Int64> _fld2; private DataTable _dataTable; static StoreBinaryOpTest__StorePairNonTemporal_Vector64_Int64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); } public StoreBinaryOpTest__StorePairNonTemporal_Vector64_Int64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data2, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); AdvSimd.Arm64.StorePairNonTemporal( (Int64*)_dataTable.outArrayPtr, Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); AdvSimd.Arm64.StorePairNonTemporal( (Int64*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int64*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.StorePairNonTemporal), new Type[] { typeof(Int64*), typeof(Vector64<Int64>), typeof(Vector64<Int64>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int64*)), Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.StorePairNonTemporal), new Type[] { typeof(Int64*), typeof(Vector64<Int64>), typeof(Vector64<Int64>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int64*)), AdvSimd.LoadVector64((Int64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int64*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); AdvSimd.Arm64.StorePairNonTemporal((Int64*)_dataTable.outArrayPtr, _clsVar1, _clsVar2); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int64>* pClsVar1 = &_clsVar1) fixed (Vector64<Int64>* pClsVar2 = &_clsVar2) { AdvSimd.Arm64.StorePairNonTemporal( (Int64*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int64*)(pClsVar1)), AdvSimd.LoadVector64((Int64*)(pClsVar2)) ); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr); AdvSimd.Arm64.StorePairNonTemporal((Int64*)_dataTable.outArrayPtr, op1, op2); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int64*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int64*)(_dataTable.inArray2Ptr)); AdvSimd.Arm64.StorePairNonTemporal((Int64*)_dataTable.outArrayPtr, op1, op2); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new StoreBinaryOpTest__StorePairNonTemporal_Vector64_Int64(); AdvSimd.Arm64.StorePairNonTemporal((Int64*)_dataTable.outArrayPtr, test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new StoreBinaryOpTest__StorePairNonTemporal_Vector64_Int64(); fixed (Vector64<Int64>* pFld1 = &test._fld1) fixed (Vector64<Int64>* pFld2 = &test._fld2) { AdvSimd.Arm64.StorePairNonTemporal( (Int64*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int64*)(pFld1)), AdvSimd.LoadVector64((Int64*)(pFld2)) ); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); AdvSimd.Arm64.StorePairNonTemporal((Int64*)_dataTable.outArrayPtr, _fld1, _fld2); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int64>* pFld1 = &_fld1) fixed (Vector64<Int64>* pFld2 = &_fld2) { AdvSimd.Arm64.StorePairNonTemporal( (Int64*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int64*)(pFld1)), AdvSimd.LoadVector64((Int64*)(pFld2)) ); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); AdvSimd.Arm64.StorePairNonTemporal((Int64*)_dataTable.outArrayPtr, test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); AdvSimd.Arm64.StorePairNonTemporal( (Int64*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int64*)(&test._fld1)), AdvSimd.LoadVector64((Int64*)(&test._fld2)) ); 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<Int64> op1, Vector64<Int64> op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)(RetElementCount * Unsafe.SizeOf<Int64>())); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)(RetElementCount * Unsafe.SizeOf<Int64>())); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] firstOp, Int64[] secondOp, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < RetElementCount; i++) { if (Helpers.Concat(firstOp, secondOp, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.StorePairNonTemporal)}<Int64>(Vector64<Int64>, Vector64<Int64>): {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.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.Reflection; 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 StorePairNonTemporal_Vector64_Int64() { var test = new StoreBinaryOpTest__StorePairNonTemporal_Vector64_Int64(); 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 StoreBinaryOpTest__StorePairNonTemporal_Vector64_Int64 { 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(Int64[] inArray1, Int64[] inArray2, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); if ((alignment != 16 && alignment != 32) || (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<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, 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<Int64> _fld1; public Vector64<Int64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); return testStruct; } public void RunStructFldScenario(StoreBinaryOpTest__StorePairNonTemporal_Vector64_Int64 testClass) { AdvSimd.Arm64.StorePairNonTemporal((Int64*)testClass._dataTable.outArrayPtr, _fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(StoreBinaryOpTest__StorePairNonTemporal_Vector64_Int64 testClass) { fixed (Vector64<Int64>* pFld1 = &_fld1) fixed (Vector64<Int64>* pFld2 = &_fld2) { AdvSimd.Arm64.StorePairNonTemporal( (Int64*)testClass._dataTable.outArrayPtr, AdvSimd.LoadVector64((Int64*)(pFld1)), AdvSimd.LoadVector64((Int64*)(pFld2)) ); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Op1ElementCount + Op2ElementCount; private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector64<Int64> _clsVar1; private static Vector64<Int64> _clsVar2; private Vector64<Int64> _fld1; private Vector64<Int64> _fld2; private DataTable _dataTable; static StoreBinaryOpTest__StorePairNonTemporal_Vector64_Int64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); } public StoreBinaryOpTest__StorePairNonTemporal_Vector64_Int64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data2, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); AdvSimd.Arm64.StorePairNonTemporal( (Int64*)_dataTable.outArrayPtr, Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); AdvSimd.Arm64.StorePairNonTemporal( (Int64*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int64*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.StorePairNonTemporal), new Type[] { typeof(Int64*), typeof(Vector64<Int64>), typeof(Vector64<Int64>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int64*)), Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.StorePairNonTemporal), new Type[] { typeof(Int64*), typeof(Vector64<Int64>), typeof(Vector64<Int64>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int64*)), AdvSimd.LoadVector64((Int64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int64*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); AdvSimd.Arm64.StorePairNonTemporal((Int64*)_dataTable.outArrayPtr, _clsVar1, _clsVar2); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int64>* pClsVar1 = &_clsVar1) fixed (Vector64<Int64>* pClsVar2 = &_clsVar2) { AdvSimd.Arm64.StorePairNonTemporal( (Int64*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int64*)(pClsVar1)), AdvSimd.LoadVector64((Int64*)(pClsVar2)) ); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int64>>(_dataTable.inArray2Ptr); AdvSimd.Arm64.StorePairNonTemporal((Int64*)_dataTable.outArrayPtr, op1, op2); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int64*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int64*)(_dataTable.inArray2Ptr)); AdvSimd.Arm64.StorePairNonTemporal((Int64*)_dataTable.outArrayPtr, op1, op2); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new StoreBinaryOpTest__StorePairNonTemporal_Vector64_Int64(); AdvSimd.Arm64.StorePairNonTemporal((Int64*)_dataTable.outArrayPtr, test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new StoreBinaryOpTest__StorePairNonTemporal_Vector64_Int64(); fixed (Vector64<Int64>* pFld1 = &test._fld1) fixed (Vector64<Int64>* pFld2 = &test._fld2) { AdvSimd.Arm64.StorePairNonTemporal( (Int64*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int64*)(pFld1)), AdvSimd.LoadVector64((Int64*)(pFld2)) ); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); AdvSimd.Arm64.StorePairNonTemporal((Int64*)_dataTable.outArrayPtr, _fld1, _fld2); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int64>* pFld1 = &_fld1) fixed (Vector64<Int64>* pFld2 = &_fld2) { AdvSimd.Arm64.StorePairNonTemporal( (Int64*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int64*)(pFld1)), AdvSimd.LoadVector64((Int64*)(pFld2)) ); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); AdvSimd.Arm64.StorePairNonTemporal((Int64*)_dataTable.outArrayPtr, test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); AdvSimd.Arm64.StorePairNonTemporal( (Int64*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int64*)(&test._fld1)), AdvSimd.LoadVector64((Int64*)(&test._fld2)) ); 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<Int64> op1, Vector64<Int64> op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)(RetElementCount * Unsafe.SizeOf<Int64>())); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)(RetElementCount * Unsafe.SizeOf<Int64>())); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] firstOp, Int64[] secondOp, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < RetElementCount; i++) { if (Helpers.Concat(firstOp, secondOp, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.StorePairNonTemporal)}<Int64>(Vector64<Int64>, Vector64<Int64>): {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/Regression/CLR-x86-JIT/V1-M14-SP1/b119538/b119538b.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; class C { private string s = "This is private"; } class B { public string t = "This is safe"; } class Class1 { public static int Main(string[] args) { B[,] ab = new B[1, 1]; object[,] ao = ab; try { ao[0, 0] = new C(); } catch (ArrayTypeMismatchException) { Console.WriteLine("PASSED"); return 100; } Console.WriteLine(ab[0, 0].t); Console.WriteLine("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; class C { private string s = "This is private"; } class B { public string t = "This is safe"; } class Class1 { public static int Main(string[] args) { B[,] ab = new B[1, 1]; object[,] ao = ab; try { ao[0, 0] = new C(); } catch (ArrayTypeMismatchException) { Console.WriteLine("PASSED"); return 100; } Console.WriteLine(ab[0, 0].t); Console.WriteLine("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)
./src/tests/JIT/Regression/JitBlue/Runtime_44895/Runtime_44895.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 Text { private readonly string _value; public Text(string value) => _value = value; public string Value => _value ?? string.Empty; } public class TextProperty { public Text GetValue(Text? a = null, Text? b = null, Text? c = null, Text? d = null) { if (a.HasValue) return a.Value; if (b.HasValue) return b.Value; if (c.HasValue) return c.Value; if (d.HasValue) return d.Value; return default; } } public class Repro { public static int Main() { string test = "test"; TextProperty t = new TextProperty(); Text gv = t.GetValue(new Text(test)); bool result = test.Equals(gv.Value); Console.WriteLine(result ? "Pass" : "Fail"); if (!result) Console.WriteLine($"got '{gv.Value}', expected '{test}'"); return result ? 100 : -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 struct Text { private readonly string _value; public Text(string value) => _value = value; public string Value => _value ?? string.Empty; } public class TextProperty { public Text GetValue(Text? a = null, Text? b = null, Text? c = null, Text? d = null) { if (a.HasValue) return a.Value; if (b.HasValue) return b.Value; if (c.HasValue) return c.Value; if (d.HasValue) return d.Value; return default; } } public class Repro { public static int Main() { string test = "test"; TextProperty t = new TextProperty(); Text gv = t.GetValue(new Text(test)); bool result = test.Equals(gv.Value); Console.WriteLine(result ? "Pass" : "Fail"); if (!result) Console.WriteLine($"got '{gv.Value}', expected '{test}'"); return result ? 100 : -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/Common/src/Interop/Windows/NtDll/Interop.SYSTEM_LEAP_SECOND_INFORMATION.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; internal static partial class Interop { internal static partial class NtDll { // From SYSTEM_INFORMATION_CLASS // Use for NtQuerySystemInformation internal const int SystemLeapSecondInformation = 206; [StructLayout(LayoutKind.Sequential)] internal struct SYSTEM_LEAP_SECOND_INFORMATION { public BOOLEAN Enabled; public uint Flags; } } }
// 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; internal static partial class Interop { internal static partial class NtDll { // From SYSTEM_INFORMATION_CLASS // Use for NtQuerySystemInformation internal const int SystemLeapSecondInformation = 206; [StructLayout(LayoutKind.Sequential)] internal struct SYSTEM_LEAP_SECOND_INFORMATION { public BOOLEAN Enabled; public uint Flags; } } }
-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.Data.Common/tests/System/Data/Common/DbProviderFactoriesTests.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.Collections.Generic; using System.Reflection; using System.Linq; using Xunit; namespace System.Data.Common { public sealed class TestProviderFactory : DbProviderFactory { public static readonly TestProviderFactory Instance = new TestProviderFactory(); private TestProviderFactory() { } } [SkipOnPlatform(TestPlatforms.Browser, "Not supported on Browser.")] public class DbProviderFactoriesTests { [Fact] public void GetFactoryClassesDataTableShapeTest() { DataTable initializedTable = DbProviderFactories.GetFactoryClasses(); Assert.NotNull(initializedTable); Assert.Equal(4, initializedTable.Columns.Count); Assert.Equal("Name", initializedTable.Columns[0].ColumnName); Assert.Equal("Description", initializedTable.Columns[1].ColumnName); Assert.Equal("InvariantName", initializedTable.Columns[2].ColumnName); Assert.Equal("AssemblyQualifiedName", initializedTable.Columns[3].ColumnName); } [Fact] public void GetFactoryNoRegistrationTest() { ClearRegisteredFactories(); Assert.Throws<ArgumentException>(() => DbProviderFactories.GetFactory("System.Data.SqlClient")); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void GetFactoryWithInvariantNameTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(()=>DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlClientFactory))); DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient"); Assert.NotNull(factory); Assert.Equal(typeof(System.Data.SqlClient.SqlClientFactory), factory.GetType()); Assert.Equal(System.Data.SqlClient.SqlClientFactory.Instance, factory); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void GetFactoryWithDbConnectionTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(()=>DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlClientFactory))); DbProviderFactory factory = DbProviderFactories.GetFactory(new System.Data.SqlClient.SqlConnection()); Assert.NotNull(factory); Assert.Equal(typeof(System.Data.SqlClient.SqlClientFactory), factory.GetType()); Assert.Equal(System.Data.SqlClient.SqlClientFactory.Instance, factory); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void GetFactoryWithDataRowTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(()=> DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlClientFactory))); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void RegisterFactoryWithTypeNameTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(()=>DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlClientFactory).AssemblyQualifiedName)); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void RegisterFactoryWithTypeTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(()=>DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlClientFactory))); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void RegisterFactoryWithInstanceTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(()=>DbProviderFactories.RegisterFactory("System.Data.SqlClient", System.Data.SqlClient.SqlClientFactory.Instance)); } [Fact] public void RegisterFactoryWithWrongTypeTest() { ClearRegisteredFactories(); Assert.Throws<ArgumentException>(() => DbProviderFactories.GetFactory("System.Data.SqlClient")); Assert.Throws<ArgumentException>(() => DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlConnection))); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void RegisterFactoryWithBadInvariantNameTest() { ClearRegisteredFactories(); Assert.Throws<ArgumentException>(() => DbProviderFactories.GetFactory("System.Data.SqlClient")); Assert.Throws<ArgumentException>(() => DbProviderFactories.RegisterFactory(string.Empty, typeof(System.Data.SqlClient.SqlClientFactory))); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void RegisterFactoryWithAssemblyQualifiedNameTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(()=>DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlClientFactory).AssemblyQualifiedName)); } [Fact] public void RegisterFactoryWithWrongAssemblyQualifiedNameTest() { ClearRegisteredFactories(); Assert.Throws<ArgumentException>(() => DbProviderFactories.GetFactory("System.Data.SqlClient")); DataTable providerTable = DbProviderFactories.GetFactoryClasses(); Assert.Equal(0, providerTable.Rows.Count); // register the connection type which is the wrong type. Registraton should succeed, as type registration/checking is deferred. DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlConnection).AssemblyQualifiedName); providerTable = DbProviderFactories.GetFactoryClasses(); Assert.Equal(1, providerTable.Rows.Count); // obtaining the factory will kick in the checks of the registered type name, which will cause exceptions. The checks were deferred till the GetFactory() call. Assert.Throws<ArgumentException>(() => DbProviderFactories.GetFactory(providerTable.Rows[0])); Assert.Throws<ArgumentException>(() => DbProviderFactories.GetFactory("System.Data.SqlClient")); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void UnregisterFactoryTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(()=>DbProviderFactories.RegisterFactory("System.Data.SqlClient", System.Data.SqlClient.SqlClientFactory.Instance)); Assert.True(DbProviderFactories.UnregisterFactory("System.Data.SqlClient")); DataTable providerTable = DbProviderFactories.GetFactoryClasses(); Assert.Equal(0, providerTable.Rows.Count); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void TryGetFactoryTest() { ClearRegisteredFactories(); Assert.False(DbProviderFactories.TryGetFactory("System.Data.SqlClient", out DbProviderFactory f)); RegisterSqlClientAndTestRegistration(() => DbProviderFactories.RegisterFactory("System.Data.SqlClient", System.Data.SqlClient.SqlClientFactory.Instance)); Assert.True(DbProviderFactories.TryGetFactory("System.Data.SqlClient", out DbProviderFactory factory)); Assert.NotNull(factory); Assert.Equal(typeof(System.Data.SqlClient.SqlClientFactory), factory.GetType()); Assert.Equal(System.Data.SqlClient.SqlClientFactory.Instance, factory); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void ReplaceFactoryWithRegisterFactoryWithTypeTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(()=>DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlClientFactory))); DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(TestProviderFactory)); DataTable providerTable = DbProviderFactories.GetFactoryClasses(); Assert.Equal(1, providerTable.Rows.Count); DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient"); Assert.NotNull(factory); Assert.Equal(typeof(TestProviderFactory), factory.GetType()); Assert.Equal(TestProviderFactory.Instance, factory); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void GetProviderInvariantNamesTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(() => DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlClientFactory))); DbProviderFactories.RegisterFactory("System.Data.Common.TestProvider", typeof(TestProviderFactory)); DataTable providerTable = DbProviderFactories.GetFactoryClasses(); Assert.Equal(2, providerTable.Rows.Count); List<string> invariantNames = DbProviderFactories.GetProviderInvariantNames().ToList(); Assert.Equal(2, invariantNames.Count); Assert.Contains("System.Data.Common.TestProvider", invariantNames); Assert.Contains("System.Data.SqlClient", invariantNames); } private void ClearRegisteredFactories() { // as the DbProviderFactories table is shared, for tests we need a clean one before a test starts to make sure the tests always succeed. Type type = typeof(DbProviderFactories); FieldInfo info = type.GetField("_registeredFactories", BindingFlags.NonPublic | BindingFlags.Static); IDictionary providerStorage = info.GetValue(null) as IDictionary; Assert.NotNull(providerStorage); providerStorage.Clear(); Assert.Equal(0, providerStorage.Count); } private void RegisterSqlClientAndTestRegistration(Action registrationFunc) { Assert.NotNull(registrationFunc); Assert.Throws<ArgumentException>(() => DbProviderFactories.GetFactory("System.Data.SqlClient")); DataTable providerTable = DbProviderFactories.GetFactoryClasses(); Assert.Equal(0, providerTable.Rows.Count); registrationFunc(); providerTable = DbProviderFactories.GetFactoryClasses(); Assert.Equal(1, providerTable.Rows.Count); DbProviderFactory factory = DbProviderFactories.GetFactory(providerTable.Rows[0]); Assert.NotNull(factory); Assert.Equal(typeof(System.Data.SqlClient.SqlClientFactory), factory.GetType()); Assert.Equal(System.Data.SqlClient.SqlClientFactory.Instance, factory); } } }
// 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.Collections.Generic; using System.Reflection; using System.Linq; using Xunit; namespace System.Data.Common { public sealed class TestProviderFactory : DbProviderFactory { public static readonly TestProviderFactory Instance = new TestProviderFactory(); private TestProviderFactory() { } } [SkipOnPlatform(TestPlatforms.Browser, "Not supported on Browser.")] public class DbProviderFactoriesTests { [Fact] public void GetFactoryClassesDataTableShapeTest() { DataTable initializedTable = DbProviderFactories.GetFactoryClasses(); Assert.NotNull(initializedTable); Assert.Equal(4, initializedTable.Columns.Count); Assert.Equal("Name", initializedTable.Columns[0].ColumnName); Assert.Equal("Description", initializedTable.Columns[1].ColumnName); Assert.Equal("InvariantName", initializedTable.Columns[2].ColumnName); Assert.Equal("AssemblyQualifiedName", initializedTable.Columns[3].ColumnName); } [Fact] public void GetFactoryNoRegistrationTest() { ClearRegisteredFactories(); Assert.Throws<ArgumentException>(() => DbProviderFactories.GetFactory("System.Data.SqlClient")); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void GetFactoryWithInvariantNameTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(()=>DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlClientFactory))); DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient"); Assert.NotNull(factory); Assert.Equal(typeof(System.Data.SqlClient.SqlClientFactory), factory.GetType()); Assert.Equal(System.Data.SqlClient.SqlClientFactory.Instance, factory); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void GetFactoryWithDbConnectionTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(()=>DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlClientFactory))); DbProviderFactory factory = DbProviderFactories.GetFactory(new System.Data.SqlClient.SqlConnection()); Assert.NotNull(factory); Assert.Equal(typeof(System.Data.SqlClient.SqlClientFactory), factory.GetType()); Assert.Equal(System.Data.SqlClient.SqlClientFactory.Instance, factory); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void GetFactoryWithDataRowTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(()=> DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlClientFactory))); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void RegisterFactoryWithTypeNameTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(()=>DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlClientFactory).AssemblyQualifiedName)); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void RegisterFactoryWithTypeTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(()=>DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlClientFactory))); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void RegisterFactoryWithInstanceTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(()=>DbProviderFactories.RegisterFactory("System.Data.SqlClient", System.Data.SqlClient.SqlClientFactory.Instance)); } [Fact] public void RegisterFactoryWithWrongTypeTest() { ClearRegisteredFactories(); Assert.Throws<ArgumentException>(() => DbProviderFactories.GetFactory("System.Data.SqlClient")); Assert.Throws<ArgumentException>(() => DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlConnection))); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void RegisterFactoryWithBadInvariantNameTest() { ClearRegisteredFactories(); Assert.Throws<ArgumentException>(() => DbProviderFactories.GetFactory("System.Data.SqlClient")); Assert.Throws<ArgumentException>(() => DbProviderFactories.RegisterFactory(string.Empty, typeof(System.Data.SqlClient.SqlClientFactory))); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void RegisterFactoryWithAssemblyQualifiedNameTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(()=>DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlClientFactory).AssemblyQualifiedName)); } [Fact] public void RegisterFactoryWithWrongAssemblyQualifiedNameTest() { ClearRegisteredFactories(); Assert.Throws<ArgumentException>(() => DbProviderFactories.GetFactory("System.Data.SqlClient")); DataTable providerTable = DbProviderFactories.GetFactoryClasses(); Assert.Equal(0, providerTable.Rows.Count); // register the connection type which is the wrong type. Registraton should succeed, as type registration/checking is deferred. DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlConnection).AssemblyQualifiedName); providerTable = DbProviderFactories.GetFactoryClasses(); Assert.Equal(1, providerTable.Rows.Count); // obtaining the factory will kick in the checks of the registered type name, which will cause exceptions. The checks were deferred till the GetFactory() call. Assert.Throws<ArgumentException>(() => DbProviderFactories.GetFactory(providerTable.Rows[0])); Assert.Throws<ArgumentException>(() => DbProviderFactories.GetFactory("System.Data.SqlClient")); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void UnregisterFactoryTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(()=>DbProviderFactories.RegisterFactory("System.Data.SqlClient", System.Data.SqlClient.SqlClientFactory.Instance)); Assert.True(DbProviderFactories.UnregisterFactory("System.Data.SqlClient")); DataTable providerTable = DbProviderFactories.GetFactoryClasses(); Assert.Equal(0, providerTable.Rows.Count); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void TryGetFactoryTest() { ClearRegisteredFactories(); Assert.False(DbProviderFactories.TryGetFactory("System.Data.SqlClient", out DbProviderFactory f)); RegisterSqlClientAndTestRegistration(() => DbProviderFactories.RegisterFactory("System.Data.SqlClient", System.Data.SqlClient.SqlClientFactory.Instance)); Assert.True(DbProviderFactories.TryGetFactory("System.Data.SqlClient", out DbProviderFactory factory)); Assert.NotNull(factory); Assert.Equal(typeof(System.Data.SqlClient.SqlClientFactory), factory.GetType()); Assert.Equal(System.Data.SqlClient.SqlClientFactory.Instance, factory); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void ReplaceFactoryWithRegisterFactoryWithTypeTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(()=>DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlClientFactory))); DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(TestProviderFactory)); DataTable providerTable = DbProviderFactories.GetFactoryClasses(); Assert.Equal(1, providerTable.Rows.Count); DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient"); Assert.NotNull(factory); Assert.Equal(typeof(TestProviderFactory), factory.GetType()); Assert.Equal(TestProviderFactory.Instance, factory); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/36879", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void GetProviderInvariantNamesTest() { ClearRegisteredFactories(); RegisterSqlClientAndTestRegistration(() => DbProviderFactories.RegisterFactory("System.Data.SqlClient", typeof(System.Data.SqlClient.SqlClientFactory))); DbProviderFactories.RegisterFactory("System.Data.Common.TestProvider", typeof(TestProviderFactory)); DataTable providerTable = DbProviderFactories.GetFactoryClasses(); Assert.Equal(2, providerTable.Rows.Count); List<string> invariantNames = DbProviderFactories.GetProviderInvariantNames().ToList(); Assert.Equal(2, invariantNames.Count); Assert.Contains("System.Data.Common.TestProvider", invariantNames); Assert.Contains("System.Data.SqlClient", invariantNames); } private void ClearRegisteredFactories() { // as the DbProviderFactories table is shared, for tests we need a clean one before a test starts to make sure the tests always succeed. Type type = typeof(DbProviderFactories); FieldInfo info = type.GetField("_registeredFactories", BindingFlags.NonPublic | BindingFlags.Static); IDictionary providerStorage = info.GetValue(null) as IDictionary; Assert.NotNull(providerStorage); providerStorage.Clear(); Assert.Equal(0, providerStorage.Count); } private void RegisterSqlClientAndTestRegistration(Action registrationFunc) { Assert.NotNull(registrationFunc); Assert.Throws<ArgumentException>(() => DbProviderFactories.GetFactory("System.Data.SqlClient")); DataTable providerTable = DbProviderFactories.GetFactoryClasses(); Assert.Equal(0, providerTable.Rows.Count); registrationFunc(); providerTable = DbProviderFactories.GetFactoryClasses(); Assert.Equal(1, providerTable.Rows.Count); DbProviderFactory factory = DbProviderFactories.GetFactory(providerTable.Rows[0]); Assert.NotNull(factory); Assert.Equal(typeof(System.Data.SqlClient.SqlClientFactory), factory.GetType()); Assert.Equal(System.Data.SqlClient.SqlClientFactory.Instance, factory); } } }
-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.Memory/tests/ReadOnlySpan/StartsWith.byte.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; namespace System.SpanTests { public static partial class ReadOnlySpanTests { [Fact] public static void ZeroLengthStartsWith_Byte() { byte[] a = new byte[3]; ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a); ReadOnlySpan<byte> slice = new ReadOnlySpan<byte>(a, 2, 0); bool b = span.StartsWith<byte>(slice); Assert.True(b); } [Fact] public static void SameSpanStartsWith_Byte() { byte[] a = { 4, 5, 6 }; ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a); bool b = span.StartsWith<byte>(span); Assert.True(b); } [Fact] public static void LengthMismatchStartsWith_Byte() { byte[] a = { 4, 5, 6 }; ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a, 0, 2); ReadOnlySpan<byte> slice = new ReadOnlySpan<byte>(a, 0, 3); bool b = span.StartsWith<byte>(slice); Assert.False(b); } [Fact] public static void StartsWithMatch_Byte() { byte[] a = { 4, 5, 6 }; ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a, 0, 3); ReadOnlySpan<byte> slice = new ReadOnlySpan<byte>(a, 0, 2); bool b = span.StartsWith<byte>(slice); Assert.True(b); } [Fact] public static void StartsWithMatchDifferentSpans_Byte() { byte[] a = { 4, 5, 6 }; byte[] b = { 4, 5, 6 }; ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a, 0, 3); ReadOnlySpan<byte> slice = new ReadOnlySpan<byte>(b, 0, 3); bool c = span.StartsWith<byte>(slice); Assert.True(c); } [Fact] public static void StartsWithNoMatch_Byte() { for (int length = 1; length < 32; length++) { for (int mismatchIndex = 0; mismatchIndex < length; mismatchIndex++) { byte[] first = new byte[length]; byte[] second = new byte[length]; for (int i = 0; i < length; i++) { first[i] = second[i] = (byte)(i + 1); } second[mismatchIndex] = (byte)(second[mismatchIndex] + 1); ReadOnlySpan<byte> firstSpan = new ReadOnlySpan<byte>(first); ReadOnlySpan<byte> secondSpan = new ReadOnlySpan<byte>(second); bool b = firstSpan.StartsWith<byte>(secondSpan); Assert.False(b); } } } [Fact] public static void MakeSureNoStartsWithChecksGoOutOfRange_Byte() { for (int length = 0; length < 100; length++) { byte[] first = new byte[length + 2]; first[0] = 99; first[length + 1] = 99; byte[] second = new byte[length + 2]; second[0] = 100; second[length + 1] = 100; ReadOnlySpan<byte> span1 = new ReadOnlySpan<byte>(first, 1, length); ReadOnlySpan<byte> span2 = new ReadOnlySpan<byte>(second, 1, length); bool b = span1.StartsWith<byte>(span2); Assert.True(b); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.SpanTests { public static partial class ReadOnlySpanTests { [Fact] public static void ZeroLengthStartsWith_Byte() { byte[] a = new byte[3]; ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a); ReadOnlySpan<byte> slice = new ReadOnlySpan<byte>(a, 2, 0); bool b = span.StartsWith<byte>(slice); Assert.True(b); } [Fact] public static void SameSpanStartsWith_Byte() { byte[] a = { 4, 5, 6 }; ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a); bool b = span.StartsWith<byte>(span); Assert.True(b); } [Fact] public static void LengthMismatchStartsWith_Byte() { byte[] a = { 4, 5, 6 }; ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a, 0, 2); ReadOnlySpan<byte> slice = new ReadOnlySpan<byte>(a, 0, 3); bool b = span.StartsWith<byte>(slice); Assert.False(b); } [Fact] public static void StartsWithMatch_Byte() { byte[] a = { 4, 5, 6 }; ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a, 0, 3); ReadOnlySpan<byte> slice = new ReadOnlySpan<byte>(a, 0, 2); bool b = span.StartsWith<byte>(slice); Assert.True(b); } [Fact] public static void StartsWithMatchDifferentSpans_Byte() { byte[] a = { 4, 5, 6 }; byte[] b = { 4, 5, 6 }; ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a, 0, 3); ReadOnlySpan<byte> slice = new ReadOnlySpan<byte>(b, 0, 3); bool c = span.StartsWith<byte>(slice); Assert.True(c); } [Fact] public static void StartsWithNoMatch_Byte() { for (int length = 1; length < 32; length++) { for (int mismatchIndex = 0; mismatchIndex < length; mismatchIndex++) { byte[] first = new byte[length]; byte[] second = new byte[length]; for (int i = 0; i < length; i++) { first[i] = second[i] = (byte)(i + 1); } second[mismatchIndex] = (byte)(second[mismatchIndex] + 1); ReadOnlySpan<byte> firstSpan = new ReadOnlySpan<byte>(first); ReadOnlySpan<byte> secondSpan = new ReadOnlySpan<byte>(second); bool b = firstSpan.StartsWith<byte>(secondSpan); Assert.False(b); } } } [Fact] public static void MakeSureNoStartsWithChecksGoOutOfRange_Byte() { for (int length = 0; length < 100; length++) { byte[] first = new byte[length + 2]; first[0] = 99; first[length + 1] = 99; byte[] second = new byte[length + 2]; second[0] = 100; second[length + 1] = 100; ReadOnlySpan<byte> span1 = new ReadOnlySpan<byte>(first, 1, length); ReadOnlySpan<byte> span2 = new ReadOnlySpan<byte>(second, 1, length); bool b = span1.StartsWith<byte>(span2); Assert.True(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/libraries/System.Private.CoreLib/src/System/ProbabilisticMap.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.Runtime.InteropServices; namespace System { /// <summary>Data structure used to optimize checks for whether a char is in a set of chars.</summary> /// <remarks> /// Like a Bloom filter, the idea is to create a bit map of the characters we are /// searching for and use this map as a "cheap" check to decide if the current /// character in the string exists in the array of input characters. There are /// 256 bits in the map, with each character mapped to 2 bits. Every character is /// divided into 2 bytes, and then every byte is mapped to 1 bit. The character map /// is an array of 8 integers acting as map blocks. The 3 lsb in each byte in the /// character is used to index into this map to get the right block, the value of /// the remaining 5 msb are used as the bit position inside this block. /// </remarks> [StructLayout(LayoutKind.Explicit, Size = Size * sizeof(uint))] internal struct ProbabilisticMap { private const int Size = 0x8; private const int IndexMask = 0x7; private const int IndexShift = 0x3; /// <summary>Initializes the map based on the specified values.</summary> /// <param name="charMap">A pointer to the beginning of a <see cref="ProbabilisticMap"/>.</param> /// <param name="values">The values to set in the map.</param> public static unsafe void Initialize(uint* charMap, ReadOnlySpan<char> values) { #if DEBUG for (int i = 0; i < Size; i++) { Debug.Assert(charMap[i] == 0, "Expected charMap to be zero-initialized."); } #endif bool hasAscii = false; uint* charMapLocal = charMap; // https://github.com/dotnet/runtime/issues/9040 for (int i = 0; i < values.Length; ++i) { int c = values[i]; // Map low bit SetCharBit(charMapLocal, (byte)c); // Map high bit c >>= 8; if (c == 0) { hasAscii = true; } else { SetCharBit(charMapLocal, (byte)c); } } if (hasAscii) { // Common to search for ASCII symbols. Just set the high value once. charMapLocal[0] |= 1u; } } public static unsafe bool IsCharBitSet(uint* charMap, byte value) => (charMap[(uint)value & IndexMask] & (1u << (value >> IndexShift))) != 0; private static unsafe void SetCharBit(uint* charMap, byte value) => charMap[(uint)value & IndexMask] |= 1u << (value >> IndexShift); /// <summary>Determines whether <paramref name="searchChar"/> is in <paramref name="span"/>.</summary> /// <remarks> /// <see cref="MemoryExtensions.Contains{T}(ReadOnlySpan{T}, T)"/> could be used, but it's optimized /// for longer spans, whereas typical usage here expects a relatively small number of items in the span. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SpanContains(ReadOnlySpan<char> span, char searchChar) { for (int i = 0; i < span.Length; i++) { if (span[i] == searchChar) { return true; } } 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 System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System { /// <summary>Data structure used to optimize checks for whether a char is in a set of chars.</summary> /// <remarks> /// Like a Bloom filter, the idea is to create a bit map of the characters we are /// searching for and use this map as a "cheap" check to decide if the current /// character in the string exists in the array of input characters. There are /// 256 bits in the map, with each character mapped to 2 bits. Every character is /// divided into 2 bytes, and then every byte is mapped to 1 bit. The character map /// is an array of 8 integers acting as map blocks. The 3 lsb in each byte in the /// character is used to index into this map to get the right block, the value of /// the remaining 5 msb are used as the bit position inside this block. /// </remarks> [StructLayout(LayoutKind.Explicit, Size = Size * sizeof(uint))] internal struct ProbabilisticMap { private const int Size = 0x8; private const int IndexMask = 0x7; private const int IndexShift = 0x3; /// <summary>Initializes the map based on the specified values.</summary> /// <param name="charMap">A pointer to the beginning of a <see cref="ProbabilisticMap"/>.</param> /// <param name="values">The values to set in the map.</param> public static unsafe void Initialize(uint* charMap, ReadOnlySpan<char> values) { #if DEBUG for (int i = 0; i < Size; i++) { Debug.Assert(charMap[i] == 0, "Expected charMap to be zero-initialized."); } #endif bool hasAscii = false; uint* charMapLocal = charMap; // https://github.com/dotnet/runtime/issues/9040 for (int i = 0; i < values.Length; ++i) { int c = values[i]; // Map low bit SetCharBit(charMapLocal, (byte)c); // Map high bit c >>= 8; if (c == 0) { hasAscii = true; } else { SetCharBit(charMapLocal, (byte)c); } } if (hasAscii) { // Common to search for ASCII symbols. Just set the high value once. charMapLocal[0] |= 1u; } } public static unsafe bool IsCharBitSet(uint* charMap, byte value) => (charMap[(uint)value & IndexMask] & (1u << (value >> IndexShift))) != 0; private static unsafe void SetCharBit(uint* charMap, byte value) => charMap[(uint)value & IndexMask] |= 1u << (value >> IndexShift); /// <summary>Determines whether <paramref name="searchChar"/> is in <paramref name="span"/>.</summary> /// <remarks> /// <see cref="MemoryExtensions.Contains{T}(ReadOnlySpan{T}, T)"/> could be used, but it's optimized /// for longer spans, whereas typical usage here expects a relatively small number of items in the span. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SpanContains(ReadOnlySpan<char> span, char searchChar) { for (int i = 0; i < span.Length; i++) { if (span[i] == searchChar) { return true; } } 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/Common/src/Interop/Windows/Advapi32/Interop.QueryServiceStatus.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Advapi32 { [GeneratedDllImport(Libraries.Advapi32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static unsafe partial bool QueryServiceStatus(SafeServiceHandle serviceHandle, SERVICE_STATUS* pStatus); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Advapi32 { [GeneratedDllImport(Libraries.Advapi32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static unsafe partial bool QueryServiceStatus(SafeServiceHandle serviceHandle, SERVICE_STATUS* pStatus); } }
-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.Data.Odbc/src/System/Data/Odbc/OdbcConnectionOpen.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.Data.Common; using System.Data.ProviderBase; namespace System.Data.Odbc { internal sealed class OdbcConnectionOpen : DbConnectionInternal { // Construct from a compiled connection string internal OdbcConnectionOpen(OdbcConnection outerConnection, OdbcConnectionString connectionOptions) { OdbcEnvironmentHandle environmentHandle = OdbcEnvironment.GetGlobalEnvironmentHandle(); outerConnection.ConnectionHandle = new OdbcConnectionHandle(outerConnection, connectionOptions, environmentHandle); } internal OdbcConnection OuterConnection { get { OdbcConnection? outerConnection = (OdbcConnection?)Owner; if (null == outerConnection) throw ODBC.OpenConnectionNoOwner(); return outerConnection; } } public override string ServerVersion { get { // https://github.com/dotnet/runtime/issues/44289: This seems like it returns null if the connection is open, whereas the docs say it should throw // InvalidOperationException return OuterConnection.Open_GetServerVersion()!; } } protected override void Activate() { } public override DbTransaction BeginTransaction(IsolationLevel isolevel) { return BeginOdbcTransaction(isolevel); } internal OdbcTransaction BeginOdbcTransaction(IsolationLevel isolevel) { return OuterConnection.Open_BeginTransaction(isolevel); } public override void ChangeDatabase(string value) { OuterConnection.Open_ChangeDatabase(value); } protected override DbReferenceCollection CreateReferenceCollection() { return new OdbcReferenceCollection(); } protected override void Deactivate() { NotifyWeakReference(OdbcReferenceCollection.Closing); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Data.Common; using System.Data.ProviderBase; namespace System.Data.Odbc { internal sealed class OdbcConnectionOpen : DbConnectionInternal { // Construct from a compiled connection string internal OdbcConnectionOpen(OdbcConnection outerConnection, OdbcConnectionString connectionOptions) { OdbcEnvironmentHandle environmentHandle = OdbcEnvironment.GetGlobalEnvironmentHandle(); outerConnection.ConnectionHandle = new OdbcConnectionHandle(outerConnection, connectionOptions, environmentHandle); } internal OdbcConnection OuterConnection { get { OdbcConnection? outerConnection = (OdbcConnection?)Owner; if (null == outerConnection) throw ODBC.OpenConnectionNoOwner(); return outerConnection; } } public override string ServerVersion { get { // https://github.com/dotnet/runtime/issues/44289: This seems like it returns null if the connection is open, whereas the docs say it should throw // InvalidOperationException return OuterConnection.Open_GetServerVersion()!; } } protected override void Activate() { } public override DbTransaction BeginTransaction(IsolationLevel isolevel) { return BeginOdbcTransaction(isolevel); } internal OdbcTransaction BeginOdbcTransaction(IsolationLevel isolevel) { return OuterConnection.Open_BeginTransaction(isolevel); } public override void ChangeDatabase(string value) { OuterConnection.Open_ChangeDatabase(value); } protected override DbReferenceCollection CreateReferenceCollection() { return new OdbcReferenceCollection(); } protected override void Deactivate() { NotifyWeakReference(OdbcReferenceCollection.Closing); } } }
-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/Common/src/System/Net/Http/aspnetcore/Http2/Hpack/HPackDecodingException.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; namespace System.Net.Http.HPack { // TODO: Should this be public? [Serializable] internal sealed class HPackDecodingException : Exception { public HPackDecodingException() { } public HPackDecodingException(string message) : base(message) { } public HPackDecodingException(string message, Exception innerException) : base(message, innerException) { } public HPackDecodingException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
// 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; namespace System.Net.Http.HPack { // TODO: Should this be public? [Serializable] internal sealed class HPackDecodingException : Exception { public HPackDecodingException() { } public HPackDecodingException(string message) : base(message) { } public HPackDecodingException(string message, Exception innerException) : base(message, innerException) { } public HPackDecodingException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
-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.IO.Pipelines/tests/Infrastructure/ReadOnlyStream.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.IO.Pipelines.Tests { public abstract class ReadOnlyStream : Stream { public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => false; public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } public override void Flush() { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.IO.Pipelines.Tests { public abstract class ReadOnlyStream : Stream { public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => false; public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } public override void Flush() { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } } }
-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/Dataflow/FlowAnnotations.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.Diagnostics.CodeAnalysis; using System.Reflection.Metadata; using Internal.IL; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; using ILLink.Shared; using Debug = System.Diagnostics.Debug; namespace ILCompiler.Dataflow { /// <summary> /// Caches dataflow annotations for type members. /// </summary> public class FlowAnnotations { private readonly TypeAnnotationsHashtable _hashtable; private readonly Logger _logger; public FlowAnnotations(Logger logger, ILProvider ilProvider) { _hashtable = new TypeAnnotationsHashtable(logger, ilProvider); _logger = logger; } public bool RequiresDataflowAnalysis(MethodDesc method) { try { method = method.GetTypicalMethodDefinition(); return GetAnnotations(method.OwningType).TryGetAnnotation(method, out _); } catch (TypeSystemException) { return false; } } public bool RequiresDataflowAnalysis(FieldDesc field) { try { field = field.GetTypicalFieldDefinition(); return GetAnnotations(field.OwningType).TryGetAnnotation(field, out _); } catch (TypeSystemException) { return false; } } public bool HasAnyAnnotations(TypeDesc type) { try { return !GetAnnotations(type.GetTypeDefinition()).IsDefault; } catch (TypeSystemException) { return false; } } /// <summary> /// Retrieves the annotations for the given parameter. /// </summary> /// <param name="parameterIndex">Parameter index in the IL sense. Parameter 0 on instance methods is `this`.</param> public DynamicallyAccessedMemberTypes GetParameterAnnotation(MethodDesc method, int parameterIndex) { method = method.GetTypicalMethodDefinition(); if (GetAnnotations(method.OwningType).TryGetAnnotation(method, out var annotation) && annotation.ParameterAnnotations != null) { return annotation.ParameterAnnotations[parameterIndex]; } return DynamicallyAccessedMemberTypes.None; } public DynamicallyAccessedMemberTypes GetReturnParameterAnnotation(MethodDesc method) { method = method.GetTypicalMethodDefinition(); if (GetAnnotations(method.OwningType).TryGetAnnotation(method, out var annotation)) { return annotation.ReturnParameterAnnotation; } return DynamicallyAccessedMemberTypes.None; } public DynamicallyAccessedMemberTypes GetFieldAnnotation(FieldDesc field) { field = field.GetTypicalFieldDefinition(); if (GetAnnotations(field.OwningType).TryGetAnnotation(field, out var annotation)) { return annotation.Annotation; } return DynamicallyAccessedMemberTypes.None; } public DynamicallyAccessedMemberTypes GetTypeAnnotation(TypeDesc type) { return GetAnnotations(type.GetTypeDefinition()).TypeAnnotation; } public DynamicallyAccessedMemberTypes GetGenericParameterAnnotation(GenericParameterDesc genericParameter) { if (genericParameter is not EcmaGenericParameter ecmaGenericParameter) return DynamicallyAccessedMemberTypes.None; GenericParameter paramDef = ecmaGenericParameter.MetadataReader.GetGenericParameter(ecmaGenericParameter.Handle); if (ecmaGenericParameter.Kind == GenericParameterKind.Type) { TypeDesc parent = ecmaGenericParameter.Module.GetType(paramDef.Parent); if (GetAnnotations(parent).TryGetAnnotation(ecmaGenericParameter, out var annotation)) { return annotation; } } else { Debug.Assert(ecmaGenericParameter.Kind == GenericParameterKind.Method); MethodDesc parent = ecmaGenericParameter.Module.GetMethod(paramDef.Parent); if (GetAnnotations(parent.OwningType).TryGetAnnotation(parent, out var methodAnnotation) && methodAnnotation.TryGetAnnotation(genericParameter, out var annotation)) { return annotation; } } return DynamicallyAccessedMemberTypes.None; } public bool ShouldWarnWhenAccessedForReflection(MethodDesc method) { method = method.GetTypicalMethodDefinition(); if (!GetAnnotations(method.OwningType).TryGetAnnotation(method, out var annotation)) return false; if (annotation.ParameterAnnotations == null && annotation.ReturnParameterAnnotation == DynamicallyAccessedMemberTypes.None) return false; // If the method only has annotation on the return value and it's not virtual avoid warning. // Return value annotations are "consumed" by the caller of a method, and as such there is nothing // wrong calling these dynamically. The only problem can happen if something overrides a virtual // method with annotated return value at runtime - in this case the trimmer can't validate // that the method will return only types which fulfill the annotation's requirements. // For example: // class BaseWithAnnotation // { // [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] // public abstract Type GetTypeWithFields(); // } // // class UsingTheBase // { // public void PrintFields(Base base) // { // // No warning here - GetTypeWithFields is correctly annotated to allow GetFields on the return value. // Console.WriteLine(string.Join(" ", base.GetTypeWithFields().GetFields().Select(f => f.Name))); // } // } // // If at runtime (through ref emit) something generates code like this: // class DerivedAtRuntimeFromBase // { // // No point in adding annotation on the return value - nothing will look at it anyway // // Linker will not see this code, so there are no checks // public override Type GetTypeWithFields() { return typeof(TestType); } // } // // If TestType from above is trimmed, it may note have all its fields, and there would be no warnings generated. // But there has to be code like this somewhere in the app, in order to generate the override: // class RuntimeTypeGenerator // { // public MethodInfo GetBaseMethod() // { // // This must warn - that the GetTypeWithFields has annotation on the return value // return typeof(BaseWithAnnotation).GetMethod("GetTypeWithFields"); // } // } return method.IsVirtual || annotation.ParameterAnnotations != null; } public bool ShouldWarnWhenAccessedForReflection(FieldDesc field) { field = field.GetTypicalFieldDefinition(); return GetAnnotations(field.OwningType).TryGetAnnotation(field, out _); } private TypeAnnotations GetAnnotations(TypeDesc type) { return _hashtable.GetOrCreateValue(type); } private class TypeAnnotationsHashtable : LockFreeReaderHashtable<TypeDesc, TypeAnnotations> { private readonly ILProvider _ilProvider; private readonly Logger _logger; public TypeAnnotationsHashtable(Logger logger, ILProvider ilProvider) => (_logger, _ilProvider) = (logger, ilProvider); private static DynamicallyAccessedMemberTypes GetMemberTypesForDynamicallyAccessedMembersAttribute(MetadataReader reader, CustomAttributeHandleCollection customAttributeHandles) { CustomAttributeHandle ca = reader.GetCustomAttributeHandle(customAttributeHandles, "System.Diagnostics.CodeAnalysis", "DynamicallyAccessedMembersAttribute"); if (ca.IsNil) return DynamicallyAccessedMemberTypes.None; BlobReader blobReader = reader.GetBlobReader(reader.GetCustomAttribute(ca).Value); Debug.Assert(blobReader.Length == 8); if (blobReader.Length != 8) return DynamicallyAccessedMemberTypes.None; blobReader.ReadUInt16(); // Prolog return (DynamicallyAccessedMemberTypes)blobReader.ReadUInt32(); } protected override bool CompareKeyToValue(TypeDesc key, TypeAnnotations value) => key == value.Type; protected override bool CompareValueToValue(TypeAnnotations value1, TypeAnnotations value2) => value1.Type == value2.Type; protected override int GetKeyHashCode(TypeDesc key) => key.GetHashCode(); protected override int GetValueHashCode(TypeAnnotations value) => value.Type.GetHashCode(); protected override TypeAnnotations CreateValueFromKey(TypeDesc key) { // We scan the entire type at this point; the reason for doing that is properties. // // We allow annotating properties, but those annotations need to flow onto individual get/set methods // and backing fields. Without scanning all properties, we can't answer questions about fields/methods. // And if we're going over all properties, we might as well go over everything else to keep things simple. Debug.Assert(key.IsTypeDefinition); if (key is not EcmaType ecmaType) return new TypeAnnotations(key, DynamicallyAccessedMemberTypes.None, null, null, null); MetadataReader reader = ecmaType.MetadataReader; // class, interface, struct can have annotations TypeDefinition typeDef = reader.GetTypeDefinition(ecmaType.Handle); DynamicallyAccessedMemberTypes typeAnnotation = GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, typeDef.GetCustomAttributes()); try { // Also inherit annotation from bases TypeDesc baseType = key.BaseType; while (baseType != null) { TypeDefinition baseTypeDef = reader.GetTypeDefinition(((EcmaType)baseType.GetTypeDefinition()).Handle); typeAnnotation |= GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, baseTypeDef.GetCustomAttributes()); baseType = baseType.BaseType; } // And inherit them from interfaces foreach (DefType runtimeInterface in key.RuntimeInterfaces) { TypeDefinition interfaceTypeDef = reader.GetTypeDefinition(((EcmaType)runtimeInterface.GetTypeDefinition()).Handle); typeAnnotation |= GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, interfaceTypeDef.GetCustomAttributes()); } } catch (TypeSystemException) { // If the class hierarchy is not walkable, just stop collecting the annotations. } var annotatedFields = new ArrayBuilder<FieldAnnotation>(); // First go over all fields with an explicit annotation foreach (EcmaField field in ecmaType.GetFields()) { FieldDefinition fieldDef = reader.GetFieldDefinition(field.Handle); DynamicallyAccessedMemberTypes annotation = GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, fieldDef.GetCustomAttributes()); if (annotation == DynamicallyAccessedMemberTypes.None) { continue; } if (!IsTypeInterestingForDataflow(field.FieldType)) { // Already know that there's a non-empty annotation on a field which is not System.Type/String and we're about to ignore it _logger.LogWarning(field, DiagnosticId.DynamicallyAccessedMembersOnFieldCanOnlyApplyToTypesOrStrings, field.GetDisplayName()); continue; } annotatedFields.Add(new FieldAnnotation(field, annotation)); } var annotatedMethods = new ArrayBuilder<MethodAnnotations>(); // Next go over all methods with an explicit annotation foreach (EcmaMethod method in ecmaType.GetMethods()) { DynamicallyAccessedMemberTypes[] paramAnnotations = null; // We convert indices from metadata space to IL space here. // IL space assigns index 0 to the `this` parameter on instance methods. DynamicallyAccessedMemberTypes methodMemberTypes = GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, reader.GetMethodDefinition(method.Handle).GetCustomAttributes()); MethodSignature signature; try { signature = method.Signature; } catch (TypeSystemException) { // If we cannot resolve things in the signature, just move along. continue; } int offset; if (!signature.IsStatic) { offset = 1; } else { offset = 0; } // If there's an annotation on the method itself and it's one of the special types (System.Type for example) // treat that annotation as annotating the "this" parameter. if (methodMemberTypes != DynamicallyAccessedMemberTypes.None) { if (IsTypeInterestingForDataflow(method.OwningType) && !signature.IsStatic) { paramAnnotations = new DynamicallyAccessedMemberTypes[signature.Length + offset]; paramAnnotations[0] = methodMemberTypes; } else { _logger.LogWarning(method, DiagnosticId.DynamicallyAccessedMembersIsNotAllowedOnMethods); } } MethodDefinition methodDef = reader.GetMethodDefinition(method.Handle); ParameterHandleCollection parameterHandles = methodDef.GetParameters(); DynamicallyAccessedMemberTypes returnAnnotation = DynamicallyAccessedMemberTypes.None; foreach (ParameterHandle parameterHandle in parameterHandles) { Parameter parameter = reader.GetParameter(parameterHandle); if (parameter.SequenceNumber == 0) { // this is the return parameter returnAnnotation = GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, parameter.GetCustomAttributes()); if (returnAnnotation != DynamicallyAccessedMemberTypes.None && !IsTypeInterestingForDataflow(signature.ReturnType)) { _logger.LogWarning(method, DiagnosticId.DynamicallyAccessedMembersOnMethodReturnValueCanOnlyApplyToTypesOrStrings, method.GetDisplayName()); } } else { DynamicallyAccessedMemberTypes pa = GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, parameter.GetCustomAttributes()); if (pa == DynamicallyAccessedMemberTypes.None) continue; if (!IsTypeInterestingForDataflow(signature[parameter.SequenceNumber - 1])) { _logger.LogWarning(method, DiagnosticId.DynamicallyAccessedMembersOnMethodParameterCanOnlyApplyToTypesOrStrings, $"#{parameter.SequenceNumber}", method.GetDisplayName()); continue; } if (paramAnnotations == null) { paramAnnotations = new DynamicallyAccessedMemberTypes[signature.Length + offset]; } paramAnnotations[parameter.SequenceNumber - 1 + offset] = pa; } } DynamicallyAccessedMemberTypes[] genericParameterAnnotations = null; foreach (EcmaGenericParameter genericParameter in method.Instantiation) { GenericParameter genericParameterDef = reader.GetGenericParameter(genericParameter.Handle); var annotation = GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, genericParameterDef.GetCustomAttributes()); if (annotation != DynamicallyAccessedMemberTypes.None) { if (genericParameterAnnotations == null) genericParameterAnnotations = new DynamicallyAccessedMemberTypes[method.Instantiation.Length]; genericParameterAnnotations[genericParameter.Index] = annotation; } } if (returnAnnotation != DynamicallyAccessedMemberTypes.None || paramAnnotations != null || genericParameterAnnotations != null) { annotatedMethods.Add(new MethodAnnotations(method, paramAnnotations, returnAnnotation, genericParameterAnnotations)); } } // Next up are properties. Annotations on properties are kind of meta because we need to // map them to annotations on methods/fields. They're syntactic sugar - what they do is expressible // by placing attribute on the accessor/backing field. For complex properties, that's what people // will need to do anyway. Like so: // // [field: Attribute] // Type MyProperty // { // [return: Attribute] // get; // [value: Attribute] // set; // } foreach (PropertyDefinitionHandle propertyHandle in reader.GetTypeDefinition(ecmaType.Handle).GetProperties()) { DynamicallyAccessedMemberTypes annotation = GetMemberTypesForDynamicallyAccessedMembersAttribute( reader, reader.GetPropertyDefinition(propertyHandle).GetCustomAttributes()); if (annotation == DynamicallyAccessedMemberTypes.None) continue; PropertyPseudoDesc property = new PropertyPseudoDesc(ecmaType, propertyHandle); if (!IsTypeInterestingForDataflow(property.Signature.ReturnType)) { _logger.LogWarning(property, DiagnosticId.DynamicallyAccessedMembersOnPropertyCanOnlyApplyToTypesOrStrings, property.GetDisplayName()); continue; } FieldDesc backingFieldFromSetter = null; // Propagate the annotation to the setter method MethodDesc setMethod = property.SetMethod; if (setMethod != null) { // Abstract property backing field propagation doesn't make sense, and any derived property will be validated // to have the exact same annotations on getter/setter, and thus if it has a detectable backing field that will be validated as well. MethodIL methodBody = _ilProvider.GetMethodIL(setMethod); if (methodBody != null) { // Look for the compiler generated backing field. If it doesn't work out simply move on. In such case we would still // propagate the annotation to the setter/getter and later on when analyzing the setter/getter we will warn // that the field (which ever it is) must be annotated as well. ScanMethodBodyForFieldAccess(methodBody, write: true, out backingFieldFromSetter); } if (annotatedMethods.Any(a => a.Method == setMethod)) { _logger.LogWarning(setMethod, DiagnosticId.DynamicallyAccessedMembersConflictsBetweenPropertyAndAccessor, property.GetDisplayName(), setMethod.GetDisplayName()); } else { int offset = setMethod.Signature.IsStatic ? 0 : 1; if (setMethod.Signature.Length > 0) { DynamicallyAccessedMemberTypes[] paramAnnotations = new DynamicallyAccessedMemberTypes[setMethod.Signature.Length + offset]; paramAnnotations[paramAnnotations.Length - 1] = annotation; annotatedMethods.Add(new MethodAnnotations(setMethod, paramAnnotations, DynamicallyAccessedMemberTypes.None, null)); } } } FieldDesc backingFieldFromGetter = null; // Propagate the annotation to the getter method MethodDesc getMethod = property.GetMethod; if (getMethod != null) { // Abstract property backing field propagation doesn't make sense, and any derived property will be validated // to have the exact same annotations on getter/setter, and thus if it has a detectable backing field that will be validated as well. MethodIL methodBody = _ilProvider.GetMethodIL(getMethod); if (methodBody != null) { // Look for the compiler generated backing field. If it doesn't work out simply move on. In such case we would still // propagate the annotation to the setter/getter and later on when analyzing the setter/getter we will warn // that the field (which ever it is) must be annotated as well. ScanMethodBodyForFieldAccess(methodBody, write: false, out backingFieldFromGetter); } if (annotatedMethods.Any(a => a.Method == getMethod)) { _logger.LogWarning(getMethod, DiagnosticId.DynamicallyAccessedMembersConflictsBetweenPropertyAndAccessor, property.GetDisplayName(), getMethod.GetDisplayName()); } else { annotatedMethods.Add(new MethodAnnotations(getMethod, null, annotation, null)); } } FieldDesc backingField; if (backingFieldFromGetter != null && backingFieldFromSetter != null && backingFieldFromGetter != backingFieldFromSetter) { _logger.LogWarning(property, DiagnosticId.DynamicallyAccessedMembersCouldNotFindBackingField, property.GetDisplayName()); backingField = null; } else { backingField = backingFieldFromGetter ?? backingFieldFromSetter; } if (backingField != null) { if (annotatedFields.Any(a => a.Field == backingField)) { _logger.LogWarning(backingField, DiagnosticId.DynamicallyAccessedMembersOnPropertyConflictsWithBackingField, property.GetDisplayName(), backingField.GetDisplayName()); } else { annotatedFields.Add(new FieldAnnotation(backingField, annotation)); } } } DynamicallyAccessedMemberTypes[] typeGenericParameterAnnotations = null; foreach (EcmaGenericParameter genericParameter in ecmaType.Instantiation) { GenericParameter genericParameterDef = reader.GetGenericParameter(genericParameter.Handle); var annotation = GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, genericParameterDef.GetCustomAttributes()); if (annotation != DynamicallyAccessedMemberTypes.None) { if (typeGenericParameterAnnotations == null) typeGenericParameterAnnotations = new DynamicallyAccessedMemberTypes[ecmaType.Instantiation.Length]; typeGenericParameterAnnotations[genericParameter.Index] = annotation; } } return new TypeAnnotations(ecmaType, typeAnnotation, annotatedMethods.ToArray(), annotatedFields.ToArray(), typeGenericParameterAnnotations); } private static bool ScanMethodBodyForFieldAccess(MethodIL body, bool write, out FieldDesc found) { // Tries to find the backing field for a property getter/setter. // Returns true if this is a method body that we can unambiguously analyze. // The found field could still be null if there's no backing store. found = null; ILReader ilReader = new ILReader(body.GetILBytes()); while (ilReader.HasNext) { ILOpcode opcode = ilReader.ReadILOpcode(); switch (opcode) { case ILOpcode.ldsfld when !write: case ILOpcode.ldfld when !write: case ILOpcode.stsfld when write: case ILOpcode.stfld when write: { // This writes/reads multiple fields - can't guess which one is the backing store. // Return failure. if (found != null) { found = null; return false; } found = (FieldDesc)body.GetObject(ilReader.ReadILToken()); } break; default: ilReader.Skip(opcode); break; } } if (found == null) { // Doesn't access any fields. Could be e.g. "Type Foo => typeof(Bar);" // Return success. return true; } if (found.OwningType != body.OwningMethod.OwningType || found.IsStatic != body.OwningMethod.Signature.IsStatic || !found.HasCustomAttribute("System.Runtime.CompilerServices", "CompilerGeneratedAttribute")) { // A couple heuristics to make sure we got the right field. // Return failure. found = null; return false; } return true; } private bool IsTypeInterestingForDataflow(TypeDesc type) { // NOTE: this method is not particulary fast. It's assumed that the caller limits // calls to this method as much as possible. if (type.IsWellKnownType(WellKnownType.String)) return true; if (!type.IsDefType) return false; var metadataType = (MetadataType)type; foreach (var intf in type.RuntimeInterfaces) { if (intf.Name == "IReflect" && intf.Namespace == "System.Reflection") return true; } if (metadataType.Name == "IReflect" && metadataType.Namespace == "System.Reflection") return true; do { if (metadataType.Name == "Type" && metadataType.Namespace == "System") return true; } while ((metadataType = metadataType.MetadataBaseType) != null); return false; } } internal void ValidateMethodAnnotationsAreSame(MethodDesc method, MethodDesc baseMethod) { method = method.GetTypicalMethodDefinition(); baseMethod = baseMethod.GetTypicalMethodDefinition(); GetAnnotations(method.OwningType).TryGetAnnotation(method, out var methodAnnotations); GetAnnotations(baseMethod.OwningType).TryGetAnnotation(baseMethod, out var baseMethodAnnotations); if (methodAnnotations.ReturnParameterAnnotation != baseMethodAnnotations.ReturnParameterAnnotation) LogValidationWarning(method.Signature.ReturnType, baseMethod, method); if (methodAnnotations.ParameterAnnotations != null || baseMethodAnnotations.ParameterAnnotations != null) { if (methodAnnotations.ParameterAnnotations == null) ValidateMethodParametersHaveNoAnnotations(baseMethodAnnotations.ParameterAnnotations, method, baseMethod, method); else if (baseMethodAnnotations.ParameterAnnotations == null) ValidateMethodParametersHaveNoAnnotations(methodAnnotations.ParameterAnnotations, method, baseMethod, method); else { if (methodAnnotations.ParameterAnnotations.Length != baseMethodAnnotations.ParameterAnnotations.Length) return; for (int parameterIndex = 0; parameterIndex < methodAnnotations.ParameterAnnotations.Length; parameterIndex++) { if (methodAnnotations.ParameterAnnotations[parameterIndex] != baseMethodAnnotations.ParameterAnnotations[parameterIndex]) LogValidationWarning( DiagnosticUtilities.GetMethodParameterFromIndex(method, parameterIndex), DiagnosticUtilities.GetMethodParameterFromIndex(baseMethod, parameterIndex), method); } } } if (methodAnnotations.GenericParameterAnnotations != null || baseMethodAnnotations.GenericParameterAnnotations != null) { if (methodAnnotations.GenericParameterAnnotations == null) ValidateMethodGenericParametersHaveNoAnnotations(baseMethodAnnotations.GenericParameterAnnotations, method, baseMethod, method); else if (baseMethodAnnotations.GenericParameterAnnotations == null) ValidateMethodGenericParametersHaveNoAnnotations(methodAnnotations.GenericParameterAnnotations, method, baseMethod, method); else { if (methodAnnotations.GenericParameterAnnotations.Length != baseMethodAnnotations.GenericParameterAnnotations.Length) return; for (int genericParameterIndex = 0; genericParameterIndex < methodAnnotations.GenericParameterAnnotations.Length; genericParameterIndex++) { if (methodAnnotations.GenericParameterAnnotations[genericParameterIndex] != baseMethodAnnotations.GenericParameterAnnotations[genericParameterIndex]) { LogValidationWarning( method.Instantiation[genericParameterIndex], baseMethod.Instantiation[genericParameterIndex], method); } } } } } void ValidateMethodParametersHaveNoAnnotations(DynamicallyAccessedMemberTypes[] parameterAnnotations, MethodDesc method, MethodDesc baseMethod, MethodDesc origin) { for (int parameterIndex = 0; parameterIndex < parameterAnnotations.Length; parameterIndex++) { var annotation = parameterAnnotations[parameterIndex]; if (annotation != DynamicallyAccessedMemberTypes.None) LogValidationWarning( parameterIndex, baseMethod, origin); } } void ValidateMethodGenericParametersHaveNoAnnotations(DynamicallyAccessedMemberTypes[] genericParameterAnnotations, MethodDesc method, MethodDesc baseMethod, MethodDesc origin) { for (int genericParameterIndex = 0; genericParameterIndex < genericParameterAnnotations.Length; genericParameterIndex++) { if (genericParameterAnnotations[genericParameterIndex] != DynamicallyAccessedMemberTypes.None) { LogValidationWarning( method.Instantiation[genericParameterIndex], baseMethod.Instantiation[genericParameterIndex], origin); } } } void LogValidationWarning(object provider, object baseProvider, MethodDesc origin) { switch (provider) { case int parameterNumber: _logger.LogWarning(origin, DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodParameterBetweenOverrides, $"#{parameterNumber}", DiagnosticUtilities.GetMethodSignatureDisplayName(origin), $"#{parameterNumber}", DiagnosticUtilities.GetMethodSignatureDisplayName((MethodDesc)baseProvider)); break; case GenericParameterDesc genericParameterOverride: _logger.LogWarning(origin, DiagnosticId.DynamicallyAccessedMembersMismatchOnGenericParameterBetweenOverrides, genericParameterOverride.Name, DiagnosticUtilities.GetGenericParameterDeclaringMemberDisplayName(new GenericParameterOrigin(genericParameterOverride)), ((GenericParameterDesc)baseProvider).Name, DiagnosticUtilities.GetGenericParameterDeclaringMemberDisplayName(new GenericParameterOrigin((GenericParameterDesc)baseProvider))); break; case TypeDesc methodReturnType: _logger.LogWarning(origin, DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodReturnValueBetweenOverrides, DiagnosticUtilities.GetMethodSignatureDisplayName(origin), DiagnosticUtilities.GetMethodSignatureDisplayName((MethodDesc)baseProvider)); break; // No fields - it's not possible to have a virtual field and override it case MethodDesc methodDefinition: _logger.LogWarning(origin, DiagnosticId.DynamicallyAccessedMembersMismatchOnImplicitThisBetweenOverrides, DiagnosticUtilities.GetMethodSignatureDisplayName(methodDefinition), DiagnosticUtilities.GetMethodSignatureDisplayName((MethodDesc)baseProvider)); break; default: throw new NotImplementedException($"Unsupported provider type {provider.GetType()}"); } } private class TypeAnnotations { public readonly TypeDesc Type; public readonly DynamicallyAccessedMemberTypes TypeAnnotation; private readonly MethodAnnotations[] _annotatedMethods; private readonly FieldAnnotation[] _annotatedFields; private readonly DynamicallyAccessedMemberTypes[] _genericParameterAnnotations; public bool IsDefault => _annotatedMethods == null && _annotatedFields == null && _genericParameterAnnotations == null; public TypeAnnotations( TypeDesc type, DynamicallyAccessedMemberTypes typeAnnotations, MethodAnnotations[] annotatedMethods, FieldAnnotation[] annotatedFields, DynamicallyAccessedMemberTypes[] genericParameterAnnotations) => (Type, TypeAnnotation, _annotatedMethods, _annotatedFields, _genericParameterAnnotations) = (type, typeAnnotations, annotatedMethods, annotatedFields, genericParameterAnnotations); public bool TryGetAnnotation(MethodDesc method, out MethodAnnotations annotations) { annotations = default; if (_annotatedMethods == null) { return false; } foreach (var m in _annotatedMethods) { if (m.Method == method) { annotations = m; return true; } } return false; } public bool TryGetAnnotation(FieldDesc field, out FieldAnnotation annotation) { annotation = default; if (_annotatedFields == null) { return false; } foreach (var f in _annotatedFields) { if (f.Field == field) { annotation = f; return true; } } return false; } public bool TryGetAnnotation(GenericParameterDesc genericParameter, out DynamicallyAccessedMemberTypes annotation) { annotation = default; if (_genericParameterAnnotations == null) return false; for (int genericParameterIndex = 0; genericParameterIndex < _genericParameterAnnotations.Length; genericParameterIndex++) { if (Type.Instantiation[genericParameterIndex] == genericParameter) { annotation = _genericParameterAnnotations[genericParameterIndex]; return true; } } return false; } } private readonly struct MethodAnnotations { public readonly MethodDesc Method; public readonly DynamicallyAccessedMemberTypes[] ParameterAnnotations; public readonly DynamicallyAccessedMemberTypes ReturnParameterAnnotation; public readonly DynamicallyAccessedMemberTypes[] GenericParameterAnnotations; public MethodAnnotations( MethodDesc method, DynamicallyAccessedMemberTypes[] paramAnnotations, DynamicallyAccessedMemberTypes returnParamAnnotations, DynamicallyAccessedMemberTypes[] genericParameterAnnotations) => (Method, ParameterAnnotations, ReturnParameterAnnotation, GenericParameterAnnotations) = (method, paramAnnotations, returnParamAnnotations, genericParameterAnnotations); public bool TryGetAnnotation(GenericParameterDesc genericParameter, out DynamicallyAccessedMemberTypes annotation) { annotation = default; if (GenericParameterAnnotations == null) return false; for (int genericParameterIndex = 0; genericParameterIndex < GenericParameterAnnotations.Length; genericParameterIndex++) { if (Method.Instantiation[genericParameterIndex] == genericParameter) { annotation = GenericParameterAnnotations[genericParameterIndex]; return true; } } return false; } } private readonly struct FieldAnnotation { public readonly FieldDesc Field; public readonly DynamicallyAccessedMemberTypes Annotation; public FieldAnnotation(FieldDesc field, DynamicallyAccessedMemberTypes annotation) => (Field, Annotation) = (field, annotation); } } }
// 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.Diagnostics.CodeAnalysis; using System.Reflection.Metadata; using Internal.IL; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; using ILLink.Shared; using Debug = System.Diagnostics.Debug; namespace ILCompiler.Dataflow { /// <summary> /// Caches dataflow annotations for type members. /// </summary> public class FlowAnnotations { private readonly TypeAnnotationsHashtable _hashtable; private readonly Logger _logger; public FlowAnnotations(Logger logger, ILProvider ilProvider) { _hashtable = new TypeAnnotationsHashtable(logger, ilProvider); _logger = logger; } public bool RequiresDataflowAnalysis(MethodDesc method) { try { method = method.GetTypicalMethodDefinition(); return GetAnnotations(method.OwningType).TryGetAnnotation(method, out _); } catch (TypeSystemException) { return false; } } public bool RequiresDataflowAnalysis(FieldDesc field) { try { field = field.GetTypicalFieldDefinition(); return GetAnnotations(field.OwningType).TryGetAnnotation(field, out _); } catch (TypeSystemException) { return false; } } public bool HasAnyAnnotations(TypeDesc type) { try { return !GetAnnotations(type.GetTypeDefinition()).IsDefault; } catch (TypeSystemException) { return false; } } /// <summary> /// Retrieves the annotations for the given parameter. /// </summary> /// <param name="parameterIndex">Parameter index in the IL sense. Parameter 0 on instance methods is `this`.</param> public DynamicallyAccessedMemberTypes GetParameterAnnotation(MethodDesc method, int parameterIndex) { method = method.GetTypicalMethodDefinition(); if (GetAnnotations(method.OwningType).TryGetAnnotation(method, out var annotation) && annotation.ParameterAnnotations != null) { return annotation.ParameterAnnotations[parameterIndex]; } return DynamicallyAccessedMemberTypes.None; } public DynamicallyAccessedMemberTypes GetReturnParameterAnnotation(MethodDesc method) { method = method.GetTypicalMethodDefinition(); if (GetAnnotations(method.OwningType).TryGetAnnotation(method, out var annotation)) { return annotation.ReturnParameterAnnotation; } return DynamicallyAccessedMemberTypes.None; } public DynamicallyAccessedMemberTypes GetFieldAnnotation(FieldDesc field) { field = field.GetTypicalFieldDefinition(); if (GetAnnotations(field.OwningType).TryGetAnnotation(field, out var annotation)) { return annotation.Annotation; } return DynamicallyAccessedMemberTypes.None; } public DynamicallyAccessedMemberTypes GetTypeAnnotation(TypeDesc type) { return GetAnnotations(type.GetTypeDefinition()).TypeAnnotation; } public DynamicallyAccessedMemberTypes GetGenericParameterAnnotation(GenericParameterDesc genericParameter) { if (genericParameter is not EcmaGenericParameter ecmaGenericParameter) return DynamicallyAccessedMemberTypes.None; GenericParameter paramDef = ecmaGenericParameter.MetadataReader.GetGenericParameter(ecmaGenericParameter.Handle); if (ecmaGenericParameter.Kind == GenericParameterKind.Type) { TypeDesc parent = ecmaGenericParameter.Module.GetType(paramDef.Parent); if (GetAnnotations(parent).TryGetAnnotation(ecmaGenericParameter, out var annotation)) { return annotation; } } else { Debug.Assert(ecmaGenericParameter.Kind == GenericParameterKind.Method); MethodDesc parent = ecmaGenericParameter.Module.GetMethod(paramDef.Parent); if (GetAnnotations(parent.OwningType).TryGetAnnotation(parent, out var methodAnnotation) && methodAnnotation.TryGetAnnotation(genericParameter, out var annotation)) { return annotation; } } return DynamicallyAccessedMemberTypes.None; } public bool ShouldWarnWhenAccessedForReflection(MethodDesc method) { method = method.GetTypicalMethodDefinition(); if (!GetAnnotations(method.OwningType).TryGetAnnotation(method, out var annotation)) return false; if (annotation.ParameterAnnotations == null && annotation.ReturnParameterAnnotation == DynamicallyAccessedMemberTypes.None) return false; // If the method only has annotation on the return value and it's not virtual avoid warning. // Return value annotations are "consumed" by the caller of a method, and as such there is nothing // wrong calling these dynamically. The only problem can happen if something overrides a virtual // method with annotated return value at runtime - in this case the trimmer can't validate // that the method will return only types which fulfill the annotation's requirements. // For example: // class BaseWithAnnotation // { // [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] // public abstract Type GetTypeWithFields(); // } // // class UsingTheBase // { // public void PrintFields(Base base) // { // // No warning here - GetTypeWithFields is correctly annotated to allow GetFields on the return value. // Console.WriteLine(string.Join(" ", base.GetTypeWithFields().GetFields().Select(f => f.Name))); // } // } // // If at runtime (through ref emit) something generates code like this: // class DerivedAtRuntimeFromBase // { // // No point in adding annotation on the return value - nothing will look at it anyway // // Linker will not see this code, so there are no checks // public override Type GetTypeWithFields() { return typeof(TestType); } // } // // If TestType from above is trimmed, it may note have all its fields, and there would be no warnings generated. // But there has to be code like this somewhere in the app, in order to generate the override: // class RuntimeTypeGenerator // { // public MethodInfo GetBaseMethod() // { // // This must warn - that the GetTypeWithFields has annotation on the return value // return typeof(BaseWithAnnotation).GetMethod("GetTypeWithFields"); // } // } return method.IsVirtual || annotation.ParameterAnnotations != null; } public bool ShouldWarnWhenAccessedForReflection(FieldDesc field) { field = field.GetTypicalFieldDefinition(); return GetAnnotations(field.OwningType).TryGetAnnotation(field, out _); } private TypeAnnotations GetAnnotations(TypeDesc type) { return _hashtable.GetOrCreateValue(type); } private class TypeAnnotationsHashtable : LockFreeReaderHashtable<TypeDesc, TypeAnnotations> { private readonly ILProvider _ilProvider; private readonly Logger _logger; public TypeAnnotationsHashtable(Logger logger, ILProvider ilProvider) => (_logger, _ilProvider) = (logger, ilProvider); private static DynamicallyAccessedMemberTypes GetMemberTypesForDynamicallyAccessedMembersAttribute(MetadataReader reader, CustomAttributeHandleCollection customAttributeHandles) { CustomAttributeHandle ca = reader.GetCustomAttributeHandle(customAttributeHandles, "System.Diagnostics.CodeAnalysis", "DynamicallyAccessedMembersAttribute"); if (ca.IsNil) return DynamicallyAccessedMemberTypes.None; BlobReader blobReader = reader.GetBlobReader(reader.GetCustomAttribute(ca).Value); Debug.Assert(blobReader.Length == 8); if (blobReader.Length != 8) return DynamicallyAccessedMemberTypes.None; blobReader.ReadUInt16(); // Prolog return (DynamicallyAccessedMemberTypes)blobReader.ReadUInt32(); } protected override bool CompareKeyToValue(TypeDesc key, TypeAnnotations value) => key == value.Type; protected override bool CompareValueToValue(TypeAnnotations value1, TypeAnnotations value2) => value1.Type == value2.Type; protected override int GetKeyHashCode(TypeDesc key) => key.GetHashCode(); protected override int GetValueHashCode(TypeAnnotations value) => value.Type.GetHashCode(); protected override TypeAnnotations CreateValueFromKey(TypeDesc key) { // We scan the entire type at this point; the reason for doing that is properties. // // We allow annotating properties, but those annotations need to flow onto individual get/set methods // and backing fields. Without scanning all properties, we can't answer questions about fields/methods. // And if we're going over all properties, we might as well go over everything else to keep things simple. Debug.Assert(key.IsTypeDefinition); if (key is not EcmaType ecmaType) return new TypeAnnotations(key, DynamicallyAccessedMemberTypes.None, null, null, null); MetadataReader reader = ecmaType.MetadataReader; // class, interface, struct can have annotations TypeDefinition typeDef = reader.GetTypeDefinition(ecmaType.Handle); DynamicallyAccessedMemberTypes typeAnnotation = GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, typeDef.GetCustomAttributes()); try { // Also inherit annotation from bases TypeDesc baseType = key.BaseType; while (baseType != null) { TypeDefinition baseTypeDef = reader.GetTypeDefinition(((EcmaType)baseType.GetTypeDefinition()).Handle); typeAnnotation |= GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, baseTypeDef.GetCustomAttributes()); baseType = baseType.BaseType; } // And inherit them from interfaces foreach (DefType runtimeInterface in key.RuntimeInterfaces) { TypeDefinition interfaceTypeDef = reader.GetTypeDefinition(((EcmaType)runtimeInterface.GetTypeDefinition()).Handle); typeAnnotation |= GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, interfaceTypeDef.GetCustomAttributes()); } } catch (TypeSystemException) { // If the class hierarchy is not walkable, just stop collecting the annotations. } var annotatedFields = new ArrayBuilder<FieldAnnotation>(); // First go over all fields with an explicit annotation foreach (EcmaField field in ecmaType.GetFields()) { FieldDefinition fieldDef = reader.GetFieldDefinition(field.Handle); DynamicallyAccessedMemberTypes annotation = GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, fieldDef.GetCustomAttributes()); if (annotation == DynamicallyAccessedMemberTypes.None) { continue; } if (!IsTypeInterestingForDataflow(field.FieldType)) { // Already know that there's a non-empty annotation on a field which is not System.Type/String and we're about to ignore it _logger.LogWarning(field, DiagnosticId.DynamicallyAccessedMembersOnFieldCanOnlyApplyToTypesOrStrings, field.GetDisplayName()); continue; } annotatedFields.Add(new FieldAnnotation(field, annotation)); } var annotatedMethods = new ArrayBuilder<MethodAnnotations>(); // Next go over all methods with an explicit annotation foreach (EcmaMethod method in ecmaType.GetMethods()) { DynamicallyAccessedMemberTypes[] paramAnnotations = null; // We convert indices from metadata space to IL space here. // IL space assigns index 0 to the `this` parameter on instance methods. DynamicallyAccessedMemberTypes methodMemberTypes = GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, reader.GetMethodDefinition(method.Handle).GetCustomAttributes()); MethodSignature signature; try { signature = method.Signature; } catch (TypeSystemException) { // If we cannot resolve things in the signature, just move along. continue; } int offset; if (!signature.IsStatic) { offset = 1; } else { offset = 0; } // If there's an annotation on the method itself and it's one of the special types (System.Type for example) // treat that annotation as annotating the "this" parameter. if (methodMemberTypes != DynamicallyAccessedMemberTypes.None) { if (IsTypeInterestingForDataflow(method.OwningType) && !signature.IsStatic) { paramAnnotations = new DynamicallyAccessedMemberTypes[signature.Length + offset]; paramAnnotations[0] = methodMemberTypes; } else { _logger.LogWarning(method, DiagnosticId.DynamicallyAccessedMembersIsNotAllowedOnMethods); } } MethodDefinition methodDef = reader.GetMethodDefinition(method.Handle); ParameterHandleCollection parameterHandles = methodDef.GetParameters(); DynamicallyAccessedMemberTypes returnAnnotation = DynamicallyAccessedMemberTypes.None; foreach (ParameterHandle parameterHandle in parameterHandles) { Parameter parameter = reader.GetParameter(parameterHandle); if (parameter.SequenceNumber == 0) { // this is the return parameter returnAnnotation = GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, parameter.GetCustomAttributes()); if (returnAnnotation != DynamicallyAccessedMemberTypes.None && !IsTypeInterestingForDataflow(signature.ReturnType)) { _logger.LogWarning(method, DiagnosticId.DynamicallyAccessedMembersOnMethodReturnValueCanOnlyApplyToTypesOrStrings, method.GetDisplayName()); } } else { DynamicallyAccessedMemberTypes pa = GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, parameter.GetCustomAttributes()); if (pa == DynamicallyAccessedMemberTypes.None) continue; if (!IsTypeInterestingForDataflow(signature[parameter.SequenceNumber - 1])) { _logger.LogWarning(method, DiagnosticId.DynamicallyAccessedMembersOnMethodParameterCanOnlyApplyToTypesOrStrings, $"#{parameter.SequenceNumber}", method.GetDisplayName()); continue; } if (paramAnnotations == null) { paramAnnotations = new DynamicallyAccessedMemberTypes[signature.Length + offset]; } paramAnnotations[parameter.SequenceNumber - 1 + offset] = pa; } } DynamicallyAccessedMemberTypes[] genericParameterAnnotations = null; foreach (EcmaGenericParameter genericParameter in method.Instantiation) { GenericParameter genericParameterDef = reader.GetGenericParameter(genericParameter.Handle); var annotation = GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, genericParameterDef.GetCustomAttributes()); if (annotation != DynamicallyAccessedMemberTypes.None) { if (genericParameterAnnotations == null) genericParameterAnnotations = new DynamicallyAccessedMemberTypes[method.Instantiation.Length]; genericParameterAnnotations[genericParameter.Index] = annotation; } } if (returnAnnotation != DynamicallyAccessedMemberTypes.None || paramAnnotations != null || genericParameterAnnotations != null) { annotatedMethods.Add(new MethodAnnotations(method, paramAnnotations, returnAnnotation, genericParameterAnnotations)); } } // Next up are properties. Annotations on properties are kind of meta because we need to // map them to annotations on methods/fields. They're syntactic sugar - what they do is expressible // by placing attribute on the accessor/backing field. For complex properties, that's what people // will need to do anyway. Like so: // // [field: Attribute] // Type MyProperty // { // [return: Attribute] // get; // [value: Attribute] // set; // } foreach (PropertyDefinitionHandle propertyHandle in reader.GetTypeDefinition(ecmaType.Handle).GetProperties()) { DynamicallyAccessedMemberTypes annotation = GetMemberTypesForDynamicallyAccessedMembersAttribute( reader, reader.GetPropertyDefinition(propertyHandle).GetCustomAttributes()); if (annotation == DynamicallyAccessedMemberTypes.None) continue; PropertyPseudoDesc property = new PropertyPseudoDesc(ecmaType, propertyHandle); if (!IsTypeInterestingForDataflow(property.Signature.ReturnType)) { _logger.LogWarning(property, DiagnosticId.DynamicallyAccessedMembersOnPropertyCanOnlyApplyToTypesOrStrings, property.GetDisplayName()); continue; } FieldDesc backingFieldFromSetter = null; // Propagate the annotation to the setter method MethodDesc setMethod = property.SetMethod; if (setMethod != null) { // Abstract property backing field propagation doesn't make sense, and any derived property will be validated // to have the exact same annotations on getter/setter, and thus if it has a detectable backing field that will be validated as well. MethodIL methodBody = _ilProvider.GetMethodIL(setMethod); if (methodBody != null) { // Look for the compiler generated backing field. If it doesn't work out simply move on. In such case we would still // propagate the annotation to the setter/getter and later on when analyzing the setter/getter we will warn // that the field (which ever it is) must be annotated as well. ScanMethodBodyForFieldAccess(methodBody, write: true, out backingFieldFromSetter); } if (annotatedMethods.Any(a => a.Method == setMethod)) { _logger.LogWarning(setMethod, DiagnosticId.DynamicallyAccessedMembersConflictsBetweenPropertyAndAccessor, property.GetDisplayName(), setMethod.GetDisplayName()); } else { int offset = setMethod.Signature.IsStatic ? 0 : 1; if (setMethod.Signature.Length > 0) { DynamicallyAccessedMemberTypes[] paramAnnotations = new DynamicallyAccessedMemberTypes[setMethod.Signature.Length + offset]; paramAnnotations[paramAnnotations.Length - 1] = annotation; annotatedMethods.Add(new MethodAnnotations(setMethod, paramAnnotations, DynamicallyAccessedMemberTypes.None, null)); } } } FieldDesc backingFieldFromGetter = null; // Propagate the annotation to the getter method MethodDesc getMethod = property.GetMethod; if (getMethod != null) { // Abstract property backing field propagation doesn't make sense, and any derived property will be validated // to have the exact same annotations on getter/setter, and thus if it has a detectable backing field that will be validated as well. MethodIL methodBody = _ilProvider.GetMethodIL(getMethod); if (methodBody != null) { // Look for the compiler generated backing field. If it doesn't work out simply move on. In such case we would still // propagate the annotation to the setter/getter and later on when analyzing the setter/getter we will warn // that the field (which ever it is) must be annotated as well. ScanMethodBodyForFieldAccess(methodBody, write: false, out backingFieldFromGetter); } if (annotatedMethods.Any(a => a.Method == getMethod)) { _logger.LogWarning(getMethod, DiagnosticId.DynamicallyAccessedMembersConflictsBetweenPropertyAndAccessor, property.GetDisplayName(), getMethod.GetDisplayName()); } else { annotatedMethods.Add(new MethodAnnotations(getMethod, null, annotation, null)); } } FieldDesc backingField; if (backingFieldFromGetter != null && backingFieldFromSetter != null && backingFieldFromGetter != backingFieldFromSetter) { _logger.LogWarning(property, DiagnosticId.DynamicallyAccessedMembersCouldNotFindBackingField, property.GetDisplayName()); backingField = null; } else { backingField = backingFieldFromGetter ?? backingFieldFromSetter; } if (backingField != null) { if (annotatedFields.Any(a => a.Field == backingField)) { _logger.LogWarning(backingField, DiagnosticId.DynamicallyAccessedMembersOnPropertyConflictsWithBackingField, property.GetDisplayName(), backingField.GetDisplayName()); } else { annotatedFields.Add(new FieldAnnotation(backingField, annotation)); } } } DynamicallyAccessedMemberTypes[] typeGenericParameterAnnotations = null; foreach (EcmaGenericParameter genericParameter in ecmaType.Instantiation) { GenericParameter genericParameterDef = reader.GetGenericParameter(genericParameter.Handle); var annotation = GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, genericParameterDef.GetCustomAttributes()); if (annotation != DynamicallyAccessedMemberTypes.None) { if (typeGenericParameterAnnotations == null) typeGenericParameterAnnotations = new DynamicallyAccessedMemberTypes[ecmaType.Instantiation.Length]; typeGenericParameterAnnotations[genericParameter.Index] = annotation; } } return new TypeAnnotations(ecmaType, typeAnnotation, annotatedMethods.ToArray(), annotatedFields.ToArray(), typeGenericParameterAnnotations); } private static bool ScanMethodBodyForFieldAccess(MethodIL body, bool write, out FieldDesc found) { // Tries to find the backing field for a property getter/setter. // Returns true if this is a method body that we can unambiguously analyze. // The found field could still be null if there's no backing store. found = null; ILReader ilReader = new ILReader(body.GetILBytes()); while (ilReader.HasNext) { ILOpcode opcode = ilReader.ReadILOpcode(); switch (opcode) { case ILOpcode.ldsfld when !write: case ILOpcode.ldfld when !write: case ILOpcode.stsfld when write: case ILOpcode.stfld when write: { // This writes/reads multiple fields - can't guess which one is the backing store. // Return failure. if (found != null) { found = null; return false; } found = (FieldDesc)body.GetObject(ilReader.ReadILToken()); } break; default: ilReader.Skip(opcode); break; } } if (found == null) { // Doesn't access any fields. Could be e.g. "Type Foo => typeof(Bar);" // Return success. return true; } if (found.OwningType != body.OwningMethod.OwningType || found.IsStatic != body.OwningMethod.Signature.IsStatic || !found.HasCustomAttribute("System.Runtime.CompilerServices", "CompilerGeneratedAttribute")) { // A couple heuristics to make sure we got the right field. // Return failure. found = null; return false; } return true; } private bool IsTypeInterestingForDataflow(TypeDesc type) { // NOTE: this method is not particulary fast. It's assumed that the caller limits // calls to this method as much as possible. if (type.IsWellKnownType(WellKnownType.String)) return true; if (!type.IsDefType) return false; var metadataType = (MetadataType)type; foreach (var intf in type.RuntimeInterfaces) { if (intf.Name == "IReflect" && intf.Namespace == "System.Reflection") return true; } if (metadataType.Name == "IReflect" && metadataType.Namespace == "System.Reflection") return true; do { if (metadataType.Name == "Type" && metadataType.Namespace == "System") return true; } while ((metadataType = metadataType.MetadataBaseType) != null); return false; } } internal void ValidateMethodAnnotationsAreSame(MethodDesc method, MethodDesc baseMethod) { method = method.GetTypicalMethodDefinition(); baseMethod = baseMethod.GetTypicalMethodDefinition(); GetAnnotations(method.OwningType).TryGetAnnotation(method, out var methodAnnotations); GetAnnotations(baseMethod.OwningType).TryGetAnnotation(baseMethod, out var baseMethodAnnotations); if (methodAnnotations.ReturnParameterAnnotation != baseMethodAnnotations.ReturnParameterAnnotation) LogValidationWarning(method.Signature.ReturnType, baseMethod, method); if (methodAnnotations.ParameterAnnotations != null || baseMethodAnnotations.ParameterAnnotations != null) { if (methodAnnotations.ParameterAnnotations == null) ValidateMethodParametersHaveNoAnnotations(baseMethodAnnotations.ParameterAnnotations, method, baseMethod, method); else if (baseMethodAnnotations.ParameterAnnotations == null) ValidateMethodParametersHaveNoAnnotations(methodAnnotations.ParameterAnnotations, method, baseMethod, method); else { if (methodAnnotations.ParameterAnnotations.Length != baseMethodAnnotations.ParameterAnnotations.Length) return; for (int parameterIndex = 0; parameterIndex < methodAnnotations.ParameterAnnotations.Length; parameterIndex++) { if (methodAnnotations.ParameterAnnotations[parameterIndex] != baseMethodAnnotations.ParameterAnnotations[parameterIndex]) LogValidationWarning( DiagnosticUtilities.GetMethodParameterFromIndex(method, parameterIndex), DiagnosticUtilities.GetMethodParameterFromIndex(baseMethod, parameterIndex), method); } } } if (methodAnnotations.GenericParameterAnnotations != null || baseMethodAnnotations.GenericParameterAnnotations != null) { if (methodAnnotations.GenericParameterAnnotations == null) ValidateMethodGenericParametersHaveNoAnnotations(baseMethodAnnotations.GenericParameterAnnotations, method, baseMethod, method); else if (baseMethodAnnotations.GenericParameterAnnotations == null) ValidateMethodGenericParametersHaveNoAnnotations(methodAnnotations.GenericParameterAnnotations, method, baseMethod, method); else { if (methodAnnotations.GenericParameterAnnotations.Length != baseMethodAnnotations.GenericParameterAnnotations.Length) return; for (int genericParameterIndex = 0; genericParameterIndex < methodAnnotations.GenericParameterAnnotations.Length; genericParameterIndex++) { if (methodAnnotations.GenericParameterAnnotations[genericParameterIndex] != baseMethodAnnotations.GenericParameterAnnotations[genericParameterIndex]) { LogValidationWarning( method.Instantiation[genericParameterIndex], baseMethod.Instantiation[genericParameterIndex], method); } } } } } void ValidateMethodParametersHaveNoAnnotations(DynamicallyAccessedMemberTypes[] parameterAnnotations, MethodDesc method, MethodDesc baseMethod, MethodDesc origin) { for (int parameterIndex = 0; parameterIndex < parameterAnnotations.Length; parameterIndex++) { var annotation = parameterAnnotations[parameterIndex]; if (annotation != DynamicallyAccessedMemberTypes.None) LogValidationWarning( parameterIndex, baseMethod, origin); } } void ValidateMethodGenericParametersHaveNoAnnotations(DynamicallyAccessedMemberTypes[] genericParameterAnnotations, MethodDesc method, MethodDesc baseMethod, MethodDesc origin) { for (int genericParameterIndex = 0; genericParameterIndex < genericParameterAnnotations.Length; genericParameterIndex++) { if (genericParameterAnnotations[genericParameterIndex] != DynamicallyAccessedMemberTypes.None) { LogValidationWarning( method.Instantiation[genericParameterIndex], baseMethod.Instantiation[genericParameterIndex], origin); } } } void LogValidationWarning(object provider, object baseProvider, MethodDesc origin) { switch (provider) { case int parameterNumber: _logger.LogWarning(origin, DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodParameterBetweenOverrides, $"#{parameterNumber}", DiagnosticUtilities.GetMethodSignatureDisplayName(origin), $"#{parameterNumber}", DiagnosticUtilities.GetMethodSignatureDisplayName((MethodDesc)baseProvider)); break; case GenericParameterDesc genericParameterOverride: _logger.LogWarning(origin, DiagnosticId.DynamicallyAccessedMembersMismatchOnGenericParameterBetweenOverrides, genericParameterOverride.Name, DiagnosticUtilities.GetGenericParameterDeclaringMemberDisplayName(new GenericParameterOrigin(genericParameterOverride)), ((GenericParameterDesc)baseProvider).Name, DiagnosticUtilities.GetGenericParameterDeclaringMemberDisplayName(new GenericParameterOrigin((GenericParameterDesc)baseProvider))); break; case TypeDesc methodReturnType: _logger.LogWarning(origin, DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodReturnValueBetweenOverrides, DiagnosticUtilities.GetMethodSignatureDisplayName(origin), DiagnosticUtilities.GetMethodSignatureDisplayName((MethodDesc)baseProvider)); break; // No fields - it's not possible to have a virtual field and override it case MethodDesc methodDefinition: _logger.LogWarning(origin, DiagnosticId.DynamicallyAccessedMembersMismatchOnImplicitThisBetweenOverrides, DiagnosticUtilities.GetMethodSignatureDisplayName(methodDefinition), DiagnosticUtilities.GetMethodSignatureDisplayName((MethodDesc)baseProvider)); break; default: throw new NotImplementedException($"Unsupported provider type {provider.GetType()}"); } } private class TypeAnnotations { public readonly TypeDesc Type; public readonly DynamicallyAccessedMemberTypes TypeAnnotation; private readonly MethodAnnotations[] _annotatedMethods; private readonly FieldAnnotation[] _annotatedFields; private readonly DynamicallyAccessedMemberTypes[] _genericParameterAnnotations; public bool IsDefault => _annotatedMethods == null && _annotatedFields == null && _genericParameterAnnotations == null; public TypeAnnotations( TypeDesc type, DynamicallyAccessedMemberTypes typeAnnotations, MethodAnnotations[] annotatedMethods, FieldAnnotation[] annotatedFields, DynamicallyAccessedMemberTypes[] genericParameterAnnotations) => (Type, TypeAnnotation, _annotatedMethods, _annotatedFields, _genericParameterAnnotations) = (type, typeAnnotations, annotatedMethods, annotatedFields, genericParameterAnnotations); public bool TryGetAnnotation(MethodDesc method, out MethodAnnotations annotations) { annotations = default; if (_annotatedMethods == null) { return false; } foreach (var m in _annotatedMethods) { if (m.Method == method) { annotations = m; return true; } } return false; } public bool TryGetAnnotation(FieldDesc field, out FieldAnnotation annotation) { annotation = default; if (_annotatedFields == null) { return false; } foreach (var f in _annotatedFields) { if (f.Field == field) { annotation = f; return true; } } return false; } public bool TryGetAnnotation(GenericParameterDesc genericParameter, out DynamicallyAccessedMemberTypes annotation) { annotation = default; if (_genericParameterAnnotations == null) return false; for (int genericParameterIndex = 0; genericParameterIndex < _genericParameterAnnotations.Length; genericParameterIndex++) { if (Type.Instantiation[genericParameterIndex] == genericParameter) { annotation = _genericParameterAnnotations[genericParameterIndex]; return true; } } return false; } } private readonly struct MethodAnnotations { public readonly MethodDesc Method; public readonly DynamicallyAccessedMemberTypes[] ParameterAnnotations; public readonly DynamicallyAccessedMemberTypes ReturnParameterAnnotation; public readonly DynamicallyAccessedMemberTypes[] GenericParameterAnnotations; public MethodAnnotations( MethodDesc method, DynamicallyAccessedMemberTypes[] paramAnnotations, DynamicallyAccessedMemberTypes returnParamAnnotations, DynamicallyAccessedMemberTypes[] genericParameterAnnotations) => (Method, ParameterAnnotations, ReturnParameterAnnotation, GenericParameterAnnotations) = (method, paramAnnotations, returnParamAnnotations, genericParameterAnnotations); public bool TryGetAnnotation(GenericParameterDesc genericParameter, out DynamicallyAccessedMemberTypes annotation) { annotation = default; if (GenericParameterAnnotations == null) return false; for (int genericParameterIndex = 0; genericParameterIndex < GenericParameterAnnotations.Length; genericParameterIndex++) { if (Method.Instantiation[genericParameterIndex] == genericParameter) { annotation = GenericParameterAnnotations[genericParameterIndex]; return true; } } return false; } } private readonly struct FieldAnnotation { public readonly FieldDesc Field; public readonly DynamicallyAccessedMemberTypes Annotation; public FieldAnnotation(FieldDesc field, DynamicallyAccessedMemberTypes annotation) => (Field, Annotation) = (field, annotation); } } }
-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/CoreMangLib/system/enum/enumiconvertibletosingle.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; /// <summary> /// System.Enum.IConvertibleToSingle(provider) /// </summary> public class EnumIConvertibleToSingle { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Convert zero to single"); try { color c1 = color.blue; IConvertible i1 = c1 as IConvertible; float f1 = i1.ToSingle(null); if (f1 != 0.0) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Test a normal enum of value 3 "); try { color c2 = color.white; IConvertible i2 = c2 as IConvertible; float f2 = i2.ToSingle(null); if (f2 != 3.0) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Convert an int32 to single"); try { e_test c2 = e_test.itemB; IConvertible i2 = c2 as IConvertible; float f2 = i2.ToSingle(null); if (f2 != Int32.MaxValue) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Convert an int64.MinValue to single"); try { e_test c2 = e_test.itemC; IConvertible i2 = c2 as IConvertible; float f2 = i2.ToSingle(null); if (f2 != Int64.MinValue) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Convert a negative to single"); try { e_test c2 = e_test.itemA; IConvertible i2 = c2 as IConvertible; float f2 = i2.ToSingle(null); if (f2 != -4) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: Convert a negative zero to single"); try { e_test c2 = e_test.itemD; IConvertible i2 = c2 as IConvertible; float f2 = i2.ToSingle(null); if (f2 != 0) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases #endregion #endregion public static int Main() { EnumIConvertibleToSingle test = new EnumIConvertibleToSingle(); TestLibrary.TestFramework.BeginTestCase("EnumIConvertibleToSingle"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } enum color { blue = 0, white = 3, red, } enum e_test : long { itemA = -4, itemB = Int32.MaxValue, itemC = Int64.MinValue, itemD = -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; /// <summary> /// System.Enum.IConvertibleToSingle(provider) /// </summary> public class EnumIConvertibleToSingle { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Convert zero to single"); try { color c1 = color.blue; IConvertible i1 = c1 as IConvertible; float f1 = i1.ToSingle(null); if (f1 != 0.0) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Test a normal enum of value 3 "); try { color c2 = color.white; IConvertible i2 = c2 as IConvertible; float f2 = i2.ToSingle(null); if (f2 != 3.0) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Convert an int32 to single"); try { e_test c2 = e_test.itemB; IConvertible i2 = c2 as IConvertible; float f2 = i2.ToSingle(null); if (f2 != Int32.MaxValue) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Convert an int64.MinValue to single"); try { e_test c2 = e_test.itemC; IConvertible i2 = c2 as IConvertible; float f2 = i2.ToSingle(null); if (f2 != Int64.MinValue) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Convert a negative to single"); try { e_test c2 = e_test.itemA; IConvertible i2 = c2 as IConvertible; float f2 = i2.ToSingle(null); if (f2 != -4) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: Convert a negative zero to single"); try { e_test c2 = e_test.itemD; IConvertible i2 = c2 as IConvertible; float f2 = i2.ToSingle(null); if (f2 != 0) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases #endregion #endregion public static int Main() { EnumIConvertibleToSingle test = new EnumIConvertibleToSingle(); TestLibrary.TestFramework.BeginTestCase("EnumIConvertibleToSingle"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } enum color { blue = 0, white = 3, red, } enum e_test : long { itemA = -4, itemB = Int32.MaxValue, itemC = Int64.MinValue, itemD = -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/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/AbsoluteCompareGreaterThanOrEqual.Vector128.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.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 AbsoluteCompareGreaterThanOrEqual_Vector128_Double() { var test = new SimpleBinaryOpTest__AbsoluteCompareGreaterThanOrEqual_Vector128_Double(); 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__AbsoluteCompareGreaterThanOrEqual_Vector128_Double { 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 != 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<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__AbsoluteCompareGreaterThanOrEqual_Vector128_Double testClass) { var result = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AbsoluteCompareGreaterThanOrEqual_Vector128_Double testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual( AdvSimd.LoadVector128((Double*)(pFld1)), AdvSimd.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__AbsoluteCompareGreaterThanOrEqual_Vector128_Double() { 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__AbsoluteCompareGreaterThanOrEqual_Vector128_Double() { 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 => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual( 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 = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual( AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((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(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual), 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(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((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 = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual( _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 = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual( AdvSimd.LoadVector128((Double*)(pClsVar1)), AdvSimd.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 = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual(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.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AbsoluteCompareGreaterThanOrEqual_Vector128_Double(); var result = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual(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__AbsoluteCompareGreaterThanOrEqual_Vector128_Double(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual( AdvSimd.LoadVector128((Double*)(pFld1)), AdvSimd.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 = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual(_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 = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual( AdvSimd.LoadVector128((Double*)(pFld1)), AdvSimd.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 = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual(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.Arm64.AbsoluteCompareGreaterThanOrEqual( AdvSimd.LoadVector128((Double*)(&test._fld1)), AdvSimd.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; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(Helpers.AbsoluteCompareGreaterThanOrEqual(left[i], right[i])) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual)}<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.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 AbsoluteCompareGreaterThanOrEqual_Vector128_Double() { var test = new SimpleBinaryOpTest__AbsoluteCompareGreaterThanOrEqual_Vector128_Double(); 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__AbsoluteCompareGreaterThanOrEqual_Vector128_Double { 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 != 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<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__AbsoluteCompareGreaterThanOrEqual_Vector128_Double testClass) { var result = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AbsoluteCompareGreaterThanOrEqual_Vector128_Double testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual( AdvSimd.LoadVector128((Double*)(pFld1)), AdvSimd.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__AbsoluteCompareGreaterThanOrEqual_Vector128_Double() { 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__AbsoluteCompareGreaterThanOrEqual_Vector128_Double() { 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 => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual( 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 = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual( AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((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(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual), 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(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((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 = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual( _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 = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual( AdvSimd.LoadVector128((Double*)(pClsVar1)), AdvSimd.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 = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual(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.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AbsoluteCompareGreaterThanOrEqual_Vector128_Double(); var result = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual(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__AbsoluteCompareGreaterThanOrEqual_Vector128_Double(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual( AdvSimd.LoadVector128((Double*)(pFld1)), AdvSimd.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 = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual(_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 = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual( AdvSimd.LoadVector128((Double*)(pFld1)), AdvSimd.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 = AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual(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.Arm64.AbsoluteCompareGreaterThanOrEqual( AdvSimd.LoadVector128((Double*)(&test._fld1)), AdvSimd.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; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(Helpers.AbsoluteCompareGreaterThanOrEqual(left[i], right[i])) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.AbsoluteCompareGreaterThanOrEqual)}<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.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/Marshal/PtrToStringAutoTests.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; namespace System.Runtime.InteropServices.Tests { public class PtrToStringAutoTests { [Fact] public void PtrToStringAuto_ZeroPtrNoLength_ReturnsNull() { Assert.Null(Marshal.PtrToStringAuto(IntPtr.Zero)); } [Fact] public void PtrToStringAuto_ZeroPtrWithLength_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("ptr", () => Marshal.PtrToStringAuto(IntPtr.Zero, 0)); } [Fact] public void PtrToStringAuto_NegativeLength_ThrowsArgumentOutOfRangeException() { string s = "Hello World"; IntPtr ptr = Marshal.StringToCoTaskMemAuto(s); try { AssertExtensions.Throws<ArgumentOutOfRangeException, ArgumentException>(() => Marshal.PtrToStringAuto(ptr, -1)); } finally { Marshal.FreeCoTaskMem(ptr); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Runtime.InteropServices.Tests { public class PtrToStringAutoTests { [Fact] public void PtrToStringAuto_ZeroPtrNoLength_ReturnsNull() { Assert.Null(Marshal.PtrToStringAuto(IntPtr.Zero)); } [Fact] public void PtrToStringAuto_ZeroPtrWithLength_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("ptr", () => Marshal.PtrToStringAuto(IntPtr.Zero, 0)); } [Fact] public void PtrToStringAuto_NegativeLength_ThrowsArgumentOutOfRangeException() { string s = "Hello World"; IntPtr ptr = Marshal.StringToCoTaskMemAuto(s); try { AssertExtensions.Throws<ArgumentOutOfRangeException, ArgumentException>(() => Marshal.PtrToStringAuto(ptr, -1)); } finally { Marshal.FreeCoTaskMem(ptr); } } } }
-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/ShiftLogicalSaturate.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 ShiftLogicalSaturate_Vector128_Int32() { var test = new SimpleBinaryOpTest__ShiftLogicalSaturate_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 SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_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 Vector128<Int32> _fld1; public Vector128<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<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>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Int32 testClass) { var result = AdvSimd.ShiftLogicalSaturate(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Int32 testClass) { fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(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<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = 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 Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__ShiftLogicalSaturate_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>>()); } public SimpleBinaryOpTest__ShiftLogicalSaturate_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 < 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.ShiftLogicalSaturate( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_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.ShiftLogicalSaturate( AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_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.ShiftLogicalSaturate), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<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.ShiftLogicalSaturate), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftLogicalSaturate( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Int32*)(pClsVar1)), AdvSimd.LoadVector128((Int32*)(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<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = AdvSimd.ShiftLogicalSaturate(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.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.ShiftLogicalSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Int32(); var result = AdvSimd.ShiftLogicalSaturate(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__ShiftLogicalSaturate_Vector128_Int32(); fixed (Vector128<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) { var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftLogicalSaturate(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(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.ShiftLogicalSaturate(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.ShiftLogicalSaturate( AdvSimd.LoadVector128((Int32*)(&test._fld1)), AdvSimd.LoadVector128((Int32*)(&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<Int32> op1, Vector128<Int32> op2, 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]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, 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>(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 outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftLogicalSaturate(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftLogicalSaturate)}<Int32>(Vector128<Int32>, Vector128<Int32>): {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 ShiftLogicalSaturate_Vector128_Int32() { var test = new SimpleBinaryOpTest__ShiftLogicalSaturate_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 SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_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 Vector128<Int32> _fld1; public Vector128<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<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>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Int32 testClass) { var result = AdvSimd.ShiftLogicalSaturate(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Int32 testClass) { fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(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<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = 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 Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__ShiftLogicalSaturate_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>>()); } public SimpleBinaryOpTest__ShiftLogicalSaturate_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 < 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.ShiftLogicalSaturate( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_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.ShiftLogicalSaturate( AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_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.ShiftLogicalSaturate), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<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.ShiftLogicalSaturate), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftLogicalSaturate( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Int32*)(pClsVar1)), AdvSimd.LoadVector128((Int32*)(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<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = AdvSimd.ShiftLogicalSaturate(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.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.ShiftLogicalSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_Int32(); var result = AdvSimd.ShiftLogicalSaturate(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__ShiftLogicalSaturate_Vector128_Int32(); fixed (Vector128<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) { var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftLogicalSaturate(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.ShiftLogicalSaturate( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(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.ShiftLogicalSaturate(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.ShiftLogicalSaturate( AdvSimd.LoadVector128((Int32*)(&test._fld1)), AdvSimd.LoadVector128((Int32*)(&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<Int32> op1, Vector128<Int32> op2, 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]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, 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>(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 outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftLogicalSaturate(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftLogicalSaturate)}<Int32>(Vector128<Int32>, Vector128<Int32>): {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/General/NotSupported/Vector128BooleanAsInt16.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 Vector128BooleanAsInt16() { bool succeeded = false; try { Vector128<short> result = default(Vector128<bool>).AsInt16(); } catch (NotSupportedException) { succeeded = true; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128BooleanAsInt16: 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 Vector128BooleanAsInt16() { bool succeeded = false; try { Vector128<short> result = default(Vector128<bool>).AsInt16(); } catch (NotSupportedException) { succeeded = true; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128BooleanAsInt16: 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.Speech/src/Internal/SapiInterop/SapiInterop.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; using Microsoft.Win32.SafeHandles; namespace System.Speech.Internal.SapiInterop { #region Enum // See sperror.h internal enum SAPIErrorCodes { S_OK = 0, // 0x00000000 S_FALSE = 1, // 0x00000001 SP_NO_RULE_ACTIVE = 0x00045055, SP_NO_RULES_TO_ACTIVATE = 282747, // 0x0004507B S_LIMIT_REACHED = 0x0004507F, E_FAIL = -2147467259, // 0x80004005 SP_NO_PARSE_FOUND = 0x0004502c, SP_WORD_EXISTS_WITHOUT_PRONUNCIATION = 0x00045037, // 282679 SPERR_FIRST = -2147201023, // 0x80045001 == SPERR_UNINITIALIZED SPERR_LAST = -2147200877, // 0x80045093 == SPERR_VOICE_NOT_FOUND STG_E_FILENOTFOUND = -2147287038, // 0x80030002 CLASS_E_CLASSNOTAVAILABLE = -2147221231, // 0x80040111 REGDB_E_CLASSNOTREG = -2147221164, // 0x80040154 SPERR_UNSUPPORTED_FORMAT = -2147201021, // 0x80045003 SPERR_UNSUPPORTED_PHONEME = -2147200902, // 0x8004507A SPERR_VOICE_NOT_FOUND = -2147200877, // 0x80045093 SPERR_NOT_IN_LEX = -2147200999, // 0x80045019 SPERR_TOO_MANY_GRAMMARS = -2147200990, // 0x80045022 SPERR_INVALID_IMPORT = -2147200988, // 0x80045024 SPERR_STREAM_CLOSED = -2147200968, // 0x80045038 SPERR_NO_MORE_ITEMS = -2147200967, // 0x80045039 SPERR_NOT_FOUND = -2147200966, // 0x8004503A SPERR_NOT_TOPLEVEL_RULE = -2147200940, // 0x80045054 SPERR_SHARED_ENGINE_DISABLED = -2147200906, // 0x80045076 SPERR_RECOGNIZER_NOT_FOUND = -2147200905, // 0x80045077 SPERR_AUDIO_NOT_FOUND = -2147200904, // 0x80045078 SPERR_NOT_SUPPORTED_FOR_INPROC_RECOGNIZER = -2147200893, // 0x80045083 SPERR_LEX_INVALID_DATA = -2147200891, // 0x80045085 SPERR_CFG_INVALID_DATA = -2147200890 // 0x80045086 } #endregion Enum #region SAPI constants internal static class SapiConstants { internal const string SPPROP_RESPONSE_SPEED = "ResponseSpeed"; internal const string SPPROP_COMPLEX_RESPONSE_SPEED = "ComplexResponseSpeed"; internal const string SPPROP_CFG_CONFIDENCE_REJECTION_THRESHOLD = "CFGConfidenceRejectionThreshold"; internal const uint SPDF_ALL = 0xff; // Throws exception if the specified Rule does not have a valid Id. internal static SRID SapiErrorCode2SRID(SAPIErrorCodes code) { if (code >= SAPIErrorCodes.SPERR_FIRST && code <= SAPIErrorCodes.SPERR_LAST) { return (SRID)((int)SRID.SapiErrorUninitialized + (code - SAPIErrorCodes.SPERR_FIRST)); } else { switch (code) { case SAPIErrorCodes.SP_NO_RULE_ACTIVE: return SRID.SapiErrorNoRuleActive; case SAPIErrorCodes.SP_NO_RULES_TO_ACTIVATE: return SRID.SapiErrorNoRulesToActivate; case SAPIErrorCodes.SP_NO_PARSE_FOUND: return SRID.NoParseFound; case SAPIErrorCodes.S_FALSE: return SRID.UnexpectedError; default: return (SRID)unchecked(-1); } } } } #endregion #region Interface [ComImport, Guid("14056589-E16C-11D2-BB90-00C04F8EE6C0"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISpObjectToken : ISpDataKey { // ISpDataKey Methods [PreserveSig] new int SetData([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, uint cbData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] pData); [PreserveSig] new int GetData([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, ref uint pcbData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] byte[] pData); [PreserveSig] new int SetStringValue([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, [MarshalAs(UnmanagedType.LPWStr)] string pszValue); [PreserveSig] new int GetStringValue([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszValue); [PreserveSig] new int SetDWORD([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, uint dwValue); [PreserveSig] new int GetDWORD([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, ref uint pdwValue); [PreserveSig] new int OpenKey([MarshalAs(UnmanagedType.LPWStr)] string pszSubKeyName, out ISpDataKey ppSubKey); [PreserveSig] new int CreateKey([MarshalAs(UnmanagedType.LPWStr)] string pszSubKey, out ISpDataKey ppSubKey); [PreserveSig] new int DeleteKey([MarshalAs(UnmanagedType.LPWStr)] string pszSubKey); [PreserveSig] new int DeleteValue([MarshalAs(UnmanagedType.LPWStr)] string pszValueName); [PreserveSig] new int EnumKeys(uint Index, [MarshalAs(UnmanagedType.LPWStr)] out string ppszSubKeyName); [PreserveSig] new int EnumValues(uint Index, [MarshalAs(UnmanagedType.LPWStr)] out string ppszValueName); // ISpObjectToken Methods void SetId([MarshalAs(UnmanagedType.LPWStr)] string pszCategoryId, [MarshalAs(UnmanagedType.LPWStr)] string pszTokenId, [MarshalAs(UnmanagedType.Bool)] bool fCreateIfNotExist); void GetId(out IntPtr ppszCoMemTokenId); void Slot15(); // void GetCategory(out ISpObjectTokenCategory ppTokenCategory); void Slot16(); // void CreateInstance(object pUnkOuter, UInt32 dwClsContext, ref Guid riid, ref IntPtr ppvObject); void Slot17(); // void GetStorageFileName(ref Guid clsidCaller, [MarshalAs(UnmanagedType.LPWStr)] string pszValueName, [MarshalAs(UnmanagedType.LPWStr)] string pszFileNameSpecifier, UInt32 nFolder, [MarshalAs(UnmanagedType.LPWStr)] out string ppszFilePath); void Slot18(); // void RemoveStorageFileName(ref Guid clsidCaller, [MarshalAs(UnmanagedType.LPWStr)] string pszKeyName, int fDeleteFile); void Slot19(); // void Remove(ref Guid pclsidCaller); void Slot20(); // void IsUISupported([MarshalAs(UnmanagedType.LPWStr)] string pszTypeOfUI, IntPtr pvExtraData, UInt32 cbExtraData, object punkObject, ref Int32 pfSupported); void Slot21(); // void DisplayUI(UInt32 hWndParent, [MarshalAs(UnmanagedType.LPWStr)] string pszTitle, [MarshalAs(UnmanagedType.LPWStr)] string pszTypeOfUI, IntPtr pvExtraData, UInt32 cbExtraData, object punkObject); void MatchesAttributes([MarshalAs(UnmanagedType.LPWStr)] string pszAttributes, [MarshalAs(UnmanagedType.Bool)] out bool pfMatches); } //--- ISpObjectWithToken ---------------------------------------------------- [ComImport, Guid("5B559F40-E952-11D2-BB91-00C04F8EE6C0"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISpObjectWithToken { [PreserveSig] int SetObjectToken(ISpObjectToken pToken); [PreserveSig] int GetObjectToken(out ISpObjectToken ppToken); }; [ComImport, Guid("14056581-E16C-11D2-BB90-00C04F8EE6C0"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISpDataKey { // ISpDataKey Methods [PreserveSig] int SetData([MarshalAs(UnmanagedType.LPWStr)] string valueName, uint cbData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data); [PreserveSig] int GetData([MarshalAs(UnmanagedType.LPWStr)] string valueName, ref uint pcbData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] byte[] data); [PreserveSig] int SetStringValue([MarshalAs(UnmanagedType.LPWStr)] string valueName, [MarshalAs(UnmanagedType.LPWStr)] string value); [PreserveSig] int GetStringValue([MarshalAs(UnmanagedType.LPWStr)] string valueName, [MarshalAs(UnmanagedType.LPWStr)] out string value); [PreserveSig] int SetDWORD([MarshalAs(UnmanagedType.LPWStr)] string valueName, uint dwValue); [PreserveSig] int GetDWORD([MarshalAs(UnmanagedType.LPWStr)] string valueName, ref uint pdwValue); [PreserveSig] int OpenKey([MarshalAs(UnmanagedType.LPWStr)] string subKeyName, out ISpDataKey ppSubKey); [PreserveSig] int CreateKey([MarshalAs(UnmanagedType.LPWStr)] string subKey, out ISpDataKey ppSubKey); [PreserveSig] int DeleteKey([MarshalAs(UnmanagedType.LPWStr)] string subKey); [PreserveSig] int DeleteValue([MarshalAs(UnmanagedType.LPWStr)] string valueName); [PreserveSig] int EnumKeys(uint index, [MarshalAs(UnmanagedType.LPWStr)] out string ppszSubKeyName); [PreserveSig] int EnumValues(uint index, [MarshalAs(UnmanagedType.LPWStr)] out string valueName); } [ComImport, Guid("92A66E2B-C830-4149-83DF-6FC2BA1E7A5B"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISpRegDataKey : ISpDataKey { // ISpDataKey Methods [PreserveSig] new int SetData([MarshalAs(UnmanagedType.LPWStr)] string valueName, uint cbData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data); [PreserveSig] new int GetData([MarshalAs(UnmanagedType.LPWStr)] string valueName, ref uint pcbData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] byte[] data); [PreserveSig] new int SetStringValue([MarshalAs(UnmanagedType.LPWStr)] string valueName, [MarshalAs(UnmanagedType.LPWStr)] string value); [PreserveSig] new int GetStringValue([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszValue); [PreserveSig] new int SetDWORD([MarshalAs(UnmanagedType.LPWStr)] string valueName, uint dwValue); [PreserveSig] new int GetDWORD([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, ref uint pdwValue); [PreserveSig] new int OpenKey([MarshalAs(UnmanagedType.LPWStr)] string pszSubKeyName, out ISpDataKey ppSubKey); [PreserveSig] new int CreateKey([MarshalAs(UnmanagedType.LPWStr)] string subKey, out ISpDataKey ppSubKey); [PreserveSig] new int DeleteKey([MarshalAs(UnmanagedType.LPWStr)] string subKey); [PreserveSig] new int DeleteValue([MarshalAs(UnmanagedType.LPWStr)] string valueName); [PreserveSig] new int EnumKeys(uint index, [MarshalAs(UnmanagedType.LPWStr)] out string ppszSubKeyName); [PreserveSig] new int EnumValues(uint Index, [MarshalAs(UnmanagedType.LPWStr)] out string ppszValueName); // ISpRegDataKey Method [PreserveSig] int SetKey(SafeRegistryHandle hkey, bool fReadOnly); } [ComImport, Guid("2D3D3845-39AF-4850-BBF9-40B49780011D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISpObjectTokenCategory : ISpDataKey { // ISpDataKey Methods [PreserveSig] new int SetData([MarshalAs(UnmanagedType.LPWStr)] string valueName, uint cbData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data); [PreserveSig] new int GetData([MarshalAs(UnmanagedType.LPWStr)] string valueName, ref uint pcbData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] byte[] data); [PreserveSig] new int SetStringValue([MarshalAs(UnmanagedType.LPWStr)] string valueName, [MarshalAs(UnmanagedType.LPWStr)] string value); [PreserveSig] new void GetStringValue([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszValue); [PreserveSig] new int SetDWORD([MarshalAs(UnmanagedType.LPWStr)] string valueName, uint dwValue); [PreserveSig] new int GetDWORD([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, ref uint pdwValue); [PreserveSig] new int OpenKey([MarshalAs(UnmanagedType.LPWStr)] string pszSubKeyName, out ISpDataKey ppSubKey); [PreserveSig] new int CreateKey([MarshalAs(UnmanagedType.LPWStr)] string subKey, out ISpDataKey ppSubKey); [PreserveSig] new int DeleteKey([MarshalAs(UnmanagedType.LPWStr)] string subKey); [PreserveSig] new int DeleteValue([MarshalAs(UnmanagedType.LPWStr)] string valueName); [PreserveSig] new int EnumKeys(uint index, [MarshalAs(UnmanagedType.LPWStr)] out string ppszSubKeyName); [PreserveSig] new int EnumValues(uint Index, [MarshalAs(UnmanagedType.LPWStr)] out string ppszValueName); // ISpObjectTokenCategory Methods void SetId([MarshalAs(UnmanagedType.LPWStr)] string pszCategoryId, [MarshalAs(UnmanagedType.Bool)] bool fCreateIfNotExist); void GetId([MarshalAs(UnmanagedType.LPWStr)] out string ppszCoMemCategoryId); void Slot14(); // void GetDataKey(System.Speech.Internal.SPDATAKEYLOCATION spdkl, out ISpDataKey ppDataKey); void EnumTokens([MarshalAs(UnmanagedType.LPWStr)] string pzsReqAttribs, [MarshalAs(UnmanagedType.LPWStr)] string pszOptAttribs, out IEnumSpObjectTokens ppEnum); void Slot16(); // void SetDefaultTokenId([MarshalAs(UnmanagedType.LPWStr)] string pszTokenId); void GetDefaultTokenId([MarshalAs(UnmanagedType.LPWStr)] out string ppszCoMemTokenId); } [ComImport, Guid("06B64F9E-7FDA-11D2-B4F2-00C04F797396"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IEnumSpObjectTokens { void Slot1(); // void Next(UInt32 celt, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0), Out] ISpObjectToken[] pelt, out UInt32 pceltFetched); void Slot2(); // void Skip(UInt32 celt); void Slot3(); // void Reset(); void Slot4(); // void Clone(out IEnumSpObjectTokens ppEnum); void Item(uint Index, out ISpObjectToken ppToken); void GetCount(out uint pCount); } [ComImport, Guid("B2745EFD-42CE-48CA-81F1-A96E02538A90"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISpPhoneticAlphabetSelection { void IsAlphabetUPS([MarshalAs(UnmanagedType.Bool)] out bool pfIsUPS); void SetAlphabetToUPS([MarshalAs(UnmanagedType.Bool)] bool fForceUPS); } [ComImport, Guid("EF411752-3736-4CB4-9C8C-8EF4CCB58EFE")] internal class SpObjectToken { } [ComImport, Guid("A910187F-0C7A-45AC-92CC-59EDAFB77B53")] internal class SpObjectTokenCategory { } [ComImport, Guid("D9F6EE60-58C9-458B-88E1-2F908FD7F87C")] internal class SpDataKey { } #endregion #region Utility Class internal static class SAPIGuids { internal static readonly Guid SPDFID_WaveFormatEx = new("C31ADBAE-527F-4ff5-A230-F62BB61FF70C"); internal static readonly Guid SPDFID_Text = new("7CEEF9F9-3D13-11d2-9EE7-00C04F797396"); } #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.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; namespace System.Speech.Internal.SapiInterop { #region Enum // See sperror.h internal enum SAPIErrorCodes { S_OK = 0, // 0x00000000 S_FALSE = 1, // 0x00000001 SP_NO_RULE_ACTIVE = 0x00045055, SP_NO_RULES_TO_ACTIVATE = 282747, // 0x0004507B S_LIMIT_REACHED = 0x0004507F, E_FAIL = -2147467259, // 0x80004005 SP_NO_PARSE_FOUND = 0x0004502c, SP_WORD_EXISTS_WITHOUT_PRONUNCIATION = 0x00045037, // 282679 SPERR_FIRST = -2147201023, // 0x80045001 == SPERR_UNINITIALIZED SPERR_LAST = -2147200877, // 0x80045093 == SPERR_VOICE_NOT_FOUND STG_E_FILENOTFOUND = -2147287038, // 0x80030002 CLASS_E_CLASSNOTAVAILABLE = -2147221231, // 0x80040111 REGDB_E_CLASSNOTREG = -2147221164, // 0x80040154 SPERR_UNSUPPORTED_FORMAT = -2147201021, // 0x80045003 SPERR_UNSUPPORTED_PHONEME = -2147200902, // 0x8004507A SPERR_VOICE_NOT_FOUND = -2147200877, // 0x80045093 SPERR_NOT_IN_LEX = -2147200999, // 0x80045019 SPERR_TOO_MANY_GRAMMARS = -2147200990, // 0x80045022 SPERR_INVALID_IMPORT = -2147200988, // 0x80045024 SPERR_STREAM_CLOSED = -2147200968, // 0x80045038 SPERR_NO_MORE_ITEMS = -2147200967, // 0x80045039 SPERR_NOT_FOUND = -2147200966, // 0x8004503A SPERR_NOT_TOPLEVEL_RULE = -2147200940, // 0x80045054 SPERR_SHARED_ENGINE_DISABLED = -2147200906, // 0x80045076 SPERR_RECOGNIZER_NOT_FOUND = -2147200905, // 0x80045077 SPERR_AUDIO_NOT_FOUND = -2147200904, // 0x80045078 SPERR_NOT_SUPPORTED_FOR_INPROC_RECOGNIZER = -2147200893, // 0x80045083 SPERR_LEX_INVALID_DATA = -2147200891, // 0x80045085 SPERR_CFG_INVALID_DATA = -2147200890 // 0x80045086 } #endregion Enum #region SAPI constants internal static class SapiConstants { internal const string SPPROP_RESPONSE_SPEED = "ResponseSpeed"; internal const string SPPROP_COMPLEX_RESPONSE_SPEED = "ComplexResponseSpeed"; internal const string SPPROP_CFG_CONFIDENCE_REJECTION_THRESHOLD = "CFGConfidenceRejectionThreshold"; internal const uint SPDF_ALL = 0xff; // Throws exception if the specified Rule does not have a valid Id. internal static SRID SapiErrorCode2SRID(SAPIErrorCodes code) { if (code >= SAPIErrorCodes.SPERR_FIRST && code <= SAPIErrorCodes.SPERR_LAST) { return (SRID)((int)SRID.SapiErrorUninitialized + (code - SAPIErrorCodes.SPERR_FIRST)); } else { switch (code) { case SAPIErrorCodes.SP_NO_RULE_ACTIVE: return SRID.SapiErrorNoRuleActive; case SAPIErrorCodes.SP_NO_RULES_TO_ACTIVATE: return SRID.SapiErrorNoRulesToActivate; case SAPIErrorCodes.SP_NO_PARSE_FOUND: return SRID.NoParseFound; case SAPIErrorCodes.S_FALSE: return SRID.UnexpectedError; default: return (SRID)unchecked(-1); } } } } #endregion #region Interface [ComImport, Guid("14056589-E16C-11D2-BB90-00C04F8EE6C0"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISpObjectToken : ISpDataKey { // ISpDataKey Methods [PreserveSig] new int SetData([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, uint cbData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] pData); [PreserveSig] new int GetData([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, ref uint pcbData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] byte[] pData); [PreserveSig] new int SetStringValue([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, [MarshalAs(UnmanagedType.LPWStr)] string pszValue); [PreserveSig] new int GetStringValue([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszValue); [PreserveSig] new int SetDWORD([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, uint dwValue); [PreserveSig] new int GetDWORD([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, ref uint pdwValue); [PreserveSig] new int OpenKey([MarshalAs(UnmanagedType.LPWStr)] string pszSubKeyName, out ISpDataKey ppSubKey); [PreserveSig] new int CreateKey([MarshalAs(UnmanagedType.LPWStr)] string pszSubKey, out ISpDataKey ppSubKey); [PreserveSig] new int DeleteKey([MarshalAs(UnmanagedType.LPWStr)] string pszSubKey); [PreserveSig] new int DeleteValue([MarshalAs(UnmanagedType.LPWStr)] string pszValueName); [PreserveSig] new int EnumKeys(uint Index, [MarshalAs(UnmanagedType.LPWStr)] out string ppszSubKeyName); [PreserveSig] new int EnumValues(uint Index, [MarshalAs(UnmanagedType.LPWStr)] out string ppszValueName); // ISpObjectToken Methods void SetId([MarshalAs(UnmanagedType.LPWStr)] string pszCategoryId, [MarshalAs(UnmanagedType.LPWStr)] string pszTokenId, [MarshalAs(UnmanagedType.Bool)] bool fCreateIfNotExist); void GetId(out IntPtr ppszCoMemTokenId); void Slot15(); // void GetCategory(out ISpObjectTokenCategory ppTokenCategory); void Slot16(); // void CreateInstance(object pUnkOuter, UInt32 dwClsContext, ref Guid riid, ref IntPtr ppvObject); void Slot17(); // void GetStorageFileName(ref Guid clsidCaller, [MarshalAs(UnmanagedType.LPWStr)] string pszValueName, [MarshalAs(UnmanagedType.LPWStr)] string pszFileNameSpecifier, UInt32 nFolder, [MarshalAs(UnmanagedType.LPWStr)] out string ppszFilePath); void Slot18(); // void RemoveStorageFileName(ref Guid clsidCaller, [MarshalAs(UnmanagedType.LPWStr)] string pszKeyName, int fDeleteFile); void Slot19(); // void Remove(ref Guid pclsidCaller); void Slot20(); // void IsUISupported([MarshalAs(UnmanagedType.LPWStr)] string pszTypeOfUI, IntPtr pvExtraData, UInt32 cbExtraData, object punkObject, ref Int32 pfSupported); void Slot21(); // void DisplayUI(UInt32 hWndParent, [MarshalAs(UnmanagedType.LPWStr)] string pszTitle, [MarshalAs(UnmanagedType.LPWStr)] string pszTypeOfUI, IntPtr pvExtraData, UInt32 cbExtraData, object punkObject); void MatchesAttributes([MarshalAs(UnmanagedType.LPWStr)] string pszAttributes, [MarshalAs(UnmanagedType.Bool)] out bool pfMatches); } //--- ISpObjectWithToken ---------------------------------------------------- [ComImport, Guid("5B559F40-E952-11D2-BB91-00C04F8EE6C0"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISpObjectWithToken { [PreserveSig] int SetObjectToken(ISpObjectToken pToken); [PreserveSig] int GetObjectToken(out ISpObjectToken ppToken); }; [ComImport, Guid("14056581-E16C-11D2-BB90-00C04F8EE6C0"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISpDataKey { // ISpDataKey Methods [PreserveSig] int SetData([MarshalAs(UnmanagedType.LPWStr)] string valueName, uint cbData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data); [PreserveSig] int GetData([MarshalAs(UnmanagedType.LPWStr)] string valueName, ref uint pcbData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] byte[] data); [PreserveSig] int SetStringValue([MarshalAs(UnmanagedType.LPWStr)] string valueName, [MarshalAs(UnmanagedType.LPWStr)] string value); [PreserveSig] int GetStringValue([MarshalAs(UnmanagedType.LPWStr)] string valueName, [MarshalAs(UnmanagedType.LPWStr)] out string value); [PreserveSig] int SetDWORD([MarshalAs(UnmanagedType.LPWStr)] string valueName, uint dwValue); [PreserveSig] int GetDWORD([MarshalAs(UnmanagedType.LPWStr)] string valueName, ref uint pdwValue); [PreserveSig] int OpenKey([MarshalAs(UnmanagedType.LPWStr)] string subKeyName, out ISpDataKey ppSubKey); [PreserveSig] int CreateKey([MarshalAs(UnmanagedType.LPWStr)] string subKey, out ISpDataKey ppSubKey); [PreserveSig] int DeleteKey([MarshalAs(UnmanagedType.LPWStr)] string subKey); [PreserveSig] int DeleteValue([MarshalAs(UnmanagedType.LPWStr)] string valueName); [PreserveSig] int EnumKeys(uint index, [MarshalAs(UnmanagedType.LPWStr)] out string ppszSubKeyName); [PreserveSig] int EnumValues(uint index, [MarshalAs(UnmanagedType.LPWStr)] out string valueName); } [ComImport, Guid("92A66E2B-C830-4149-83DF-6FC2BA1E7A5B"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISpRegDataKey : ISpDataKey { // ISpDataKey Methods [PreserveSig] new int SetData([MarshalAs(UnmanagedType.LPWStr)] string valueName, uint cbData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data); [PreserveSig] new int GetData([MarshalAs(UnmanagedType.LPWStr)] string valueName, ref uint pcbData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] byte[] data); [PreserveSig] new int SetStringValue([MarshalAs(UnmanagedType.LPWStr)] string valueName, [MarshalAs(UnmanagedType.LPWStr)] string value); [PreserveSig] new int GetStringValue([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszValue); [PreserveSig] new int SetDWORD([MarshalAs(UnmanagedType.LPWStr)] string valueName, uint dwValue); [PreserveSig] new int GetDWORD([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, ref uint pdwValue); [PreserveSig] new int OpenKey([MarshalAs(UnmanagedType.LPWStr)] string pszSubKeyName, out ISpDataKey ppSubKey); [PreserveSig] new int CreateKey([MarshalAs(UnmanagedType.LPWStr)] string subKey, out ISpDataKey ppSubKey); [PreserveSig] new int DeleteKey([MarshalAs(UnmanagedType.LPWStr)] string subKey); [PreserveSig] new int DeleteValue([MarshalAs(UnmanagedType.LPWStr)] string valueName); [PreserveSig] new int EnumKeys(uint index, [MarshalAs(UnmanagedType.LPWStr)] out string ppszSubKeyName); [PreserveSig] new int EnumValues(uint Index, [MarshalAs(UnmanagedType.LPWStr)] out string ppszValueName); // ISpRegDataKey Method [PreserveSig] int SetKey(SafeRegistryHandle hkey, bool fReadOnly); } [ComImport, Guid("2D3D3845-39AF-4850-BBF9-40B49780011D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISpObjectTokenCategory : ISpDataKey { // ISpDataKey Methods [PreserveSig] new int SetData([MarshalAs(UnmanagedType.LPWStr)] string valueName, uint cbData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data); [PreserveSig] new int GetData([MarshalAs(UnmanagedType.LPWStr)] string valueName, ref uint pcbData, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] byte[] data); [PreserveSig] new int SetStringValue([MarshalAs(UnmanagedType.LPWStr)] string valueName, [MarshalAs(UnmanagedType.LPWStr)] string value); [PreserveSig] new void GetStringValue([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszValue); [PreserveSig] new int SetDWORD([MarshalAs(UnmanagedType.LPWStr)] string valueName, uint dwValue); [PreserveSig] new int GetDWORD([MarshalAs(UnmanagedType.LPWStr)] string pszValueName, ref uint pdwValue); [PreserveSig] new int OpenKey([MarshalAs(UnmanagedType.LPWStr)] string pszSubKeyName, out ISpDataKey ppSubKey); [PreserveSig] new int CreateKey([MarshalAs(UnmanagedType.LPWStr)] string subKey, out ISpDataKey ppSubKey); [PreserveSig] new int DeleteKey([MarshalAs(UnmanagedType.LPWStr)] string subKey); [PreserveSig] new int DeleteValue([MarshalAs(UnmanagedType.LPWStr)] string valueName); [PreserveSig] new int EnumKeys(uint index, [MarshalAs(UnmanagedType.LPWStr)] out string ppszSubKeyName); [PreserveSig] new int EnumValues(uint Index, [MarshalAs(UnmanagedType.LPWStr)] out string ppszValueName); // ISpObjectTokenCategory Methods void SetId([MarshalAs(UnmanagedType.LPWStr)] string pszCategoryId, [MarshalAs(UnmanagedType.Bool)] bool fCreateIfNotExist); void GetId([MarshalAs(UnmanagedType.LPWStr)] out string ppszCoMemCategoryId); void Slot14(); // void GetDataKey(System.Speech.Internal.SPDATAKEYLOCATION spdkl, out ISpDataKey ppDataKey); void EnumTokens([MarshalAs(UnmanagedType.LPWStr)] string pzsReqAttribs, [MarshalAs(UnmanagedType.LPWStr)] string pszOptAttribs, out IEnumSpObjectTokens ppEnum); void Slot16(); // void SetDefaultTokenId([MarshalAs(UnmanagedType.LPWStr)] string pszTokenId); void GetDefaultTokenId([MarshalAs(UnmanagedType.LPWStr)] out string ppszCoMemTokenId); } [ComImport, Guid("06B64F9E-7FDA-11D2-B4F2-00C04F797396"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IEnumSpObjectTokens { void Slot1(); // void Next(UInt32 celt, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0), Out] ISpObjectToken[] pelt, out UInt32 pceltFetched); void Slot2(); // void Skip(UInt32 celt); void Slot3(); // void Reset(); void Slot4(); // void Clone(out IEnumSpObjectTokens ppEnum); void Item(uint Index, out ISpObjectToken ppToken); void GetCount(out uint pCount); } [ComImport, Guid("B2745EFD-42CE-48CA-81F1-A96E02538A90"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISpPhoneticAlphabetSelection { void IsAlphabetUPS([MarshalAs(UnmanagedType.Bool)] out bool pfIsUPS); void SetAlphabetToUPS([MarshalAs(UnmanagedType.Bool)] bool fForceUPS); } [ComImport, Guid("EF411752-3736-4CB4-9C8C-8EF4CCB58EFE")] internal class SpObjectToken { } [ComImport, Guid("A910187F-0C7A-45AC-92CC-59EDAFB77B53")] internal class SpObjectTokenCategory { } [ComImport, Guid("D9F6EE60-58C9-458B-88E1-2F908FD7F87C")] internal class SpDataKey { } #endregion #region Utility Class internal static class SAPIGuids { internal static readonly Guid SPDFID_WaveFormatEx = new("C31ADBAE-527F-4ff5-A230-F62BB61FF70C"); internal static readonly Guid SPDFID_Text = new("7CEEF9F9-3D13-11d2-9EE7-00C04F797396"); } #endregion }
-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/ParameterAttributes.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ParameterAttributes is an enum defining the attributes that may be // associated with a Parameter. These are defined in CorHdr.h. namespace System.Reflection { // This Enum matchs the CorParamAttr defined in CorHdr.h [Flags] public enum ParameterAttributes { None = 0x0000, // no flag is specified In = 0x0001, // Param is [In] Out = 0x0002, // Param is [Out] Lcid = 0x0004, // Param is [lcid] Retval = 0x0008, // Param is [Retval] Optional = 0x0010, // Param is optional HasDefault = 0x1000, // Param has default value. HasFieldMarshal = 0x2000, // Param has FieldMarshal. Reserved3 = 0x4000, Reserved4 = 0x8000, ReservedMask = 0xf000, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ParameterAttributes is an enum defining the attributes that may be // associated with a Parameter. These are defined in CorHdr.h. namespace System.Reflection { // This Enum matchs the CorParamAttr defined in CorHdr.h [Flags] public enum ParameterAttributes { None = 0x0000, // no flag is specified In = 0x0001, // Param is [In] Out = 0x0002, // Param is [Out] Lcid = 0x0004, // Param is [lcid] Retval = 0x0008, // Param is [Retval] Optional = 0x0010, // Param is optional HasDefault = 0x1000, // Param has default value. HasFieldMarshal = 0x2000, // Param has FieldMarshal. Reserved3 = 0x4000, Reserved4 = 0x8000, ReservedMask = 0xf000, } }
-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/src/System/Xml/Xsl/XsltOld/CopyNodeSetAction.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.Xml.Xsl.XsltOld { using System; using System.Diagnostics; using System.Xml; using System.Xml.XPath; internal sealed class CopyNodeSetAction : Action { private const int BeginEvent = 2; private const int Contents = 3; private const int Namespaces = 4; private const int Attributes = 5; private const int Subtree = 6; private const int EndEvent = 7; private static readonly CopyNodeSetAction s_Action = new CopyNodeSetAction(); internal static CopyNodeSetAction GetAction() { Debug.Assert(s_Action != null); return s_Action; } internal override void Execute(Processor processor, ActionFrame frame) { Debug.Assert(processor != null && frame != null); while (processor.CanContinue) { switch (frame.State) { case Initialized: if (frame.NextNode(processor)) { frame.State = BeginEvent; goto case BeginEvent; } else { frame.Finished(); break; } case BeginEvent: Debug.Assert(frame.State == BeginEvent); if (SendBeginEvent(processor, frame.Node!) == false) { // This one wasn't output break; } frame.State = Contents; continue; case Contents: Debug.Assert(frame.State == Contents); XPathNodeType nodeType = frame.Node!.NodeType; if (nodeType == XPathNodeType.Element || nodeType == XPathNodeType.Root) { processor.PushActionFrame(CopyNamespacesAction.GetAction(), frame.NodeSet); frame.State = Namespaces; break; } if (SendTextEvent(processor, frame.Node) == false) { // This one wasn't output break; } frame.State = EndEvent; continue; case Namespaces: processor.PushActionFrame(CopyAttributesAction.GetAction(), frame.NodeSet); frame.State = Attributes; break; case Attributes: if (frame.Node!.HasChildren) { processor.PushActionFrame(GetAction(), frame.Node.SelectChildren(XPathNodeType.All)); frame.State = Subtree; break; } frame.State = EndEvent; goto case EndEvent; case Subtree: //frame.Node.MoveToParent(); frame.State = EndEvent; continue; case EndEvent: Debug.Assert(frame.State == EndEvent); if (SendEndEvent(processor, frame.Node!) == false) { // This one wasn't output break; } frame.State = Initialized; continue; } break; } } private static bool SendBeginEvent(Processor processor, XPathNavigator node) { return processor.CopyBeginEvent(node, node.IsEmptyElement); } private static bool SendTextEvent(Processor processor, XPathNavigator node) { return processor.CopyTextEvent(node); } private static bool SendEndEvent(Processor processor, XPathNavigator node) { return processor.CopyEndEvent(node); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Xml.Xsl.XsltOld { using System; using System.Diagnostics; using System.Xml; using System.Xml.XPath; internal sealed class CopyNodeSetAction : Action { private const int BeginEvent = 2; private const int Contents = 3; private const int Namespaces = 4; private const int Attributes = 5; private const int Subtree = 6; private const int EndEvent = 7; private static readonly CopyNodeSetAction s_Action = new CopyNodeSetAction(); internal static CopyNodeSetAction GetAction() { Debug.Assert(s_Action != null); return s_Action; } internal override void Execute(Processor processor, ActionFrame frame) { Debug.Assert(processor != null && frame != null); while (processor.CanContinue) { switch (frame.State) { case Initialized: if (frame.NextNode(processor)) { frame.State = BeginEvent; goto case BeginEvent; } else { frame.Finished(); break; } case BeginEvent: Debug.Assert(frame.State == BeginEvent); if (SendBeginEvent(processor, frame.Node!) == false) { // This one wasn't output break; } frame.State = Contents; continue; case Contents: Debug.Assert(frame.State == Contents); XPathNodeType nodeType = frame.Node!.NodeType; if (nodeType == XPathNodeType.Element || nodeType == XPathNodeType.Root) { processor.PushActionFrame(CopyNamespacesAction.GetAction(), frame.NodeSet); frame.State = Namespaces; break; } if (SendTextEvent(processor, frame.Node) == false) { // This one wasn't output break; } frame.State = EndEvent; continue; case Namespaces: processor.PushActionFrame(CopyAttributesAction.GetAction(), frame.NodeSet); frame.State = Attributes; break; case Attributes: if (frame.Node!.HasChildren) { processor.PushActionFrame(GetAction(), frame.Node.SelectChildren(XPathNodeType.All)); frame.State = Subtree; break; } frame.State = EndEvent; goto case EndEvent; case Subtree: //frame.Node.MoveToParent(); frame.State = EndEvent; continue; case EndEvent: Debug.Assert(frame.State == EndEvent); if (SendEndEvent(processor, frame.Node!) == false) { // This one wasn't output break; } frame.State = Initialized; continue; } break; } } private static bool SendBeginEvent(Processor processor, XPathNavigator node) { return processor.CopyBeginEvent(node, node.IsEmptyElement); } private static bool SendTextEvent(Processor processor, XPathNavigator node) { return processor.CopyTextEvent(node); } private static bool SendEndEvent(Processor processor, XPathNavigator node) { return processor.CopyEndEvent(node); } } }
-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/opt/OSR/osrcontainstry.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; // OSR method contains try class OSRContainsTry { [MethodImpl(MethodImplOptions.NoInlining)] public static unsafe int I(ref int p) => p; [MethodImpl(MethodImplOptions.NoInlining)] public static unsafe int F(int from, int to) { int result = 0; for (int i = from; i < to; i++) { try { result = I(ref result) + i; } catch (Exception e) { } } return result; } public static int Main() { Console.WriteLine($"starting sum"); int result = F(0, 1_000_000); Console.WriteLine($"done, sum is {result}"); return result == 1783293664 ? 100 : -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; using System.Runtime.CompilerServices; // OSR method contains try class OSRContainsTry { [MethodImpl(MethodImplOptions.NoInlining)] public static unsafe int I(ref int p) => p; [MethodImpl(MethodImplOptions.NoInlining)] public static unsafe int F(int from, int to) { int result = 0; for (int i = from; i < to; i++) { try { result = I(ref result) + i; } catch (Exception e) { } } return result; } public static int Main() { Console.WriteLine($"starting sum"); int result = F(0, 1_000_000); Console.WriteLine($"done, sum is {result}"); return result == 1783293664 ? 100 : -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/Common/src/Interop/Windows/Kernel32/Interop.MAX_PATH.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. internal static partial class Interop { internal static partial class Kernel32 { internal const int MAX_PATH = 260; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. internal static partial class Interop { internal static partial class Kernel32 { internal const int MAX_PATH = 260; } }
-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/ShiftArithmeticRoundedSaturate.Vector128.Int64.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 ShiftArithmeticRoundedSaturate_Vector128_Int64() { var test = new SimpleBinaryOpTest__ShiftArithmeticRoundedSaturate_Vector128_Int64(); 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__ShiftArithmeticRoundedSaturate_Vector128_Int64 { 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(Int64[] inArray1, Int64[] inArray2, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); 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<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, 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<Int64> _fld1; public Vector128<Int64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__ShiftArithmeticRoundedSaturate_Vector128_Int64 testClass) { var result = AdvSimd.ShiftArithmeticRoundedSaturate(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__ShiftArithmeticRoundedSaturate_Vector128_Int64 testClass) { fixed (Vector128<Int64>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld2) { var result = AdvSimd.ShiftArithmeticRoundedSaturate( AdvSimd.LoadVector128((Int64*)(pFld1)), AdvSimd.LoadVector128((Int64*)(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<Int64>>() / sizeof(Int64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector128<Int64> _clsVar1; private static Vector128<Int64> _clsVar2; private Vector128<Int64> _fld1; private Vector128<Int64> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__ShiftArithmeticRoundedSaturate_Vector128_Int64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public SimpleBinaryOpTest__ShiftArithmeticRoundedSaturate_Vector128_Int64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data2, new Int64[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.ShiftArithmeticRoundedSaturate( Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_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.ShiftArithmeticRoundedSaturate( AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int64*)(_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.ShiftArithmeticRoundedSaturate), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(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.ShiftArithmeticRoundedSaturate), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftArithmeticRoundedSaturate( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int64>* pClsVar1 = &_clsVar1) fixed (Vector128<Int64>* pClsVar2 = &_clsVar2) { var result = AdvSimd.ShiftArithmeticRoundedSaturate( AdvSimd.LoadVector128((Int64*)(pClsVar1)), AdvSimd.LoadVector128((Int64*)(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<Int64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr); var result = AdvSimd.ShiftArithmeticRoundedSaturate(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.LoadVector128((Int64*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)); var result = AdvSimd.ShiftArithmeticRoundedSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__ShiftArithmeticRoundedSaturate_Vector128_Int64(); var result = AdvSimd.ShiftArithmeticRoundedSaturate(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__ShiftArithmeticRoundedSaturate_Vector128_Int64(); fixed (Vector128<Int64>* pFld1 = &test._fld1) fixed (Vector128<Int64>* pFld2 = &test._fld2) { var result = AdvSimd.ShiftArithmeticRoundedSaturate( AdvSimd.LoadVector128((Int64*)(pFld1)), AdvSimd.LoadVector128((Int64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftArithmeticRoundedSaturate(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int64>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld2) { var result = AdvSimd.ShiftArithmeticRoundedSaturate( AdvSimd.LoadVector128((Int64*)(pFld1)), AdvSimd.LoadVector128((Int64*)(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.ShiftArithmeticRoundedSaturate(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.ShiftArithmeticRoundedSaturate( AdvSimd.LoadVector128((Int64*)(&test._fld1)), AdvSimd.LoadVector128((Int64*)(&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<Int64> op1, Vector128<Int64> op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftArithmeticRoundedSaturate(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftArithmeticRoundedSaturate)}<Int64>(Vector128<Int64>, Vector128<Int64>): {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 ShiftArithmeticRoundedSaturate_Vector128_Int64() { var test = new SimpleBinaryOpTest__ShiftArithmeticRoundedSaturate_Vector128_Int64(); 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__ShiftArithmeticRoundedSaturate_Vector128_Int64 { 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(Int64[] inArray1, Int64[] inArray2, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); 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<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, 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<Int64> _fld1; public Vector128<Int64> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__ShiftArithmeticRoundedSaturate_Vector128_Int64 testClass) { var result = AdvSimd.ShiftArithmeticRoundedSaturate(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__ShiftArithmeticRoundedSaturate_Vector128_Int64 testClass) { fixed (Vector128<Int64>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld2) { var result = AdvSimd.ShiftArithmeticRoundedSaturate( AdvSimd.LoadVector128((Int64*)(pFld1)), AdvSimd.LoadVector128((Int64*)(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<Int64>>() / sizeof(Int64); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector128<Int64> _clsVar1; private static Vector128<Int64> _clsVar2; private Vector128<Int64> _fld1; private Vector128<Int64> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__ShiftArithmeticRoundedSaturate_Vector128_Int64() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public SimpleBinaryOpTest__ShiftArithmeticRoundedSaturate_Vector128_Int64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data2, new Int64[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.ShiftArithmeticRoundedSaturate( Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_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.ShiftArithmeticRoundedSaturate( AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int64*)(_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.ShiftArithmeticRoundedSaturate), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(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.ShiftArithmeticRoundedSaturate), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftArithmeticRoundedSaturate( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int64>* pClsVar1 = &_clsVar1) fixed (Vector128<Int64>* pClsVar2 = &_clsVar2) { var result = AdvSimd.ShiftArithmeticRoundedSaturate( AdvSimd.LoadVector128((Int64*)(pClsVar1)), AdvSimd.LoadVector128((Int64*)(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<Int64>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr); var result = AdvSimd.ShiftArithmeticRoundedSaturate(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.LoadVector128((Int64*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)); var result = AdvSimd.ShiftArithmeticRoundedSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__ShiftArithmeticRoundedSaturate_Vector128_Int64(); var result = AdvSimd.ShiftArithmeticRoundedSaturate(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__ShiftArithmeticRoundedSaturate_Vector128_Int64(); fixed (Vector128<Int64>* pFld1 = &test._fld1) fixed (Vector128<Int64>* pFld2 = &test._fld2) { var result = AdvSimd.ShiftArithmeticRoundedSaturate( AdvSimd.LoadVector128((Int64*)(pFld1)), AdvSimd.LoadVector128((Int64*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftArithmeticRoundedSaturate(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int64>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld2) { var result = AdvSimd.ShiftArithmeticRoundedSaturate( AdvSimd.LoadVector128((Int64*)(pFld1)), AdvSimd.LoadVector128((Int64*)(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.ShiftArithmeticRoundedSaturate(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.ShiftArithmeticRoundedSaturate( AdvSimd.LoadVector128((Int64*)(&test._fld1)), AdvSimd.LoadVector128((Int64*)(&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<Int64> op1, Vector128<Int64> op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftArithmeticRoundedSaturate(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftArithmeticRoundedSaturate)}<Int64>(Vector128<Int64>, Vector128<Int64>): {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/Common/src/Interop/Windows/Kernel32/Interop.GenericOperations.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. internal static partial class Interop { internal static partial class Kernel32 { internal static partial class GenericOperations { internal const int GENERIC_READ = unchecked((int)0x80000000); internal const int GENERIC_WRITE = 0x40000000; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. internal static partial class Interop { internal static partial class Kernel32 { internal static partial class GenericOperations { internal const int GENERIC_READ = unchecked((int)0x80000000); internal const int GENERIC_WRITE = 0x40000000; } } }
-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/nativeaot/SmokeTests/DynamicGenerics/MetadataAttribs.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 CoreFXTestLibrary { /// <summary> /// A method to be called before any tests in the assembly are executed. /// </summary> [AttributeUsage(AttributeTargets.Method)] public class AssemblyInitializeAttribute : Attribute { } /// <summary> /// A method to be called after all tests in the assembly are executed. /// </summary> [AttributeUsage(AttributeTargets.Method)] public class AssemblyCleanupAttribute : Attribute { } /// <summary> /// A test class. A test class using this attribute must use instance methods for Tests. /// </summary> [AttributeUsage(AttributeTargets.Class)] public class TestClassAttribute : Attribute { } /// <summary> /// A test method in a test class. /// </summary> [AttributeUsage(AttributeTargets.Method)] public class TestMethodAttribute : Attribute { } /// <summary> /// A method to be called before each test is executed. /// </summary> [AttributeUsage(AttributeTargets.Method)] public class TestInitializeAttribute : Attribute { } /// <summary> /// A method to be called after each test is executed. /// </summary> [AttributeUsage(AttributeTargets.Method)] public class TestCleanupAttribute : Attribute { } /// <summary> /// Indicates that a test should be ignored. /// </summary> [AttributeUsage(AttributeTargets.Method)] public class IgnoreAttribute : Attribute { public readonly string Description; public IgnoreAttribute() { } public IgnoreAttribute(string description) { Description = description; } } /// <summary> /// Indicates that a test is expected to throw an exception. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class ExpectedExceptionAttribute : Attribute { public readonly string Description; public readonly Type ExceptionType; private ExpectedExceptionAttribute() { } public ExpectedExceptionAttribute(Type type) : this(type, null) { } public ExpectedExceptionAttribute(Type type, string description) { ExceptionType = type; Description = description; } } /// <summary> /// Indicates that this TestMethod has specific requirements. This will be propagated to generated runproj files. /// </summary> [AttributeUsage(AttributeTargets.Method)] public class CLRTestRequiresAttribute : Attribute { public readonly string Requirements; public CLRTestRequiresAttribute(String Requirements) { this.Requirements = Requirements; } } /// <summary> /// Contracts required for the test class to build. /// </summary> [AttributeUsage(AttributeTargets.Class)] public class ContractsRequiredAttribute : Attribute { public readonly string[] Contracts; /// <summary> /// Comma separated string containing all of the contracts required. /// </summary> /// <example>contracts = "System.Threading, System.Threading.Tasks, System.Runtime"</example> /// <param name="contract">contracts required.</param> public ContractsRequiredAttribute(string contracts) { string[] parsed = contracts.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); Contracts = parsed; } /// <summary> /// Pass an array of strings representing a contract. /// </summary> /// <remarks> /// Not CLS-Compliant. /// </remarks> /// <param name="contracts">contracts required.</param> public ContractsRequiredAttribute(string[] contracts) { Contracts = contracts; } } }
// 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 CoreFXTestLibrary { /// <summary> /// A method to be called before any tests in the assembly are executed. /// </summary> [AttributeUsage(AttributeTargets.Method)] public class AssemblyInitializeAttribute : Attribute { } /// <summary> /// A method to be called after all tests in the assembly are executed. /// </summary> [AttributeUsage(AttributeTargets.Method)] public class AssemblyCleanupAttribute : Attribute { } /// <summary> /// A test class. A test class using this attribute must use instance methods for Tests. /// </summary> [AttributeUsage(AttributeTargets.Class)] public class TestClassAttribute : Attribute { } /// <summary> /// A test method in a test class. /// </summary> [AttributeUsage(AttributeTargets.Method)] public class TestMethodAttribute : Attribute { } /// <summary> /// A method to be called before each test is executed. /// </summary> [AttributeUsage(AttributeTargets.Method)] public class TestInitializeAttribute : Attribute { } /// <summary> /// A method to be called after each test is executed. /// </summary> [AttributeUsage(AttributeTargets.Method)] public class TestCleanupAttribute : Attribute { } /// <summary> /// Indicates that a test should be ignored. /// </summary> [AttributeUsage(AttributeTargets.Method)] public class IgnoreAttribute : Attribute { public readonly string Description; public IgnoreAttribute() { } public IgnoreAttribute(string description) { Description = description; } } /// <summary> /// Indicates that a test is expected to throw an exception. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class ExpectedExceptionAttribute : Attribute { public readonly string Description; public readonly Type ExceptionType; private ExpectedExceptionAttribute() { } public ExpectedExceptionAttribute(Type type) : this(type, null) { } public ExpectedExceptionAttribute(Type type, string description) { ExceptionType = type; Description = description; } } /// <summary> /// Indicates that this TestMethod has specific requirements. This will be propagated to generated runproj files. /// </summary> [AttributeUsage(AttributeTargets.Method)] public class CLRTestRequiresAttribute : Attribute { public readonly string Requirements; public CLRTestRequiresAttribute(String Requirements) { this.Requirements = Requirements; } } /// <summary> /// Contracts required for the test class to build. /// </summary> [AttributeUsage(AttributeTargets.Class)] public class ContractsRequiredAttribute : Attribute { public readonly string[] Contracts; /// <summary> /// Comma separated string containing all of the contracts required. /// </summary> /// <example>contracts = "System.Threading, System.Threading.Tasks, System.Runtime"</example> /// <param name="contract">contracts required.</param> public ContractsRequiredAttribute(string contracts) { string[] parsed = contracts.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); Contracts = parsed; } /// <summary> /// Pass an array of strings representing a contract. /// </summary> /// <remarks> /// Not CLS-Compliant. /// </remarks> /// <param name="contracts">contracts required.</param> public ContractsRequiredAttribute(string[] contracts) { Contracts = contracts; } } }
-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/gen/EventSourceGenerator.Parser.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.Linq; using System.Security.Cryptography; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DotnetRuntime.Extensions; namespace Generators { public partial class EventSourceGenerator { private sealed class Parser { private readonly CancellationToken _cancellationToken; private readonly Compilation _compilation; private readonly Action<Diagnostic> _reportDiagnostic; public Parser(Compilation compilation, Action<Diagnostic> reportDiagnostic, CancellationToken cancellationToken) { _compilation = compilation; _cancellationToken = cancellationToken; _reportDiagnostic = reportDiagnostic; } public EventSourceClass[] GetEventSourceClasses(List<ClassDeclarationSyntax> classDeclarations) { INamedTypeSymbol? autogenerateAttribute = _compilation.GetBestTypeByMetadataName("System.Diagnostics.Tracing.EventSourceAutoGenerateAttribute"); if (autogenerateAttribute is null) { // No EventSourceAutoGenerateAttribute return Array.Empty<EventSourceClass>(); } INamedTypeSymbol? eventSourceAttribute = _compilation.GetBestTypeByMetadataName("System.Diagnostics.Tracing.EventSourceAttribute"); if (eventSourceAttribute is null) { // No EventSourceAttribute return Array.Empty<EventSourceClass>(); } List<EventSourceClass>? results = null; // we enumerate by syntax tree, to minimize the need to instantiate semantic models (since they're expensive) foreach (IGrouping<SyntaxTree, ClassDeclarationSyntax>? group in classDeclarations.GroupBy(x => x.SyntaxTree)) { SemanticModel? sm = null; EventSourceClass? eventSourceClass = null; foreach (ClassDeclarationSyntax? classDef in group) { if (_cancellationToken.IsCancellationRequested) { // be nice and stop if we're asked to return results?.ToArray() ?? Array.Empty<EventSourceClass>(); } bool autoGenerate = false; foreach (AttributeListSyntax? cal in classDef.AttributeLists) { foreach (AttributeSyntax? ca in cal.Attributes) { // need a semantic model for this tree sm ??= _compilation.GetSemanticModel(classDef.SyntaxTree); if (sm.GetSymbolInfo(ca, _cancellationToken).Symbol is not IMethodSymbol caSymbol) { // badly formed attribute definition, or not the right attribute continue; } if (autogenerateAttribute.Equals(caSymbol.ContainingType, SymbolEqualityComparer.Default)) { autoGenerate = true; continue; } if (eventSourceAttribute.Equals(caSymbol.ContainingType, SymbolEqualityComparer.Default)) { string nspace = string.Empty; NamespaceDeclarationSyntax? ns = classDef.Parent as NamespaceDeclarationSyntax; if (ns is null) { if (classDef.Parent is not CompilationUnitSyntax) { // since this generator doesn't know how to generate a nested type... continue; } } else { nspace = ns.Name.ToString(); while (true) { ns = ns.Parent as NamespaceDeclarationSyntax; if (ns == null) { break; } nspace = $"{ns.Name}.{nspace}"; } } string className = classDef.Identifier.ToString(); string name = className; string guid = ""; SeparatedSyntaxList<AttributeArgumentSyntax>? args = ca.ArgumentList?.Arguments; if (args is not null) { foreach (AttributeArgumentSyntax? arg in args) { string? argName = arg.NameEquals!.Name.Identifier.ToString(); string? value = sm.GetConstantValue(arg.Expression, _cancellationToken).ToString(); switch (argName) { case "Guid": guid = value; break; case "Name": name = value; break; } } } if (!Guid.TryParse(guid, out Guid result)) { result = GenerateGuidFromName(name.ToUpperInvariant()); } eventSourceClass = new EventSourceClass { Namespace = nspace, ClassName = className, SourceName = name, Guid = result }; continue; } } } if (!autoGenerate) { continue; } if (eventSourceClass is null) { continue; } results ??= new List<EventSourceClass>(); results.Add(eventSourceClass); } } return results?.ToArray() ?? Array.Empty<EventSourceClass>(); } // From System.Private.CoreLib private static Guid GenerateGuidFromName(string name) { ReadOnlySpan<byte> namespaceBytes = new byte[] // rely on C# compiler optimization to remove byte[] allocation { 0x48, 0x2C, 0x2D, 0xB2, 0xC3, 0x90, 0x47, 0xC8, 0x87, 0xF8, 0x1A, 0x15, 0xBF, 0xC1, 0x30, 0xFB, }; byte[] bytes = Encoding.BigEndianUnicode.GetBytes(name); byte[] combinedBytes = new byte[namespaceBytes.Length + bytes.Length]; bytes.CopyTo(combinedBytes, namespaceBytes.Length); namespaceBytes.CopyTo(combinedBytes); using (SHA1 sha = SHA1.Create()) { bytes = sha.ComputeHash(combinedBytes); } Array.Resize(ref bytes, 16); bytes[7] = unchecked((byte)((bytes[7] & 0x0F) | 0x50)); // Set high 4 bits of octet 7 to 5, as per RFC 4122 return new Guid(bytes); } } } }
// 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.Linq; using System.Security.Cryptography; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DotnetRuntime.Extensions; namespace Generators { public partial class EventSourceGenerator { private sealed class Parser { private readonly CancellationToken _cancellationToken; private readonly Compilation _compilation; private readonly Action<Diagnostic> _reportDiagnostic; public Parser(Compilation compilation, Action<Diagnostic> reportDiagnostic, CancellationToken cancellationToken) { _compilation = compilation; _cancellationToken = cancellationToken; _reportDiagnostic = reportDiagnostic; } public EventSourceClass[] GetEventSourceClasses(List<ClassDeclarationSyntax> classDeclarations) { INamedTypeSymbol? autogenerateAttribute = _compilation.GetBestTypeByMetadataName("System.Diagnostics.Tracing.EventSourceAutoGenerateAttribute"); if (autogenerateAttribute is null) { // No EventSourceAutoGenerateAttribute return Array.Empty<EventSourceClass>(); } INamedTypeSymbol? eventSourceAttribute = _compilation.GetBestTypeByMetadataName("System.Diagnostics.Tracing.EventSourceAttribute"); if (eventSourceAttribute is null) { // No EventSourceAttribute return Array.Empty<EventSourceClass>(); } List<EventSourceClass>? results = null; // we enumerate by syntax tree, to minimize the need to instantiate semantic models (since they're expensive) foreach (IGrouping<SyntaxTree, ClassDeclarationSyntax>? group in classDeclarations.GroupBy(x => x.SyntaxTree)) { SemanticModel? sm = null; EventSourceClass? eventSourceClass = null; foreach (ClassDeclarationSyntax? classDef in group) { if (_cancellationToken.IsCancellationRequested) { // be nice and stop if we're asked to return results?.ToArray() ?? Array.Empty<EventSourceClass>(); } bool autoGenerate = false; foreach (AttributeListSyntax? cal in classDef.AttributeLists) { foreach (AttributeSyntax? ca in cal.Attributes) { // need a semantic model for this tree sm ??= _compilation.GetSemanticModel(classDef.SyntaxTree); if (sm.GetSymbolInfo(ca, _cancellationToken).Symbol is not IMethodSymbol caSymbol) { // badly formed attribute definition, or not the right attribute continue; } if (autogenerateAttribute.Equals(caSymbol.ContainingType, SymbolEqualityComparer.Default)) { autoGenerate = true; continue; } if (eventSourceAttribute.Equals(caSymbol.ContainingType, SymbolEqualityComparer.Default)) { string nspace = string.Empty; NamespaceDeclarationSyntax? ns = classDef.Parent as NamespaceDeclarationSyntax; if (ns is null) { if (classDef.Parent is not CompilationUnitSyntax) { // since this generator doesn't know how to generate a nested type... continue; } } else { nspace = ns.Name.ToString(); while (true) { ns = ns.Parent as NamespaceDeclarationSyntax; if (ns == null) { break; } nspace = $"{ns.Name}.{nspace}"; } } string className = classDef.Identifier.ToString(); string name = className; string guid = ""; SeparatedSyntaxList<AttributeArgumentSyntax>? args = ca.ArgumentList?.Arguments; if (args is not null) { foreach (AttributeArgumentSyntax? arg in args) { string? argName = arg.NameEquals!.Name.Identifier.ToString(); string? value = sm.GetConstantValue(arg.Expression, _cancellationToken).ToString(); switch (argName) { case "Guid": guid = value; break; case "Name": name = value; break; } } } if (!Guid.TryParse(guid, out Guid result)) { result = GenerateGuidFromName(name.ToUpperInvariant()); } eventSourceClass = new EventSourceClass { Namespace = nspace, ClassName = className, SourceName = name, Guid = result }; continue; } } } if (!autoGenerate) { continue; } if (eventSourceClass is null) { continue; } results ??= new List<EventSourceClass>(); results.Add(eventSourceClass); } } return results?.ToArray() ?? Array.Empty<EventSourceClass>(); } // From System.Private.CoreLib private static Guid GenerateGuidFromName(string name) { ReadOnlySpan<byte> namespaceBytes = new byte[] // rely on C# compiler optimization to remove byte[] allocation { 0x48, 0x2C, 0x2D, 0xB2, 0xC3, 0x90, 0x47, 0xC8, 0x87, 0xF8, 0x1A, 0x15, 0xBF, 0xC1, 0x30, 0xFB, }; byte[] bytes = Encoding.BigEndianUnicode.GetBytes(name); byte[] combinedBytes = new byte[namespaceBytes.Length + bytes.Length]; bytes.CopyTo(combinedBytes, namespaceBytes.Length); namespaceBytes.CopyTo(combinedBytes); using (SHA1 sha = SHA1.Create()) { bytes = sha.ComputeHash(combinedBytes); } Array.Resize(ref bytes, 16); bytes[7] = unchecked((byte)((bytes[7] & 0x0F) | 0x50)); // Set high 4 bits of octet 7 to 5, as per RFC 4122 return new Guid(bytes); } } } }
-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/binding/tracing/BinderTracingTest.ResolutionFlow.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.IO; using System.Reflection; using System.Runtime.Loader; using Xunit; using ResolutionStage = BinderTracingTests.ResolutionAttempt.ResolutionStage; using ResolutionResult = BinderTracingTests.ResolutionAttempt.ResolutionResult; namespace BinderTracingTests { partial class BinderTracingTest { private static CustomALC alcInstance = new CustomALC("StaticInstance"); private static Assembly loadedAssembly; // Matching assembly in load context: // ResolutionAttempted : FindInLoadContext (CustomALC) [Success] [BinderTest(isolate: true, testSetup: nameof(LoadSubdirectoryAssembly_InstanceALC))] public static BindOperation FindInLoadContext_CustomALC() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); Assembly asm = alcInstance.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alcInstance.ToString(), Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alcInstance, ResolutionResult.Success, asm) } }; } // Matching assembly in load context: // ResolutionAttempted : FindInLoadContext (DefaultALC) [Success] [BinderTest(isolate: true, testSetup: nameof(UseDependentAssembly))] public static BindOperation FindInLoadContext_DefaultALC() { var assemblyName = new AssemblyName(DependentAssemblyName); Assembly asm = AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = DefaultALC, Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.Success, asm) } }; } // Incompatible version in load context: // ResolutionAttempted : FindInLoadContext (CustomALC) [IncompatibleVersion] // ResolutionAttempted : AssemblyLoadContextLoad (CustomALC) [AssemblyNotFound] // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : DefaultAssemblyLoadContextFallback (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AppDomainAssemblyResolveEvent (CustomALC) [AssemblyNotFound] [BinderTest(isolate: true, testSetup: nameof(LoadSubdirectoryAssembly_InstanceALC))] public static BindOperation FindInLoadContext_CustomALC_IncompatibleVersion() { var assemblyName = new AssemblyName($"{SubdirectoryAssemblyName}, Version=4.3.2.1"); Assert.Throws<FileNotFoundException>(() => alcInstance.LoadFromAssemblyName(assemblyName)); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alcInstance.ToString(), Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alcInstance, ResolutionResult.IncompatibleVersion, loadedAssembly), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextLoad, alcInstance, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.DefaultAssemblyLoadContextFallback, alcInstance, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, alcInstance, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AppDomainAssemblyResolveEvent, alcInstance, ResolutionResult.AssemblyNotFound) } }; } // Incompatible version in load context: // ResolutionAttempted : FindInLoadContext (DefaultALC) [IncompatibleVersion] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : AppDomainAssemblyResolveEvent (DefaultALC) [AssemblyNotFound] [BinderTest(isolate: true, testSetup: nameof(UseDependentAssembly))] public static BindOperation FindInLoadContext_DefaultALC_IncompatibleVersion() { var assemblyName = new AssemblyName($"{DependentAssemblyName}, Version=4.3.2.1"); Assert.Throws<FileNotFoundException>(() => AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName)); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = DefaultALC, Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.IncompatibleVersion, UseDependentAssembly()), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AppDomainAssemblyResolveEvent, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound) } }; } // Successful load through application assemblies search: // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [Success] [BinderTest(isolate: true)] public static BindOperation ApplicationAssemblies() { var assemblyName = new AssemblyName(DependentAssemblyName); Assembly asm = AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = DefaultALC, Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.Success, asm) } }; } // Incompatible version in load context: // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [IncompatibleVersion] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : AppDomainAssemblyResolveEvent (DefaultALC) [AssemblyNotFound] [BinderTest(isolate: true)] public static BindOperation ApplicationAssemblies_IncompatibleVersion() { var assemblyName = new AssemblyName($"{DependentAssemblyName}, Version=4.3.2.1"); Assert.Throws<FileNotFoundException>(() => AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName)); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = DefaultALC, Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.IncompatibleVersion, new AssemblyName($"{DependentAssemblyName}, Version=1.0.0.0"), Helpers.GetAssemblyInAppPath(DependentAssemblyName)), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AppDomainAssemblyResolveEvent, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound) } }; } // Mismatched assembly name from platform assemblies: // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [MismatchedAssemblyName] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : AppDomainAssemblyResolveEvent (DefaultALC) [AssemblyNotFound] [BinderTest(isolate: true, additionalLoadsToTrack: new string[] { DependentAssemblyName + "_Copy" } )] public static BindOperation ApplicationAssemblies_MismatchedAssemblyName() { var assemblyName = new AssemblyName($"{DependentAssemblyName}_Copy, Culture=neutral, PublicKeyToken=null"); string assemblyPath = Helpers.GetAssemblyInAppPath(assemblyName.Name); try { File.Copy(Helpers.GetAssemblyInAppPath(DependentAssemblyName), assemblyPath, true); Assert.Throws<FileNotFoundException>(() => AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName)); } finally { File.Delete(assemblyPath); } return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = DefaultALC, Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.MismatchedAssemblyName, UseDependentAssembly().GetName(), assemblyPath), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AppDomainAssemblyResolveEvent, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound) } }; } // Successful load through AssemblyLoadContext.Load: // ResolutionAttempted : FindInLoadContext (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextLoad (CustomALC) [Success] [BinderTest] public static BindOperation AssemblyLoadContextLoad() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); var assemblyPath = Helpers.GetAssemblyInSubdirectoryPath(assemblyName.Name); CustomALC alc = new CustomALC(nameof(AssemblyLoadContextLoad)); alc.EnableLoad(assemblyName.Name, assemblyPath); Assembly asm = alc.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alc.ToString(), Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextLoad, alc, ResolutionResult.Success, asm) } }; } // Exception thrown in AssemblyLoadContext.Load: // ResolutionAttempted : FindInLoadContext (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextLoad (CustomALC) [Exception] [BinderTest] public static BindOperation AssemblyLoadContextLoad_Exception() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); var assemblyPath = Helpers.GetAssemblyInSubdirectoryPath(assemblyName.Name); CustomALC alc = new CustomALC(nameof(AssemblyLoadContextLoad), true /*throwOnLoad*/); AssertExtensions.ThrowsWithInnerException<FileLoadException, Exception>(() => alc.LoadFromAssemblyName(assemblyName)); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alc.ToString(), Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextLoad, alc, $"Exception on Load in '{alc.ToString()}'") } }; } // Successful load through default ALC fallback: // ResolutionAttempted : FindInLoadContext (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextLoad (CustomALC) [AssemblyNotFound] // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [Success] // ResolutionAttempted : DefaultAssemblyLoadContextFallback (CustomALC) [Success] [BinderTest(isolate: true, additionalLoadsToTrack: new string[] { "System.Xml" })] public static BindOperation DefaultAssemblyLoadContextFallback() { var assemblyName = new AssemblyName("System.Xml"); CustomALC alc = new CustomALC(nameof(DefaultAssemblyLoadContextFallback)); Assembly asm = alc.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alc.ToString(), Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextLoad, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.Success, asm), GetResolutionAttempt(assemblyName, ResolutionStage.DefaultAssemblyLoadContextFallback, alc, ResolutionResult.Success, asm) } }; } // Successful load through satellite assembly resolution logic: // ResolutionAttempted : FindInLoadContext (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextLoad (CustomALC) [AssemblyNotFound] // ResolutionAttempted : ResolveSatelliteAssembly (CustomALC) [Success] [BinderTest] public static BindOperation ResolveSatelliteAssembly() { AssemblyName assemblyName = new AssemblyName($"{DependentAssemblyName}.resources"); assemblyName.CultureInfo = SatelliteCulture; CustomALC alc = new CustomALC(nameof(ResolveSatelliteAssembly)); alc.LoadFromAssemblyPath(Helpers.GetAssemblyInAppPath(DependentAssemblyName)); Assembly asm = alc.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alc.ToString(), Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextLoad, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ResolveSatelliteAssembly, alc, ResolutionResult.Success, asm) } }; } // Successful load through AssemblyLoadContext.Resolving event (Custom ALC): // ResolutionAttempted : FindInLoadContext (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextLoad (CustomALC) [AssemblyNotFound] // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : DefaultAssemblyLoadContextFallback (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (CustomALC) [Success] [BinderTest(isolate: true)] public static BindOperation AssemblyLoadContextResolvingEvent_CustomALC() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); CustomALC alc = new CustomALC(nameof(AssemblyLoadContextResolvingEvent_CustomALC)); using (var handlers = new Handlers(HandlerReturn.RequestedAssembly, alc)) { Assembly asm = alc.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alc.ToString(), Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextLoad, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.DefaultAssemblyLoadContextFallback, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, alc, ResolutionResult.Success, asm) }, AssemblyLoadContextResolvingHandlers = handlers.Invocations }; } } // Successful load through AssemblyLoadContext.Resolving event (default ALC): // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (DefaultALC) [Success] [BinderTest(isolate: true)] public static BindOperation AssemblyLoadContextResolvingEvent_DefaultALC() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); using (var handlers = new Handlers(HandlerReturn.RequestedAssembly, AssemblyLoadContext.Default)) { Assembly asm = AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = DefaultALC, Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, AssemblyLoadContext.Default, ResolutionResult.Success, asm) }, AssemblyLoadContextResolvingHandlers = handlers.Invocations }; } } // Exception in AssemblyLoadContext.Resolving event handler (Custom ALC): // ResolutionAttempted : FindInLoadContext (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextLoad (CustomALC) [AssemblyNotFound] // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : DefaultAssemblyLoadContextFallback (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (CustomALC) [Exception] [BinderTest(isolate: true)] public static BindOperation AssemblyLoadContextResolvingEvent_CustomALC_Exception() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); CustomALC alc = new CustomALC(nameof(AssemblyLoadContextResolvingEvent_CustomALC_Exception)); using (var handlers = new Handlers(HandlerReturn.Exception, alc)) { AssertExtensions.ThrowsWithInnerException<FileLoadException, BinderTestException>(() => alc.LoadFromAssemblyName(assemblyName)); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alc.ToString(), Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextLoad, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.DefaultAssemblyLoadContextFallback, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, alc, "Exception in handler for AssemblyLoadContext.Resolving") }, AssemblyLoadContextResolvingHandlers = handlers.Invocations }; } } // Exception in AssemblyLoadContext.Resolving event handler (default ALC): // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (DefaultALC) [Exception] [BinderTest(isolate: true)] public static BindOperation AssemblyLoadContextResolvingEvent_DefaultALC_Exception() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); using (var handlers = new Handlers(HandlerReturn.Exception, AssemblyLoadContext.Default)) { AssertExtensions.ThrowsWithInnerException<FileLoadException, BinderTestException>(() => AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName)); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = DefaultALC, Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, AssemblyLoadContext.Default, "Exception in handler for AssemblyLoadContext.Resolving") }, AssemblyLoadContextResolvingHandlers = handlers.Invocations }; } } // Successful load through AppDomain.AssemblyResolve event (Custom ALC): // ResolutionAttempted : FindInLoadContext (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextLoad (CustomALC) [AssemblyNotFound] // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : DefaultAssemblyLoadContextFallback (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AppDomainAssemblyResolveEvent (CustomALC) [Success] [BinderTest(isolate: true)] public static BindOperation AppDomainAssemblyResolveEvent_CustomALC() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); CustomALC alc = new CustomALC(nameof(AppDomainAssemblyResolveEvent_CustomALC)); using (var handlers = new Handlers(HandlerReturn.RequestedAssembly)) { Assembly asm = alc.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alc.ToString(), Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextLoad, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.DefaultAssemblyLoadContextFallback, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AppDomainAssemblyResolveEvent, alc, ResolutionResult.Success, asm) }, AppDomainAssemblyResolveHandlers = handlers.Invocations }; } } // Successful load through AppDomain.AssemblyResolve event (default ALC): // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : AppDomainAssemblyResolveEvent (DefaultALC) [Success] [BinderTest(isolate: true)] public static BindOperation AppDomainAssemblyResolveEvent_DefaultALC() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); using (var handlers = new Handlers(HandlerReturn.RequestedAssembly)) { Assembly asm = AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = DefaultALC, Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AppDomainAssemblyResolveEvent, AssemblyLoadContext.Default, ResolutionResult.Success, asm) }, AppDomainAssemblyResolveHandlers = handlers.Invocations }; } } // Exception in AppDomain.AssemblyResolve event handler: // ResolutionAttempted : FindInLoadContext (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextLoad (CustomALC) [AssemblyNotFound] // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : DefaultAssemblyLoadContextFallback (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AppDomainAssemblyResolveEvent (CustomALC) [Exception] [BinderTest(isolate: true)] public static BindOperation AppDomainAssemblyResolveEvent_Exception() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); CustomALC alc = new CustomALC(nameof(AppDomainAssemblyResolveEvent_Exception)); using (var handlers = new Handlers(HandlerReturn.Exception)) { AssertExtensions.ThrowsWithInnerException<FileLoadException, BinderTestException>(() => alc.LoadFromAssemblyName(assemblyName)); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alc.ToString(), Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextLoad, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.DefaultAssemblyLoadContextFallback, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AppDomainAssemblyResolveEvent, alc, "Exception in handler for AppDomain.AssemblyResolve") }, AppDomainAssemblyResolveHandlers = handlers.Invocations }; } } // Assembly is found in app path when attempted to load through full path: // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [Success] [BinderTest(isolate: true)] public static BindOperation LoadFromAssemblyPath_FoundInAppPath() { var assemblyName = new AssemblyName(DependentAssemblyName); var assemblyPath = Helpers.GetAssemblyInSubdirectoryPath(assemblyName.Name); Assembly asm = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath); Assert.NotEqual(assemblyPath, asm.Location); return new BindOperation() { AssemblyName = asm.GetName(), AssemblyPath = assemblyPath, AssemblyLoadContext = DefaultALC, RequestingAssembly = CoreLibName, RequestingAssemblyLoadContext = DefaultALC, Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(asm.GetName(), ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(asm.GetName(), ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.Success, asm), } }; } // Assembly with different MVID is found in load context when attempted to load through full path: // ResolutionAttempted : FindInLoadContext (DefaultALC) [Failure] [BinderTest(isolate: true, testSetup: nameof(UseDependentAssembly))] public static BindOperation LoadFromAssemblyPath_FoundInLoadContext_DifferentMvid() { var assemblyPath = Helpers.GetAssemblyInSubdirectoryPath($"{DependentAssemblyName}_V2"); string errorMessage = null; try { AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath); } catch (FileLoadException e) { errorMessage = e.Message; } var assemblyName = new AssemblyName($"{DependentAssemblyName}, Version=2.0.0.0"); return new BindOperation() { AssemblyName = assemblyName, AssemblyPath = assemblyPath, AssemblyLoadContext = DefaultALC, RequestingAssembly = CoreLibName, RequestingAssemblyLoadContext = DefaultALC, Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { // GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.IncompatibleVersion, UseDependentAssembly()), GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.Failure, new AssemblyName($"{DependentAssemblyName}, Version=1.0.0.0"), Helpers.GetAssemblyInAppPath(DependentAssemblyName), errorMessage), } }; } // Incompatible version is found in app path when attempted to load through full path: // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [IncompatibleVersion] [BinderTest(isolate: true)] public static BindOperation LoadFromAssemblyPath_FoundInAppPath_IncompatibleVersion() { var assemblyPath = Helpers.GetAssemblyInSubdirectoryPath($"{DependentAssemblyName}_V2"); Assert.Throws<FileLoadException>(() => AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath)); var assemblyName = new AssemblyName($"{DependentAssemblyName}, Version=2.0.0.0"); return new BindOperation() { AssemblyName = assemblyName, AssemblyPath = assemblyPath, AssemblyLoadContext = DefaultALC, RequestingAssembly = CoreLibName, RequestingAssemblyLoadContext = DefaultALC, Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.IncompatibleVersion, new AssemblyName($"{DependentAssemblyName}, Version=1.0.0.0"), Helpers.GetAssemblyInAppPath(DependentAssemblyName)), } }; } private static ResolutionAttempt GetResolutionAttempt(AssemblyName assemblyName, ResolutionStage stage, AssemblyLoadContext alc, string exceptionMessage) { return GetResolutionAttempt(assemblyName, stage, alc, ResolutionResult.Exception, null, null, exceptionMessage); } private static ResolutionAttempt GetResolutionAttempt(AssemblyName assemblyName, ResolutionStage stage, AssemblyLoadContext alc, ResolutionResult result, Assembly resultAssembly = null) { AssemblyName resultAssemblyName = null; string resultAssemblyPath = string.Empty; if (resultAssembly != null) { resultAssemblyName = resultAssembly.GetName(); resultAssemblyPath = resultAssembly.Location; } return GetResolutionAttempt(assemblyName, stage, alc, result, resultAssemblyName, resultAssemblyPath); } private static ResolutionAttempt GetResolutionAttempt(AssemblyName assemblyName, ResolutionStage stage, AssemblyLoadContext alc, ResolutionResult result, AssemblyName resultAssemblyName, string resultAssemblyPath, string errorMessage = null) { var attempt = new ResolutionAttempt() { AssemblyName = assemblyName, Stage = stage, AssemblyLoadContext = alc == AssemblyLoadContext.Default ? DefaultALC : alc.ToString(), Result = result, ResultAssemblyName = resultAssemblyName, ResultAssemblyPath = resultAssemblyPath }; if (!string.IsNullOrEmpty(errorMessage)) { attempt.ErrorMessage = errorMessage; } else { switch (result) { case ResolutionAttempt.ResolutionResult.AssemblyNotFound: attempt.ErrorMessage = "Could not locate assembly"; break; case ResolutionAttempt.ResolutionResult.IncompatibleVersion: attempt.ErrorMessage = $"Requested version {assemblyName.Version} is incompatible with found version {resultAssemblyName.Version}"; break; case ResolutionAttempt.ResolutionResult.MismatchedAssemblyName: attempt.ErrorMessage = $"Requested assembly name '{assemblyName.FullName}' does not match found assembly name '{resultAssemblyName.FullName}'"; break; } } return attempt; } private static void LoadSubdirectoryAssembly_InstanceALC() { string assemblyPath = Helpers.GetAssemblyInSubdirectoryPath(SubdirectoryAssemblyName); loadedAssembly = alcInstance.LoadFromAssemblyPath(assemblyPath); } } }
// 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.IO; using System.Reflection; using System.Runtime.Loader; using Xunit; using ResolutionStage = BinderTracingTests.ResolutionAttempt.ResolutionStage; using ResolutionResult = BinderTracingTests.ResolutionAttempt.ResolutionResult; namespace BinderTracingTests { partial class BinderTracingTest { private static CustomALC alcInstance = new CustomALC("StaticInstance"); private static Assembly loadedAssembly; // Matching assembly in load context: // ResolutionAttempted : FindInLoadContext (CustomALC) [Success] [BinderTest(isolate: true, testSetup: nameof(LoadSubdirectoryAssembly_InstanceALC))] public static BindOperation FindInLoadContext_CustomALC() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); Assembly asm = alcInstance.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alcInstance.ToString(), Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alcInstance, ResolutionResult.Success, asm) } }; } // Matching assembly in load context: // ResolutionAttempted : FindInLoadContext (DefaultALC) [Success] [BinderTest(isolate: true, testSetup: nameof(UseDependentAssembly))] public static BindOperation FindInLoadContext_DefaultALC() { var assemblyName = new AssemblyName(DependentAssemblyName); Assembly asm = AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = DefaultALC, Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.Success, asm) } }; } // Incompatible version in load context: // ResolutionAttempted : FindInLoadContext (CustomALC) [IncompatibleVersion] // ResolutionAttempted : AssemblyLoadContextLoad (CustomALC) [AssemblyNotFound] // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : DefaultAssemblyLoadContextFallback (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AppDomainAssemblyResolveEvent (CustomALC) [AssemblyNotFound] [BinderTest(isolate: true, testSetup: nameof(LoadSubdirectoryAssembly_InstanceALC))] public static BindOperation FindInLoadContext_CustomALC_IncompatibleVersion() { var assemblyName = new AssemblyName($"{SubdirectoryAssemblyName}, Version=4.3.2.1"); Assert.Throws<FileNotFoundException>(() => alcInstance.LoadFromAssemblyName(assemblyName)); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alcInstance.ToString(), Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alcInstance, ResolutionResult.IncompatibleVersion, loadedAssembly), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextLoad, alcInstance, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.DefaultAssemblyLoadContextFallback, alcInstance, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, alcInstance, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AppDomainAssemblyResolveEvent, alcInstance, ResolutionResult.AssemblyNotFound) } }; } // Incompatible version in load context: // ResolutionAttempted : FindInLoadContext (DefaultALC) [IncompatibleVersion] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : AppDomainAssemblyResolveEvent (DefaultALC) [AssemblyNotFound] [BinderTest(isolate: true, testSetup: nameof(UseDependentAssembly))] public static BindOperation FindInLoadContext_DefaultALC_IncompatibleVersion() { var assemblyName = new AssemblyName($"{DependentAssemblyName}, Version=4.3.2.1"); Assert.Throws<FileNotFoundException>(() => AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName)); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = DefaultALC, Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.IncompatibleVersion, UseDependentAssembly()), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AppDomainAssemblyResolveEvent, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound) } }; } // Successful load through application assemblies search: // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [Success] [BinderTest(isolate: true)] public static BindOperation ApplicationAssemblies() { var assemblyName = new AssemblyName(DependentAssemblyName); Assembly asm = AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = DefaultALC, Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.Success, asm) } }; } // Incompatible version in load context: // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [IncompatibleVersion] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : AppDomainAssemblyResolveEvent (DefaultALC) [AssemblyNotFound] [BinderTest(isolate: true)] public static BindOperation ApplicationAssemblies_IncompatibleVersion() { var assemblyName = new AssemblyName($"{DependentAssemblyName}, Version=4.3.2.1"); Assert.Throws<FileNotFoundException>(() => AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName)); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = DefaultALC, Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.IncompatibleVersion, new AssemblyName($"{DependentAssemblyName}, Version=1.0.0.0"), Helpers.GetAssemblyInAppPath(DependentAssemblyName)), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AppDomainAssemblyResolveEvent, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound) } }; } // Mismatched assembly name from platform assemblies: // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [MismatchedAssemblyName] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : AppDomainAssemblyResolveEvent (DefaultALC) [AssemblyNotFound] [BinderTest(isolate: true, additionalLoadsToTrack: new string[] { DependentAssemblyName + "_Copy" } )] public static BindOperation ApplicationAssemblies_MismatchedAssemblyName() { var assemblyName = new AssemblyName($"{DependentAssemblyName}_Copy, Culture=neutral, PublicKeyToken=null"); string assemblyPath = Helpers.GetAssemblyInAppPath(assemblyName.Name); try { File.Copy(Helpers.GetAssemblyInAppPath(DependentAssemblyName), assemblyPath, true); Assert.Throws<FileNotFoundException>(() => AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName)); } finally { File.Delete(assemblyPath); } return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = DefaultALC, Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.MismatchedAssemblyName, UseDependentAssembly().GetName(), assemblyPath), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AppDomainAssemblyResolveEvent, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound) } }; } // Successful load through AssemblyLoadContext.Load: // ResolutionAttempted : FindInLoadContext (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextLoad (CustomALC) [Success] [BinderTest] public static BindOperation AssemblyLoadContextLoad() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); var assemblyPath = Helpers.GetAssemblyInSubdirectoryPath(assemblyName.Name); CustomALC alc = new CustomALC(nameof(AssemblyLoadContextLoad)); alc.EnableLoad(assemblyName.Name, assemblyPath); Assembly asm = alc.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alc.ToString(), Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextLoad, alc, ResolutionResult.Success, asm) } }; } // Exception thrown in AssemblyLoadContext.Load: // ResolutionAttempted : FindInLoadContext (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextLoad (CustomALC) [Exception] [BinderTest] public static BindOperation AssemblyLoadContextLoad_Exception() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); var assemblyPath = Helpers.GetAssemblyInSubdirectoryPath(assemblyName.Name); CustomALC alc = new CustomALC(nameof(AssemblyLoadContextLoad), true /*throwOnLoad*/); AssertExtensions.ThrowsWithInnerException<FileLoadException, Exception>(() => alc.LoadFromAssemblyName(assemblyName)); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alc.ToString(), Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextLoad, alc, $"Exception on Load in '{alc.ToString()}'") } }; } // Successful load through default ALC fallback: // ResolutionAttempted : FindInLoadContext (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextLoad (CustomALC) [AssemblyNotFound] // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [Success] // ResolutionAttempted : DefaultAssemblyLoadContextFallback (CustomALC) [Success] [BinderTest(isolate: true, additionalLoadsToTrack: new string[] { "System.Xml" })] public static BindOperation DefaultAssemblyLoadContextFallback() { var assemblyName = new AssemblyName("System.Xml"); CustomALC alc = new CustomALC(nameof(DefaultAssemblyLoadContextFallback)); Assembly asm = alc.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alc.ToString(), Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextLoad, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.Success, asm), GetResolutionAttempt(assemblyName, ResolutionStage.DefaultAssemblyLoadContextFallback, alc, ResolutionResult.Success, asm) } }; } // Successful load through satellite assembly resolution logic: // ResolutionAttempted : FindInLoadContext (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextLoad (CustomALC) [AssemblyNotFound] // ResolutionAttempted : ResolveSatelliteAssembly (CustomALC) [Success] [BinderTest] public static BindOperation ResolveSatelliteAssembly() { AssemblyName assemblyName = new AssemblyName($"{DependentAssemblyName}.resources"); assemblyName.CultureInfo = SatelliteCulture; CustomALC alc = new CustomALC(nameof(ResolveSatelliteAssembly)); alc.LoadFromAssemblyPath(Helpers.GetAssemblyInAppPath(DependentAssemblyName)); Assembly asm = alc.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alc.ToString(), Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextLoad, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ResolveSatelliteAssembly, alc, ResolutionResult.Success, asm) } }; } // Successful load through AssemblyLoadContext.Resolving event (Custom ALC): // ResolutionAttempted : FindInLoadContext (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextLoad (CustomALC) [AssemblyNotFound] // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : DefaultAssemblyLoadContextFallback (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (CustomALC) [Success] [BinderTest(isolate: true)] public static BindOperation AssemblyLoadContextResolvingEvent_CustomALC() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); CustomALC alc = new CustomALC(nameof(AssemblyLoadContextResolvingEvent_CustomALC)); using (var handlers = new Handlers(HandlerReturn.RequestedAssembly, alc)) { Assembly asm = alc.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alc.ToString(), Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextLoad, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.DefaultAssemblyLoadContextFallback, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, alc, ResolutionResult.Success, asm) }, AssemblyLoadContextResolvingHandlers = handlers.Invocations }; } } // Successful load through AssemblyLoadContext.Resolving event (default ALC): // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (DefaultALC) [Success] [BinderTest(isolate: true)] public static BindOperation AssemblyLoadContextResolvingEvent_DefaultALC() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); using (var handlers = new Handlers(HandlerReturn.RequestedAssembly, AssemblyLoadContext.Default)) { Assembly asm = AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = DefaultALC, Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, AssemblyLoadContext.Default, ResolutionResult.Success, asm) }, AssemblyLoadContextResolvingHandlers = handlers.Invocations }; } } // Exception in AssemblyLoadContext.Resolving event handler (Custom ALC): // ResolutionAttempted : FindInLoadContext (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextLoad (CustomALC) [AssemblyNotFound] // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : DefaultAssemblyLoadContextFallback (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (CustomALC) [Exception] [BinderTest(isolate: true)] public static BindOperation AssemblyLoadContextResolvingEvent_CustomALC_Exception() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); CustomALC alc = new CustomALC(nameof(AssemblyLoadContextResolvingEvent_CustomALC_Exception)); using (var handlers = new Handlers(HandlerReturn.Exception, alc)) { AssertExtensions.ThrowsWithInnerException<FileLoadException, BinderTestException>(() => alc.LoadFromAssemblyName(assemblyName)); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alc.ToString(), Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextLoad, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.DefaultAssemblyLoadContextFallback, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, alc, "Exception in handler for AssemblyLoadContext.Resolving") }, AssemblyLoadContextResolvingHandlers = handlers.Invocations }; } } // Exception in AssemblyLoadContext.Resolving event handler (default ALC): // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (DefaultALC) [Exception] [BinderTest(isolate: true)] public static BindOperation AssemblyLoadContextResolvingEvent_DefaultALC_Exception() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); using (var handlers = new Handlers(HandlerReturn.Exception, AssemblyLoadContext.Default)) { AssertExtensions.ThrowsWithInnerException<FileLoadException, BinderTestException>(() => AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName)); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = DefaultALC, Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, AssemblyLoadContext.Default, "Exception in handler for AssemblyLoadContext.Resolving") }, AssemblyLoadContextResolvingHandlers = handlers.Invocations }; } } // Successful load through AppDomain.AssemblyResolve event (Custom ALC): // ResolutionAttempted : FindInLoadContext (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextLoad (CustomALC) [AssemblyNotFound] // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : DefaultAssemblyLoadContextFallback (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AppDomainAssemblyResolveEvent (CustomALC) [Success] [BinderTest(isolate: true)] public static BindOperation AppDomainAssemblyResolveEvent_CustomALC() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); CustomALC alc = new CustomALC(nameof(AppDomainAssemblyResolveEvent_CustomALC)); using (var handlers = new Handlers(HandlerReturn.RequestedAssembly)) { Assembly asm = alc.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alc.ToString(), Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextLoad, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.DefaultAssemblyLoadContextFallback, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AppDomainAssemblyResolveEvent, alc, ResolutionResult.Success, asm) }, AppDomainAssemblyResolveHandlers = handlers.Invocations }; } } // Successful load through AppDomain.AssemblyResolve event (default ALC): // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : AppDomainAssemblyResolveEvent (DefaultALC) [Success] [BinderTest(isolate: true)] public static BindOperation AppDomainAssemblyResolveEvent_DefaultALC() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); using (var handlers = new Handlers(HandlerReturn.RequestedAssembly)) { Assembly asm = AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = DefaultALC, Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AppDomainAssemblyResolveEvent, AssemblyLoadContext.Default, ResolutionResult.Success, asm) }, AppDomainAssemblyResolveHandlers = handlers.Invocations }; } } // Exception in AppDomain.AssemblyResolve event handler: // ResolutionAttempted : FindInLoadContext (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextLoad (CustomALC) [AssemblyNotFound] // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : DefaultAssemblyLoadContextFallback (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AssemblyLoadContextResolvingEvent (CustomALC) [AssemblyNotFound] // ResolutionAttempted : AppDomainAssemblyResolveEvent (CustomALC) [Exception] [BinderTest(isolate: true)] public static BindOperation AppDomainAssemblyResolveEvent_Exception() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); CustomALC alc = new CustomALC(nameof(AppDomainAssemblyResolveEvent_Exception)); using (var handlers = new Handlers(HandlerReturn.Exception)) { AssertExtensions.ThrowsWithInnerException<FileLoadException, BinderTestException>(() => alc.LoadFromAssemblyName(assemblyName)); return new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alc.ToString(), Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextLoad, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.DefaultAssemblyLoadContextFallback, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AssemblyLoadContextResolvingEvent, alc, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.AppDomainAssemblyResolveEvent, alc, "Exception in handler for AppDomain.AssemblyResolve") }, AppDomainAssemblyResolveHandlers = handlers.Invocations }; } } // Assembly is found in app path when attempted to load through full path: // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [Success] [BinderTest(isolate: true)] public static BindOperation LoadFromAssemblyPath_FoundInAppPath() { var assemblyName = new AssemblyName(DependentAssemblyName); var assemblyPath = Helpers.GetAssemblyInSubdirectoryPath(assemblyName.Name); Assembly asm = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath); Assert.NotEqual(assemblyPath, asm.Location); return new BindOperation() { AssemblyName = asm.GetName(), AssemblyPath = assemblyPath, AssemblyLoadContext = DefaultALC, RequestingAssembly = CoreLibName, RequestingAssemblyLoadContext = DefaultALC, Success = true, ResultAssemblyName = asm.GetName(), ResultAssemblyPath = asm.Location, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(asm.GetName(), ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(asm.GetName(), ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.Success, asm), } }; } // Assembly with different MVID is found in load context when attempted to load through full path: // ResolutionAttempted : FindInLoadContext (DefaultALC) [Failure] [BinderTest(isolate: true, testSetup: nameof(UseDependentAssembly))] public static BindOperation LoadFromAssemblyPath_FoundInLoadContext_DifferentMvid() { var assemblyPath = Helpers.GetAssemblyInSubdirectoryPath($"{DependentAssemblyName}_V2"); string errorMessage = null; try { AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath); } catch (FileLoadException e) { errorMessage = e.Message; } var assemblyName = new AssemblyName($"{DependentAssemblyName}, Version=2.0.0.0"); return new BindOperation() { AssemblyName = assemblyName, AssemblyPath = assemblyPath, AssemblyLoadContext = DefaultALC, RequestingAssembly = CoreLibName, RequestingAssemblyLoadContext = DefaultALC, Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { // GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.IncompatibleVersion, UseDependentAssembly()), GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.Failure, new AssemblyName($"{DependentAssemblyName}, Version=1.0.0.0"), Helpers.GetAssemblyInAppPath(DependentAssemblyName), errorMessage), } }; } // Incompatible version is found in app path when attempted to load through full path: // ResolutionAttempted : FindInLoadContext (DefaultALC) [AssemblyNotFound] // ResolutionAttempted : ApplicationAssemblies (DefaultALC) [IncompatibleVersion] [BinderTest(isolate: true)] public static BindOperation LoadFromAssemblyPath_FoundInAppPath_IncompatibleVersion() { var assemblyPath = Helpers.GetAssemblyInSubdirectoryPath($"{DependentAssemblyName}_V2"); Assert.Throws<FileLoadException>(() => AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath)); var assemblyName = new AssemblyName($"{DependentAssemblyName}, Version=2.0.0.0"); return new BindOperation() { AssemblyName = assemblyName, AssemblyPath = assemblyPath, AssemblyLoadContext = DefaultALC, RequestingAssembly = CoreLibName, RequestingAssemblyLoadContext = DefaultALC, Success = false, Cached = false, ResolutionAttempts = new List<ResolutionAttempt>() { GetResolutionAttempt(assemblyName, ResolutionStage.FindInLoadContext, AssemblyLoadContext.Default, ResolutionResult.AssemblyNotFound), GetResolutionAttempt(assemblyName, ResolutionStage.ApplicationAssemblies, AssemblyLoadContext.Default, ResolutionResult.IncompatibleVersion, new AssemblyName($"{DependentAssemblyName}, Version=1.0.0.0"), Helpers.GetAssemblyInAppPath(DependentAssemblyName)), } }; } private static ResolutionAttempt GetResolutionAttempt(AssemblyName assemblyName, ResolutionStage stage, AssemblyLoadContext alc, string exceptionMessage) { return GetResolutionAttempt(assemblyName, stage, alc, ResolutionResult.Exception, null, null, exceptionMessage); } private static ResolutionAttempt GetResolutionAttempt(AssemblyName assemblyName, ResolutionStage stage, AssemblyLoadContext alc, ResolutionResult result, Assembly resultAssembly = null) { AssemblyName resultAssemblyName = null; string resultAssemblyPath = string.Empty; if (resultAssembly != null) { resultAssemblyName = resultAssembly.GetName(); resultAssemblyPath = resultAssembly.Location; } return GetResolutionAttempt(assemblyName, stage, alc, result, resultAssemblyName, resultAssemblyPath); } private static ResolutionAttempt GetResolutionAttempt(AssemblyName assemblyName, ResolutionStage stage, AssemblyLoadContext alc, ResolutionResult result, AssemblyName resultAssemblyName, string resultAssemblyPath, string errorMessage = null) { var attempt = new ResolutionAttempt() { AssemblyName = assemblyName, Stage = stage, AssemblyLoadContext = alc == AssemblyLoadContext.Default ? DefaultALC : alc.ToString(), Result = result, ResultAssemblyName = resultAssemblyName, ResultAssemblyPath = resultAssemblyPath }; if (!string.IsNullOrEmpty(errorMessage)) { attempt.ErrorMessage = errorMessage; } else { switch (result) { case ResolutionAttempt.ResolutionResult.AssemblyNotFound: attempt.ErrorMessage = "Could not locate assembly"; break; case ResolutionAttempt.ResolutionResult.IncompatibleVersion: attempt.ErrorMessage = $"Requested version {assemblyName.Version} is incompatible with found version {resultAssemblyName.Version}"; break; case ResolutionAttempt.ResolutionResult.MismatchedAssemblyName: attempt.ErrorMessage = $"Requested assembly name '{assemblyName.FullName}' does not match found assembly name '{resultAssemblyName.FullName}'"; break; } } return attempt; } private static void LoadSubdirectoryAssembly_InstanceALC() { string assemblyPath = Helpers.GetAssemblyInSubdirectoryPath(SubdirectoryAssemblyName); loadedAssembly = alcInstance.LoadFromAssemblyPath(assemblyPath); } } }
-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.Extensions.FileSystemGlobbing/src/Abstractions/DirectoryInfoBase.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 Microsoft.Extensions.FileSystemGlobbing.Abstractions { /// <summary> /// Represents a directory /// </summary> public abstract class DirectoryInfoBase : FileSystemInfoBase { /// <summary> /// Enumerates all files and directories in the directory. /// </summary> /// <returns>Collection of files and directories</returns> public abstract IEnumerable<FileSystemInfoBase> EnumerateFileSystemInfos(); /// <summary> /// Returns an instance of <see cref="DirectoryInfoBase" /> that represents a subdirectory /// </summary> /// <param name="path">The directory name</param> /// <returns>Instance of <see cref="DirectoryInfoBase" /> even if directory does not exist</returns> public abstract DirectoryInfoBase? GetDirectory(string path); /// <summary> /// Returns an instance of <see cref="FileInfoBase" /> that represents a file in the directory /// </summary> /// <param name="path">The file name</param> /// <returns>Instance of <see cref="FileInfoBase" /> even if file does not exist</returns> public abstract FileInfoBase? GetFile(string path); } }
// 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 Microsoft.Extensions.FileSystemGlobbing.Abstractions { /// <summary> /// Represents a directory /// </summary> public abstract class DirectoryInfoBase : FileSystemInfoBase { /// <summary> /// Enumerates all files and directories in the directory. /// </summary> /// <returns>Collection of files and directories</returns> public abstract IEnumerable<FileSystemInfoBase> EnumerateFileSystemInfos(); /// <summary> /// Returns an instance of <see cref="DirectoryInfoBase" /> that represents a subdirectory /// </summary> /// <param name="path">The directory name</param> /// <returns>Instance of <see cref="DirectoryInfoBase" /> even if directory does not exist</returns> public abstract DirectoryInfoBase? GetDirectory(string path); /// <summary> /// Returns an instance of <see cref="FileInfoBase" /> that represents a file in the directory /// </summary> /// <param name="path">The file name</param> /// <returns>Instance of <see cref="FileInfoBase" /> even if file does not exist</returns> public abstract FileInfoBase? GetFile(string path); } }
-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/Common/tests/System/Xml/BaseLibManaged/Globalization.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 WebData.BaseLib { public class WebDataBaseLibException : System.Exception { public WebDataBaseLibException(string sExceptionMsg) : base(sExceptionMsg) { } } public class StringGen { public int seed; private string _fileLocation = string.Empty; protected static int[] cWhitespaceMap = { 0x20, 0x9, 0xD, 0xA }; protected static int[] cBaseCharMap = { //Base Chars:: 0x0041, 0x005A, 0x0061, 0x007A, 0x00C0, 0x00D6, 0x00D8, 0x00F6, 0x00F8, 0x00FF, 0x0100, 0x0131, 0x0134, 0x013E, 0x0141, 0x0148, 0x014A, 0x017E, 0x0180, 0x01C3, 0x01CD, 0x01F0, 0x01F4, 0x01F5, 0x01FA, 0x0217, 0x0250, 0x02A8, 0x02BB, 0x02C1, 0x0386, 0x0386, 0x0388, 0x038A, 0x038C, 0x038C, 0x038E, 0x03A1, 0x03A3, 0x03CE, 0x03D0, 0x03D6, 0x03DA, 0x03DA, 0x03DC, 0x03DC, 0x03DE, 0x03DE, 0x03E0, 0x03E0, 0x03E2, 0x03F3, 0x0401, 0x040C, 0x040E, 0x044F, 0x0451, 0x045C, 0x045E, 0x0481, 0x0490, 0x04C4, 0x04C7, 0x04C8, 0x04CB, 0x04CC, 0x04D0, 0x04EB, 0x04EE, 0x04F5, 0x04F8, 0x04F9, 0x0531, 0x0556, 0x0559, 0x0559, 0x0561, 0x0586, 0x05D0, 0x05EA, 0x05F0, 0x05F2, 0x0621, 0x063A, 0x0641, 0x064A, 0x0671, 0x06B7, 0x06BA, 0x06BE, 0x06C0, 0x06CE, 0x06D0, 0x06D3, 0x06D5, 0x06D5, 0x06E5, 0x06E6, 0x0905, 0x0939, 0x093D, 0x093D, 0x0958, 0x0961, 0x0985, 0x098C, 0x098F, 0x0990, 0x0993, 0x09A8, 0x09AA, 0x09B0, 0x09B2, 0x09B2, 0x09B6, 0x09B9, 0x09DC, 0x09DD, 0x09DF, 0x09E1, 0x09F0, 0x09F1, 0x0A05, 0x0A0A, 0x0A0F, 0x0A10, 0x0A13, 0x0A28, 0x0A2A, 0x0A30, 0x0A32, 0x0A33, 0x0A35, 0x0A36, 0x0A38, 0x0A39, 0x0A59, 0x0A5C, 0x0A5E, 0x0A5E, 0x0A72, 0x0A74, 0x0A85, 0x0A8B, 0x0A8D, 0x0A8D, 0x0A8F, 0x0A91, 0x0A93, 0x0AA8, 0x0AAA, 0x0AB0, 0x0AB2, 0x0AB3, 0x0AB5, 0x0AB9, 0x0ABD, 0x0ABD, 0x0AE0, 0x0AE0, 0x0B05, 0x0B0C, 0x0B0F, 0x0B10, 0x0B13, 0x0B28, 0x0B2A, 0x0B30, 0x0B32, 0x0B33, 0x0B36, 0x0B39, 0x0B3D, 0x0B3D, 0x0B5C, 0x0B5D, 0x0B5F, 0x0B61, 0x0B85, 0x0B8A, 0x0B8E, 0x0B90, 0x0B92, 0x0B95, 0x0B99, 0x0B9A, 0x0B9C, 0x0B9C, 0x0B9E, 0x0B9F, 0x0BA3, 0x0BA4, 0x0BA8, 0x0BAA, 0x0BAE, 0x0BB5, 0x0BB7, 0x0BB9, 0x0C05, 0x0C0C, 0x0C0E, 0x0C10, 0x0C12, 0x0C28, 0x0C2A, 0x0C33, 0x0C35, 0x0C39, 0x0C60, 0x0C61, 0x0C85, 0x0C8C, 0x0C8E, 0x0C90, 0x0C92, 0x0CA8, 0x0CAA, 0x0CB3, 0x0CB5, 0x0CB9, 0x0CDE, 0x0CDE, 0x0CE0, 0x0CE1, 0x0D05, 0x0D0C, 0x0D0E, 0x0D10, 0x0D12, 0x0D28, 0x0D2A, 0x0D39, 0x0D60, 0x0D61, 0x0E01, 0x0E2E, 0x0E30, 0x0E30, 0x0E32, 0x0E33, 0x0E40, 0x0E45, 0x0E81, 0x0E82, 0x0E84, 0x0E84, 0x0E87, 0x0E88, 0x0E8A, 0x0E8A, 0x0E8D, 0x0E8D, 0x0E94, 0x0E97, 0x0E99, 0x0E9F, 0x0EA1, 0x0EA3, 0x0EA5, 0x0EA5, 0x0EA7, 0x0EA7, 0x0EAA, 0x0EAB, 0x0EAD, 0x0EAE, 0x0EB0, 0x0EB0, 0x0EB2, 0x0EB3, 0x0EBD, 0x0EBD, 0x0EC0, 0x0EC4, 0x0F40, 0x0F47, 0x0F49, 0x0F69, 0x10A0, 0x10C5, 0x10D0, 0x10F6, 0x1100, 0x1100, 0x1102, 0x1103, 0x1105, 0x1107, 0x1109, 0x1109, 0x110B, 0x110C, 0x110E, 0x1112, 0x113C, 0x113C, 0x113E, 0x113E, 0x1140, 0x1140, 0x114C, 0x114C, 0x114E, 0x114E, 0x1150, 0x1150, 0x1154, 0x1155, 0x1159, 0x1159, 0x115F, 0x1161, 0x1163, 0x1163, 0x1165, 0x1165, 0x1167, 0x1167, 0x1169, 0x1169, 0x116D, 0x116E, 0x1172, 0x1173, 0x1175, 0x1175, 0x119E, 0x119E, 0x11A8, 0x11A8, 0x11AB, 0x11AB, 0x11AE, 0x11AF, 0x11B7, 0x11B8, 0x11BA, 0x11BA, 0x11BC, 0x11C2, 0x11EB, 0x11EB, 0x11F0, 0x11F0, 0x11F9, 0x11F9, 0x1E00, 0x1E9B, 0x1EA0, 0x1EF9, 0x1F00, 0x1F15, 0x1F18, 0x1F1D, 0x1F20, 0x1F45, 0x1F48, 0x1F4D, 0x1F50, 0x1F57, 0x1F59, 0x1F59, 0x1F5B, 0x1F5B, 0x1F5D, 0x1F5D, 0x1F5F, 0x1F7D, 0x1F80, 0x1FB4, 0x1FB6, 0x1FBC, 0x1FBE, 0x1FBE, 0x1FC2, 0x1FC4, 0x1FC6, 0x1FCC, 0x1FD0, 0x1FD3, 0x1FD6, 0x1FDB, 0x1FE0, 0x1FEC, 0x1FF2, 0x1FF4, 0x1FF6, 0x1FFC, 0x2126, 0x2126, 0x212A, 0x212B, 0x212E, 0x212E, 0x2180, 0x2182, 0x3041, 0x3094, 0x30A1, 0x30FA, 0x3105, 0x312C, 0xAC00, 0xD7A3, //Ideographic:: 0x4E00, 0x9FA5, 0x3007, 0x3007, 0x3021, 0x3029, //Combining Chars:: 0x0300, 0x0345, 0x0360, 0x0361, 0x0483, 0x0486, 0x0591, 0x05A1, 0x05A3, 0x05B9, 0x05BB, 0x05BD, 0x05BF, 0x05BF, 0x05C1, 0x05C2, 0x05C4, 0x05C4, 0x064B, 0x0652, 0x0670, 0x0670, 0x06D6, 0x06DC, 0x06DD, 0x06DF, 0x06E0, 0x06E4, 0x06E7, 0x06E8, 0x06EA, 0x06ED, 0x0901, 0x0903, 0x093C, 0x093C, 0x093E, 0x094C, 0x094D, 0x094D, 0x0951, 0x0954, 0x0962, 0x0963, 0x0981, 0x0983, 0x09BC, 0x09BC, 0x09BE, 0x09BE, 0x09BF, 0x09BF, 0x09C0, 0x09C4, 0x09C7, 0x09C8, 0x09CB, 0x09CD, 0x09D7, 0x09D7, 0x09E2, 0x09E3, 0x0A02, 0x0A02, 0x0A3C, 0x0A3C, 0x0A3E, 0x0A3E, 0x0A3F, 0x0A3F, 0x0A40, 0x0A42, 0x0A47, 0x0A48, 0x0A4B, 0x0A4D, 0x0A70, 0x0A71, 0x0A81, 0x0A83, 0x0ABC, 0x0ABC, 0x0ABE, 0x0AC5, 0x0AC7, 0x0AC9, 0x0ACB, 0x0ACD, 0x0B01, 0x0B03, 0x0B3C, 0x0B3C, 0x0B3E, 0x0B43, 0x0B47, 0x0B48, 0x0B4B, 0x0B4D, 0x0B56, 0x0B57, 0x0B82, 0x0B83, 0x0BBE, 0x0BC2, 0x0BC6, 0x0BC8, 0x0BCA, 0x0BCD, 0x0BD7, 0x0BD7, 0x0C01, 0x0C03, 0x0C3E, 0x0C44, 0x0C46, 0x0C48, 0x0C4A, 0x0C4D, 0x0C55, 0x0C56, 0x0C82, 0x0C83, 0x0CBE, 0x0CC4, 0x0CC6, 0x0CC8, 0x0CCA, 0x0CCD, 0x0CD5, 0x0CD6, 0x0D02, 0x0D03, 0x0D3E, 0x0D43, 0x0D46, 0x0D48, 0x0D4A, 0x0D4D, 0x0D57, 0x0D57, 0x0E31, 0x0E31, 0x0E34, 0x0E3A, 0x0E47, 0x0E4E, 0x0EB1, 0x0EB1, 0x0EB4, 0x0EB9, 0x0EBB, 0x0EBC, 0x0EC8, 0x0ECD, 0x0F18, 0x0F19, 0x0F35, 0x0F35, 0x0F37, 0x0F37, 0x0F39, 0x0F39, 0x0F3E, 0x0F3E, 0x0F3F, 0x0F3F, 0x0F71, 0x0F84, 0x0F86, 0x0F8B, 0x0F90, 0x0F95, 0x0F97, 0x0F97, 0x0F99, 0x0FAD, 0x0FB1, 0x0FB7, 0x0FB9, 0x0FB9, 0x20D0, 0x20DC, 0x20E1, 0x20E1, 0x302A, 0x302F, 0x3099, 0x3099, 0x309A, 0x309A, //Digit:: 0x0030, 0x0039, 0x0660, 0x0669, 0x06F0, 0x06F9, 0x0966, 0x096F, 0x09E6, 0x09EF, 0x0A66, 0x0A6F, 0x0AE6, 0x0AEF, 0x0B66, 0x0B6F, 0x0BE7, 0x0BEF, 0x0C66, 0x0C6F, 0x0CE6, 0x0CEF, 0x0D66, 0x0D6F, 0x0E50, 0x0E59, 0x0ED0, 0x0ED9, 0x0F20, 0x0F29, //Extender:: 0x00B7, 0x00B7, 0x02D0, 0x02D0, 0x02D1, 0x02D1, 0x0387, 0x0387, 0x0640, 0x0640, 0x0E46, 0x0E46, 0x0EC6, 0x0EC6, 0x3005, 0x3005, 0x3031, 0x3035, 0x309D, 0x309E, 0x30FC, 0x30FE }; public static string GetIllegalXmlString(int iMaxChar, bool bAbsolute) { return WebData.BaseLib.StringGen.GetIllegalXmlStringWithSeed(iMaxChar, bAbsolute, 0); } public static string GetIllegalXmlStringWithSeed(int iMaxChar, bool bAbsolute, int iSeed) { int i = 0; Random cRandom; if (iSeed != 0) { cRandom = new Random(iSeed); } else { cRandom = new Random(); } string sResult = string.Empty; int iStrLen = bAbsolute ? iMaxChar : cRandom.Next(1, iMaxChar); //get the maximum number of illegal characters in the valid range. int iSum = 0; for (i = 0; i < cBaseCharMap.Length; i += 2) { //special processing for 0 if (i == 0) { iSum += cBaseCharMap[i] - 1; } else { //as the data in the table is not sequential, we //we need to take an educated guess if this is a non interval //we will take that the rage shouldn't be more than 100 chars //as well as the range shouldn't be negative if ((cBaseCharMap[i] - cBaseCharMap[i - 1] - 1 > 0) && (cBaseCharMap[i] - cBaseCharMap[i - 1] - 1 < 100)) { iSum += cBaseCharMap[i] - cBaseCharMap[i - 1] - 1; } } } for (int iChar = 0; iChar < iStrLen; iChar++) { //get a rand number out of that int iRandNum = cRandom.Next(iSum); //get the right char under the number we just got i = 0; int iVal = 0; while (true) { iVal = iRandNum; //special case for 0 if (i == 0) { iRandNum -= cBaseCharMap[i] - 1; } else { if (cBaseCharMap[i] - cBaseCharMap[i - 1] - 1 > 0) { iRandNum -= cBaseCharMap[i] - cBaseCharMap[i - 1] - 1; } } if (iRandNum >= 0) { i += 2; } else { break; } } //special case for i=0 if (i == 0) { sResult += (char)iVal; } else { sResult += (char)(cBaseCharMap[i - 1] + iVal); } } //for string return sResult; } } //StringGen }//namespace
// 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 WebData.BaseLib { public class WebDataBaseLibException : System.Exception { public WebDataBaseLibException(string sExceptionMsg) : base(sExceptionMsg) { } } public class StringGen { public int seed; private string _fileLocation = string.Empty; protected static int[] cWhitespaceMap = { 0x20, 0x9, 0xD, 0xA }; protected static int[] cBaseCharMap = { //Base Chars:: 0x0041, 0x005A, 0x0061, 0x007A, 0x00C0, 0x00D6, 0x00D8, 0x00F6, 0x00F8, 0x00FF, 0x0100, 0x0131, 0x0134, 0x013E, 0x0141, 0x0148, 0x014A, 0x017E, 0x0180, 0x01C3, 0x01CD, 0x01F0, 0x01F4, 0x01F5, 0x01FA, 0x0217, 0x0250, 0x02A8, 0x02BB, 0x02C1, 0x0386, 0x0386, 0x0388, 0x038A, 0x038C, 0x038C, 0x038E, 0x03A1, 0x03A3, 0x03CE, 0x03D0, 0x03D6, 0x03DA, 0x03DA, 0x03DC, 0x03DC, 0x03DE, 0x03DE, 0x03E0, 0x03E0, 0x03E2, 0x03F3, 0x0401, 0x040C, 0x040E, 0x044F, 0x0451, 0x045C, 0x045E, 0x0481, 0x0490, 0x04C4, 0x04C7, 0x04C8, 0x04CB, 0x04CC, 0x04D0, 0x04EB, 0x04EE, 0x04F5, 0x04F8, 0x04F9, 0x0531, 0x0556, 0x0559, 0x0559, 0x0561, 0x0586, 0x05D0, 0x05EA, 0x05F0, 0x05F2, 0x0621, 0x063A, 0x0641, 0x064A, 0x0671, 0x06B7, 0x06BA, 0x06BE, 0x06C0, 0x06CE, 0x06D0, 0x06D3, 0x06D5, 0x06D5, 0x06E5, 0x06E6, 0x0905, 0x0939, 0x093D, 0x093D, 0x0958, 0x0961, 0x0985, 0x098C, 0x098F, 0x0990, 0x0993, 0x09A8, 0x09AA, 0x09B0, 0x09B2, 0x09B2, 0x09B6, 0x09B9, 0x09DC, 0x09DD, 0x09DF, 0x09E1, 0x09F0, 0x09F1, 0x0A05, 0x0A0A, 0x0A0F, 0x0A10, 0x0A13, 0x0A28, 0x0A2A, 0x0A30, 0x0A32, 0x0A33, 0x0A35, 0x0A36, 0x0A38, 0x0A39, 0x0A59, 0x0A5C, 0x0A5E, 0x0A5E, 0x0A72, 0x0A74, 0x0A85, 0x0A8B, 0x0A8D, 0x0A8D, 0x0A8F, 0x0A91, 0x0A93, 0x0AA8, 0x0AAA, 0x0AB0, 0x0AB2, 0x0AB3, 0x0AB5, 0x0AB9, 0x0ABD, 0x0ABD, 0x0AE0, 0x0AE0, 0x0B05, 0x0B0C, 0x0B0F, 0x0B10, 0x0B13, 0x0B28, 0x0B2A, 0x0B30, 0x0B32, 0x0B33, 0x0B36, 0x0B39, 0x0B3D, 0x0B3D, 0x0B5C, 0x0B5D, 0x0B5F, 0x0B61, 0x0B85, 0x0B8A, 0x0B8E, 0x0B90, 0x0B92, 0x0B95, 0x0B99, 0x0B9A, 0x0B9C, 0x0B9C, 0x0B9E, 0x0B9F, 0x0BA3, 0x0BA4, 0x0BA8, 0x0BAA, 0x0BAE, 0x0BB5, 0x0BB7, 0x0BB9, 0x0C05, 0x0C0C, 0x0C0E, 0x0C10, 0x0C12, 0x0C28, 0x0C2A, 0x0C33, 0x0C35, 0x0C39, 0x0C60, 0x0C61, 0x0C85, 0x0C8C, 0x0C8E, 0x0C90, 0x0C92, 0x0CA8, 0x0CAA, 0x0CB3, 0x0CB5, 0x0CB9, 0x0CDE, 0x0CDE, 0x0CE0, 0x0CE1, 0x0D05, 0x0D0C, 0x0D0E, 0x0D10, 0x0D12, 0x0D28, 0x0D2A, 0x0D39, 0x0D60, 0x0D61, 0x0E01, 0x0E2E, 0x0E30, 0x0E30, 0x0E32, 0x0E33, 0x0E40, 0x0E45, 0x0E81, 0x0E82, 0x0E84, 0x0E84, 0x0E87, 0x0E88, 0x0E8A, 0x0E8A, 0x0E8D, 0x0E8D, 0x0E94, 0x0E97, 0x0E99, 0x0E9F, 0x0EA1, 0x0EA3, 0x0EA5, 0x0EA5, 0x0EA7, 0x0EA7, 0x0EAA, 0x0EAB, 0x0EAD, 0x0EAE, 0x0EB0, 0x0EB0, 0x0EB2, 0x0EB3, 0x0EBD, 0x0EBD, 0x0EC0, 0x0EC4, 0x0F40, 0x0F47, 0x0F49, 0x0F69, 0x10A0, 0x10C5, 0x10D0, 0x10F6, 0x1100, 0x1100, 0x1102, 0x1103, 0x1105, 0x1107, 0x1109, 0x1109, 0x110B, 0x110C, 0x110E, 0x1112, 0x113C, 0x113C, 0x113E, 0x113E, 0x1140, 0x1140, 0x114C, 0x114C, 0x114E, 0x114E, 0x1150, 0x1150, 0x1154, 0x1155, 0x1159, 0x1159, 0x115F, 0x1161, 0x1163, 0x1163, 0x1165, 0x1165, 0x1167, 0x1167, 0x1169, 0x1169, 0x116D, 0x116E, 0x1172, 0x1173, 0x1175, 0x1175, 0x119E, 0x119E, 0x11A8, 0x11A8, 0x11AB, 0x11AB, 0x11AE, 0x11AF, 0x11B7, 0x11B8, 0x11BA, 0x11BA, 0x11BC, 0x11C2, 0x11EB, 0x11EB, 0x11F0, 0x11F0, 0x11F9, 0x11F9, 0x1E00, 0x1E9B, 0x1EA0, 0x1EF9, 0x1F00, 0x1F15, 0x1F18, 0x1F1D, 0x1F20, 0x1F45, 0x1F48, 0x1F4D, 0x1F50, 0x1F57, 0x1F59, 0x1F59, 0x1F5B, 0x1F5B, 0x1F5D, 0x1F5D, 0x1F5F, 0x1F7D, 0x1F80, 0x1FB4, 0x1FB6, 0x1FBC, 0x1FBE, 0x1FBE, 0x1FC2, 0x1FC4, 0x1FC6, 0x1FCC, 0x1FD0, 0x1FD3, 0x1FD6, 0x1FDB, 0x1FE0, 0x1FEC, 0x1FF2, 0x1FF4, 0x1FF6, 0x1FFC, 0x2126, 0x2126, 0x212A, 0x212B, 0x212E, 0x212E, 0x2180, 0x2182, 0x3041, 0x3094, 0x30A1, 0x30FA, 0x3105, 0x312C, 0xAC00, 0xD7A3, //Ideographic:: 0x4E00, 0x9FA5, 0x3007, 0x3007, 0x3021, 0x3029, //Combining Chars:: 0x0300, 0x0345, 0x0360, 0x0361, 0x0483, 0x0486, 0x0591, 0x05A1, 0x05A3, 0x05B9, 0x05BB, 0x05BD, 0x05BF, 0x05BF, 0x05C1, 0x05C2, 0x05C4, 0x05C4, 0x064B, 0x0652, 0x0670, 0x0670, 0x06D6, 0x06DC, 0x06DD, 0x06DF, 0x06E0, 0x06E4, 0x06E7, 0x06E8, 0x06EA, 0x06ED, 0x0901, 0x0903, 0x093C, 0x093C, 0x093E, 0x094C, 0x094D, 0x094D, 0x0951, 0x0954, 0x0962, 0x0963, 0x0981, 0x0983, 0x09BC, 0x09BC, 0x09BE, 0x09BE, 0x09BF, 0x09BF, 0x09C0, 0x09C4, 0x09C7, 0x09C8, 0x09CB, 0x09CD, 0x09D7, 0x09D7, 0x09E2, 0x09E3, 0x0A02, 0x0A02, 0x0A3C, 0x0A3C, 0x0A3E, 0x0A3E, 0x0A3F, 0x0A3F, 0x0A40, 0x0A42, 0x0A47, 0x0A48, 0x0A4B, 0x0A4D, 0x0A70, 0x0A71, 0x0A81, 0x0A83, 0x0ABC, 0x0ABC, 0x0ABE, 0x0AC5, 0x0AC7, 0x0AC9, 0x0ACB, 0x0ACD, 0x0B01, 0x0B03, 0x0B3C, 0x0B3C, 0x0B3E, 0x0B43, 0x0B47, 0x0B48, 0x0B4B, 0x0B4D, 0x0B56, 0x0B57, 0x0B82, 0x0B83, 0x0BBE, 0x0BC2, 0x0BC6, 0x0BC8, 0x0BCA, 0x0BCD, 0x0BD7, 0x0BD7, 0x0C01, 0x0C03, 0x0C3E, 0x0C44, 0x0C46, 0x0C48, 0x0C4A, 0x0C4D, 0x0C55, 0x0C56, 0x0C82, 0x0C83, 0x0CBE, 0x0CC4, 0x0CC6, 0x0CC8, 0x0CCA, 0x0CCD, 0x0CD5, 0x0CD6, 0x0D02, 0x0D03, 0x0D3E, 0x0D43, 0x0D46, 0x0D48, 0x0D4A, 0x0D4D, 0x0D57, 0x0D57, 0x0E31, 0x0E31, 0x0E34, 0x0E3A, 0x0E47, 0x0E4E, 0x0EB1, 0x0EB1, 0x0EB4, 0x0EB9, 0x0EBB, 0x0EBC, 0x0EC8, 0x0ECD, 0x0F18, 0x0F19, 0x0F35, 0x0F35, 0x0F37, 0x0F37, 0x0F39, 0x0F39, 0x0F3E, 0x0F3E, 0x0F3F, 0x0F3F, 0x0F71, 0x0F84, 0x0F86, 0x0F8B, 0x0F90, 0x0F95, 0x0F97, 0x0F97, 0x0F99, 0x0FAD, 0x0FB1, 0x0FB7, 0x0FB9, 0x0FB9, 0x20D0, 0x20DC, 0x20E1, 0x20E1, 0x302A, 0x302F, 0x3099, 0x3099, 0x309A, 0x309A, //Digit:: 0x0030, 0x0039, 0x0660, 0x0669, 0x06F0, 0x06F9, 0x0966, 0x096F, 0x09E6, 0x09EF, 0x0A66, 0x0A6F, 0x0AE6, 0x0AEF, 0x0B66, 0x0B6F, 0x0BE7, 0x0BEF, 0x0C66, 0x0C6F, 0x0CE6, 0x0CEF, 0x0D66, 0x0D6F, 0x0E50, 0x0E59, 0x0ED0, 0x0ED9, 0x0F20, 0x0F29, //Extender:: 0x00B7, 0x00B7, 0x02D0, 0x02D0, 0x02D1, 0x02D1, 0x0387, 0x0387, 0x0640, 0x0640, 0x0E46, 0x0E46, 0x0EC6, 0x0EC6, 0x3005, 0x3005, 0x3031, 0x3035, 0x309D, 0x309E, 0x30FC, 0x30FE }; public static string GetIllegalXmlString(int iMaxChar, bool bAbsolute) { return WebData.BaseLib.StringGen.GetIllegalXmlStringWithSeed(iMaxChar, bAbsolute, 0); } public static string GetIllegalXmlStringWithSeed(int iMaxChar, bool bAbsolute, int iSeed) { int i = 0; Random cRandom; if (iSeed != 0) { cRandom = new Random(iSeed); } else { cRandom = new Random(); } string sResult = string.Empty; int iStrLen = bAbsolute ? iMaxChar : cRandom.Next(1, iMaxChar); //get the maximum number of illegal characters in the valid range. int iSum = 0; for (i = 0; i < cBaseCharMap.Length; i += 2) { //special processing for 0 if (i == 0) { iSum += cBaseCharMap[i] - 1; } else { //as the data in the table is not sequential, we //we need to take an educated guess if this is a non interval //we will take that the rage shouldn't be more than 100 chars //as well as the range shouldn't be negative if ((cBaseCharMap[i] - cBaseCharMap[i - 1] - 1 > 0) && (cBaseCharMap[i] - cBaseCharMap[i - 1] - 1 < 100)) { iSum += cBaseCharMap[i] - cBaseCharMap[i - 1] - 1; } } } for (int iChar = 0; iChar < iStrLen; iChar++) { //get a rand number out of that int iRandNum = cRandom.Next(iSum); //get the right char under the number we just got i = 0; int iVal = 0; while (true) { iVal = iRandNum; //special case for 0 if (i == 0) { iRandNum -= cBaseCharMap[i] - 1; } else { if (cBaseCharMap[i] - cBaseCharMap[i - 1] - 1 > 0) { iRandNum -= cBaseCharMap[i] - cBaseCharMap[i - 1] - 1; } } if (iRandNum >= 0) { i += 2; } else { break; } } //special case for i=0 if (i == 0) { sResult += (char)iVal; } else { sResult += (char)(cBaseCharMap[i - 1] + iVal); } } //for string return sResult; } } //StringGen }//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/tests/JIT/HardwareIntrinsics/General/Vector64/Negate.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 NegateSingle() { var test = new VectorUnaryOpTest__NegateSingle(); // 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__NegateSingle { 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 Vector64<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<Vector64<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__NegateSingle testClass) { var result = Vector64.Negate(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector64<Single> _clsVar1; private Vector64<Single> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__NegateSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); } public VectorUnaryOpTest__NegateSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<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 = Vector64.Negate( Unsafe.Read<Vector64<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(Vector64).GetMethod(nameof(Vector64.Negate), new Type[] { typeof(Vector64<Single>) }); if (method is null) { method = typeof(Vector64).GetMethod(nameof(Vector64.Negate), 1, new Type[] { typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Single)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector64.Negate( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr); var result = Vector64.Negate(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__NegateSingle(); var result = Vector64.Negate(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector64.Negate(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector64.Negate(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(Vector64<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<Vector64<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<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (float)(0 - firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (float)(0 - firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.Negate)}<Single>(Vector64<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 NegateSingle() { var test = new VectorUnaryOpTest__NegateSingle(); // 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__NegateSingle { 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 Vector64<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<Vector64<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__NegateSingle testClass) { var result = Vector64.Negate(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector64<Single> _clsVar1; private Vector64<Single> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__NegateSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); } public VectorUnaryOpTest__NegateSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<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 = Vector64.Negate( Unsafe.Read<Vector64<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(Vector64).GetMethod(nameof(Vector64.Negate), new Type[] { typeof(Vector64<Single>) }); if (method is null) { method = typeof(Vector64).GetMethod(nameof(Vector64.Negate), 1, new Type[] { typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Single)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector64.Negate( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr); var result = Vector64.Negate(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__NegateSingle(); var result = Vector64.Negate(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector64.Negate(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector64.Negate(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(Vector64<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<Vector64<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<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (float)(0 - firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (float)(0 - firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.Negate)}<Single>(Vector64<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,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.Arm64/SubtractSaturateScalar.Vector64.Int16.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 SubtractSaturateScalar_Vector64_Int16() { var test = new SimpleBinaryOpTest__SubtractSaturateScalar_Vector64_Int16(); 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__SubtractSaturateScalar_Vector64_Int16 { 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(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); 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<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, 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<Int16> _fld1; public Vector64<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__SubtractSaturateScalar_Vector64_Int16 testClass) { var result = AdvSimd.Arm64.SubtractSaturateScalar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__SubtractSaturateScalar_Vector64_Int16 testClass) { fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.SubtractSaturateScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(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<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector64<Int16> _clsVar1; private static Vector64<Int16> _clsVar2; private Vector64<Int16> _fld1; private Vector64<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__SubtractSaturateScalar_Vector64_Int16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); } public SimpleBinaryOpTest__SubtractSaturateScalar_Vector64_Int16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.SubtractSaturateScalar( Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_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.Arm64.SubtractSaturateScalar( AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_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.Arm64).GetMethod(nameof(AdvSimd.Arm64.SubtractSaturateScalar), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.SubtractSaturateScalar), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.SubtractSaturateScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int16>* pClsVar1 = &_clsVar1) fixed (Vector64<Int16>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.SubtractSaturateScalar( AdvSimd.LoadVector64((Int16*)(pClsVar1)), AdvSimd.LoadVector64((Int16*)(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<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.SubtractSaturateScalar(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((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.SubtractSaturateScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__SubtractSaturateScalar_Vector64_Int16(); var result = AdvSimd.Arm64.SubtractSaturateScalar(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__SubtractSaturateScalar_Vector64_Int16(); fixed (Vector64<Int16>* pFld1 = &test._fld1) fixed (Vector64<Int16>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.SubtractSaturateScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.SubtractSaturateScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.SubtractSaturateScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(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.Arm64.SubtractSaturateScalar(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.Arm64.SubtractSaturateScalar( AdvSimd.LoadVector64((Int16*)(&test._fld1)), AdvSimd.LoadVector64((Int16*)(&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<Int16> op1, Vector64<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (Helpers.SubtractSaturate(left[0], right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.SubtractSaturateScalar)}<Int16>(Vector64<Int16>, Vector64<Int16>): {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 SubtractSaturateScalar_Vector64_Int16() { var test = new SimpleBinaryOpTest__SubtractSaturateScalar_Vector64_Int16(); 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__SubtractSaturateScalar_Vector64_Int16 { 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(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); 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<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, 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<Int16> _fld1; public Vector64<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__SubtractSaturateScalar_Vector64_Int16 testClass) { var result = AdvSimd.Arm64.SubtractSaturateScalar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__SubtractSaturateScalar_Vector64_Int16 testClass) { fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.SubtractSaturateScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(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<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector64<Int16> _clsVar1; private static Vector64<Int16> _clsVar2; private Vector64<Int16> _fld1; private Vector64<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__SubtractSaturateScalar_Vector64_Int16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); } public SimpleBinaryOpTest__SubtractSaturateScalar_Vector64_Int16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.SubtractSaturateScalar( Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_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.Arm64.SubtractSaturateScalar( AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_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.Arm64).GetMethod(nameof(AdvSimd.Arm64.SubtractSaturateScalar), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.SubtractSaturateScalar), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.SubtractSaturateScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int16>* pClsVar1 = &_clsVar1) fixed (Vector64<Int16>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.SubtractSaturateScalar( AdvSimd.LoadVector64((Int16*)(pClsVar1)), AdvSimd.LoadVector64((Int16*)(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<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.SubtractSaturateScalar(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((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.SubtractSaturateScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__SubtractSaturateScalar_Vector64_Int16(); var result = AdvSimd.Arm64.SubtractSaturateScalar(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__SubtractSaturateScalar_Vector64_Int16(); fixed (Vector64<Int16>* pFld1 = &test._fld1) fixed (Vector64<Int16>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.SubtractSaturateScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.SubtractSaturateScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.SubtractSaturateScalar( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(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.Arm64.SubtractSaturateScalar(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.Arm64.SubtractSaturateScalar( AdvSimd.LoadVector64((Int16*)(&test._fld1)), AdvSimd.LoadVector64((Int16*)(&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<Int16> op1, Vector64<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (Helpers.SubtractSaturate(left[0], right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.SubtractSaturateScalar)}<Int16>(Vector64<Int16>, Vector64<Int16>): {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/coreclr/tools/aot/ILCompiler.MetadataTransform/ILCompiler/Metadata/MetadataTransform.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 Internal.Metadata.NativeFormat.Writer; using Cts = Internal.TypeSystem; namespace ILCompiler.Metadata { /// <summary> /// Transforms type system object model into metadata writer object model that is suitable /// for binary serialization into a metadata blob using the <see cref="MetadataWriter"/> class. /// </summary> public abstract class MetadataTransform { /// <summary> /// Transforms the specified modules using the specified metadata generation /// policy. Policy is required to be a struct for performance reasons. /// </summary> /// <remarks> /// The list of <paramref name="modules"/> is required to be transitively complete with respect to /// <paramref name="policy"/>: whenever there's a reference from the object graph to a type or member defined in a /// module that was not included in the <paramref name="modules"/> enumeration, the /// <see cref="IMetadataPolicy.GeneratesMetadata(Cts.MetadataType)"/> /// and <see cref="IMetadataPolicy.GeneratesMetadata(Cts.MethodDesc)"/> are required to return false. /// </remarks> public static MetadataTransformResult<TPolicy> Run<TPolicy>(TPolicy policy, IEnumerable<Cts.ModuleDesc> modules) where TPolicy : struct, IMetadataPolicy { // TODO: Make this multithreaded. The high level plan is: // - make EntityMap thread safe // - change the way TypeDefs are hooked up into namespaces and scopes // - queue up calls to the various Initialize* methods on a threadpool var transform = new Transform<TPolicy>(policy); foreach (var module in modules) { foreach (var type in module.GetAllTypes()) { if (policy.GeneratesMetadata(type) && !policy.IsBlocked(type)) { transform.HandleType(type); } } } return new MetadataTransformResult<TPolicy>(transform); } /// <summary> /// Retrieves an existing <see cref="TypeDefinition"/>, <see cref="TypeReference"/>, /// or <see cref="TypeSpecification"/> record representing specified type in the metadata writer object /// model, or creates a new one. /// </summary> public abstract MetadataRecord HandleType(Cts.TypeDesc type); /// <summary> /// Retrieves an existing <see cref="QualifiedMethod"/>, <see cref="MemberReference"/>, or <see cref="MethodInstantiation"/> /// record representing specified method in the metadata writer object model, or creates a new one. /// </summary> public abstract MetadataRecord HandleQualifiedMethod(Cts.MethodDesc method); /// <summary> /// Retrieves an existing <see cref="QualifiedField"> or a <see cref="MemberReference"/> record /// representing specified field in the metadata writer object model, or creates a new one. /// </summary> public abstract MetadataRecord HandleQualifiedField(Cts.FieldDesc field); /// <summary> /// Retrieves an existing <see cref="MethodSignature"/> record representing the specified signature /// in the metadata writer object model, or creates a new one. /// </summary> public abstract MethodSignature HandleMethodSignature(Cts.MethodSignature signature); } }
// 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 Internal.Metadata.NativeFormat.Writer; using Cts = Internal.TypeSystem; namespace ILCompiler.Metadata { /// <summary> /// Transforms type system object model into metadata writer object model that is suitable /// for binary serialization into a metadata blob using the <see cref="MetadataWriter"/> class. /// </summary> public abstract class MetadataTransform { /// <summary> /// Transforms the specified modules using the specified metadata generation /// policy. Policy is required to be a struct for performance reasons. /// </summary> /// <remarks> /// The list of <paramref name="modules"/> is required to be transitively complete with respect to /// <paramref name="policy"/>: whenever there's a reference from the object graph to a type or member defined in a /// module that was not included in the <paramref name="modules"/> enumeration, the /// <see cref="IMetadataPolicy.GeneratesMetadata(Cts.MetadataType)"/> /// and <see cref="IMetadataPolicy.GeneratesMetadata(Cts.MethodDesc)"/> are required to return false. /// </remarks> public static MetadataTransformResult<TPolicy> Run<TPolicy>(TPolicy policy, IEnumerable<Cts.ModuleDesc> modules) where TPolicy : struct, IMetadataPolicy { // TODO: Make this multithreaded. The high level plan is: // - make EntityMap thread safe // - change the way TypeDefs are hooked up into namespaces and scopes // - queue up calls to the various Initialize* methods on a threadpool var transform = new Transform<TPolicy>(policy); foreach (var module in modules) { foreach (var type in module.GetAllTypes()) { if (policy.GeneratesMetadata(type) && !policy.IsBlocked(type)) { transform.HandleType(type); } } } return new MetadataTransformResult<TPolicy>(transform); } /// <summary> /// Retrieves an existing <see cref="TypeDefinition"/>, <see cref="TypeReference"/>, /// or <see cref="TypeSpecification"/> record representing specified type in the metadata writer object /// model, or creates a new one. /// </summary> public abstract MetadataRecord HandleType(Cts.TypeDesc type); /// <summary> /// Retrieves an existing <see cref="QualifiedMethod"/>, <see cref="MemberReference"/>, or <see cref="MethodInstantiation"/> /// record representing specified method in the metadata writer object model, or creates a new one. /// </summary> public abstract MetadataRecord HandleQualifiedMethod(Cts.MethodDesc method); /// <summary> /// Retrieves an existing <see cref="QualifiedField"> or a <see cref="MemberReference"/> record /// representing specified field in the metadata writer object model, or creates a new one. /// </summary> public abstract MetadataRecord HandleQualifiedField(Cts.FieldDesc field); /// <summary> /// Retrieves an existing <see cref="MethodSignature"/> record representing the specified signature /// in the metadata writer object model, or creates a new one. /// </summary> public abstract MethodSignature HandleMethodSignature(Cts.MethodSignature signature); } }
-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/SurrogateSelectorTests.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; namespace System.Runtime.Serialization.Formatters.Tests { public class SurrogateSelectorTests { [Fact] public void AddSurrogate_InvalidArguments_ThrowExceptions() { var s = new SurrogateSelector(); AssertExtensions.Throws<ArgumentNullException>("type", () => s.AddSurrogate(null, new StreamingContext(), new NonSerializablePairSurrogate())); AssertExtensions.Throws<ArgumentNullException>("surrogate", () => s.AddSurrogate(typeof(NonSerializablePair<int, string>), new StreamingContext(), null)); } [Fact] public void ChainSelector_InvalidArguments_ThrowExceptions() { var s1 = new SurrogateSelector(); AssertExtensions.Throws<ArgumentNullException>("selector", () => s1.ChainSelector(null)); Assert.Throws<SerializationException>(() => s1.ChainSelector(s1)); var s2 = new SurrogateSelector(); s2.ChainSelector(s1); AssertExtensions.Throws<ArgumentException>("selector", () => s1.ChainSelector(s2)); var s3 = new SurrogateSelector(); s3.ChainSelector(s2); AssertExtensions.Throws<ArgumentException>("selector", () => s1.ChainSelector(s3)); } [Fact] public void GetNextSelector_ReturnsCorrectSelector() { var s1 = new SurrogateSelector(); var s2 = new SurrogateSelector(); s2.ChainSelector(s1); Assert.Null(s1.GetNextSelector()); Assert.Same(s1, s2.GetNextSelector()); } [Fact] public void GetSurrogate_InvalidArguments_ThrowExceptions() { var s = new SurrogateSelector(); var c = new StreamingContext(); ISurrogateSelector selector; AssertExtensions.Throws<ArgumentNullException>("type", () => s.GetSurrogate(null, c, out selector)); } [Fact] public void GetSurrogate_ChainsToNextSelector() { var c = new StreamingContext(); var s1 = new SurrogateSelector(); var s2 = new SurrogateSelector(); s2.ChainSelector(s1); ISurrogateSelector selector; Assert.Null(s1.GetSurrogate(typeof(NonSerializablePair<int, string>), c, out selector)); Assert.Same(s1, selector); s1.AddSurrogate(typeof(NonSerializablePair<int, string>), c, new NonSerializablePairSurrogate()); Assert.NotNull(s1.GetSurrogate(typeof(NonSerializablePair<int, string>), c, out selector)); Assert.Same(s1, selector); Assert.NotNull(s2.GetSurrogate(typeof(NonSerializablePair<int, string>), c, out selector)); Assert.Same(s1, selector); s2.AddSurrogate(typeof(NonSerializablePair<int, string>), c, new NonSerializablePairSurrogate()); Assert.NotNull(s2.GetSurrogate(typeof(NonSerializablePair<int, string>), c, out selector)); Assert.Same(s2, selector); s2.RemoveSurrogate(typeof(NonSerializablePair<int, string>), c); Assert.NotNull(s2.GetSurrogate(typeof(NonSerializablePair<int, string>), c, out selector)); Assert.Same(s1, selector); s1.RemoveSurrogate(typeof(NonSerializablePair<int, string>), c); Assert.Null(s2.GetSurrogate(typeof(NonSerializablePair<int, string>), c, out selector)); Assert.Same(s1, selector); } [Fact] public void RemoveSurrogate_InvalidArguments_ThrowExceptions() { var s = new SurrogateSelector(); var c = new StreamingContext(); AssertExtensions.Throws<ArgumentNullException>("type", () => s.RemoveSurrogate(null, c)); s.RemoveSurrogate(typeof(string), c); // no exception even if removal fails } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Runtime.Serialization.Formatters.Tests { public class SurrogateSelectorTests { [Fact] public void AddSurrogate_InvalidArguments_ThrowExceptions() { var s = new SurrogateSelector(); AssertExtensions.Throws<ArgumentNullException>("type", () => s.AddSurrogate(null, new StreamingContext(), new NonSerializablePairSurrogate())); AssertExtensions.Throws<ArgumentNullException>("surrogate", () => s.AddSurrogate(typeof(NonSerializablePair<int, string>), new StreamingContext(), null)); } [Fact] public void ChainSelector_InvalidArguments_ThrowExceptions() { var s1 = new SurrogateSelector(); AssertExtensions.Throws<ArgumentNullException>("selector", () => s1.ChainSelector(null)); Assert.Throws<SerializationException>(() => s1.ChainSelector(s1)); var s2 = new SurrogateSelector(); s2.ChainSelector(s1); AssertExtensions.Throws<ArgumentException>("selector", () => s1.ChainSelector(s2)); var s3 = new SurrogateSelector(); s3.ChainSelector(s2); AssertExtensions.Throws<ArgumentException>("selector", () => s1.ChainSelector(s3)); } [Fact] public void GetNextSelector_ReturnsCorrectSelector() { var s1 = new SurrogateSelector(); var s2 = new SurrogateSelector(); s2.ChainSelector(s1); Assert.Null(s1.GetNextSelector()); Assert.Same(s1, s2.GetNextSelector()); } [Fact] public void GetSurrogate_InvalidArguments_ThrowExceptions() { var s = new SurrogateSelector(); var c = new StreamingContext(); ISurrogateSelector selector; AssertExtensions.Throws<ArgumentNullException>("type", () => s.GetSurrogate(null, c, out selector)); } [Fact] public void GetSurrogate_ChainsToNextSelector() { var c = new StreamingContext(); var s1 = new SurrogateSelector(); var s2 = new SurrogateSelector(); s2.ChainSelector(s1); ISurrogateSelector selector; Assert.Null(s1.GetSurrogate(typeof(NonSerializablePair<int, string>), c, out selector)); Assert.Same(s1, selector); s1.AddSurrogate(typeof(NonSerializablePair<int, string>), c, new NonSerializablePairSurrogate()); Assert.NotNull(s1.GetSurrogate(typeof(NonSerializablePair<int, string>), c, out selector)); Assert.Same(s1, selector); Assert.NotNull(s2.GetSurrogate(typeof(NonSerializablePair<int, string>), c, out selector)); Assert.Same(s1, selector); s2.AddSurrogate(typeof(NonSerializablePair<int, string>), c, new NonSerializablePairSurrogate()); Assert.NotNull(s2.GetSurrogate(typeof(NonSerializablePair<int, string>), c, out selector)); Assert.Same(s2, selector); s2.RemoveSurrogate(typeof(NonSerializablePair<int, string>), c); Assert.NotNull(s2.GetSurrogate(typeof(NonSerializablePair<int, string>), c, out selector)); Assert.Same(s1, selector); s1.RemoveSurrogate(typeof(NonSerializablePair<int, string>), c); Assert.Null(s2.GetSurrogate(typeof(NonSerializablePair<int, string>), c, out selector)); Assert.Same(s1, selector); } [Fact] public void RemoveSurrogate_InvalidArguments_ThrowExceptions() { var s = new SurrogateSelector(); var c = new StreamingContext(); AssertExtensions.Throws<ArgumentNullException>("type", () => s.RemoveSurrogate(null, c)); s.RemoveSurrogate(typeof(string), c); // no exception even if removal fails } } }
-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.Extensions.FileProviders.Abstractions/src/NotFoundFileInfo.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; using System.IO; namespace Microsoft.Extensions.FileProviders { /// <summary> /// Represents a non-existing file. /// </summary> public class NotFoundFileInfo : IFileInfo { /// <summary> /// Initializes an instance of <see cref="NotFoundFileInfo"/>. /// </summary> /// <param name="name">The name of the file that could not be found</param> public NotFoundFileInfo(string name) { Name = name; } /// <summary> /// Always false. /// </summary> public bool Exists => false; /// <summary> /// Always false. /// </summary> public bool IsDirectory => false; /// <summary> /// Returns <see cref="DateTimeOffset.MinValue"/>. /// </summary> public DateTimeOffset LastModified => DateTimeOffset.MinValue; /// <summary> /// Always equals -1. /// </summary> public long Length => -1; /// <inheritdoc /> public string Name { get; } /// <summary> /// Always null. /// </summary> public string? PhysicalPath => null; /// <summary> /// Always throws. A stream cannot be created for non-existing file. /// </summary> /// <exception cref="FileNotFoundException">Always thrown.</exception> /// <returns>Does not return</returns> [DoesNotReturn] public Stream CreateReadStream() { throw new FileNotFoundException(SR.Format(SR.FileNotExists, Name)); } } }
// 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; using System.IO; namespace Microsoft.Extensions.FileProviders { /// <summary> /// Represents a non-existing file. /// </summary> public class NotFoundFileInfo : IFileInfo { /// <summary> /// Initializes an instance of <see cref="NotFoundFileInfo"/>. /// </summary> /// <param name="name">The name of the file that could not be found</param> public NotFoundFileInfo(string name) { Name = name; } /// <summary> /// Always false. /// </summary> public bool Exists => false; /// <summary> /// Always false. /// </summary> public bool IsDirectory => false; /// <summary> /// Returns <see cref="DateTimeOffset.MinValue"/>. /// </summary> public DateTimeOffset LastModified => DateTimeOffset.MinValue; /// <summary> /// Always equals -1. /// </summary> public long Length => -1; /// <inheritdoc /> public string Name { get; } /// <summary> /// Always null. /// </summary> public string? PhysicalPath => null; /// <summary> /// Always throws. A stream cannot be created for non-existing file. /// </summary> /// <exception cref="FileNotFoundException">Always thrown.</exception> /// <returns>Does not return</returns> [DoesNotReturn] public Stream CreateReadStream() { throw new FileNotFoundException(SR.Format(SR.FileNotExists, Name)); } } }
-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.Http/src/System/Net/Http/HttpResponseMessage.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.Diagnostics.CodeAnalysis; using System.Net.Http.Headers; using System.Text; namespace System.Net.Http { public class HttpResponseMessage : IDisposable { private const HttpStatusCode DefaultStatusCode = HttpStatusCode.OK; private static Version DefaultResponseVersion => HttpVersion.Version11; private HttpStatusCode _statusCode; private HttpResponseHeaders? _headers; private HttpResponseHeaders? _trailingHeaders; private string? _reasonPhrase; private HttpRequestMessage? _requestMessage; private Version _version; private HttpContent? _content; private bool _disposed; public Version Version { get { return _version; } set { #if !PHONE ArgumentNullException.ThrowIfNull(value); #endif CheckDisposed(); _version = value; } } internal void SetVersionWithoutValidation(Version value) => _version = value; [AllowNull] public HttpContent Content { get { return _content ??= new EmptyContent(); } set { CheckDisposed(); if (NetEventSource.Log.IsEnabled()) { if (value == null) { NetEventSource.ContentNull(this); } else { NetEventSource.Associate(this, value); } } _content = value; } } public HttpStatusCode StatusCode { get { return _statusCode; } set { if (((int)value < 0) || ((int)value > 999)) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposed(); _statusCode = value; } } internal void SetStatusCodeWithoutValidation(HttpStatusCode value) => _statusCode = value; public string? ReasonPhrase { get { if (_reasonPhrase != null) { return _reasonPhrase; } // Provide a default if one was not set. return HttpStatusDescription.Get(StatusCode); } set { if ((value != null) && ContainsNewLineCharacter(value)) { throw new FormatException(SR.net_http_reasonphrase_format_error); } CheckDisposed(); _reasonPhrase = value; // It's OK to have a 'null' reason phrase. } } internal void SetReasonPhraseWithoutValidation(string value) => _reasonPhrase = value; public HttpResponseHeaders Headers => _headers ??= new HttpResponseHeaders(); public HttpResponseHeaders TrailingHeaders => _trailingHeaders ??= new HttpResponseHeaders(containsTrailingHeaders: true); /// <summary>Stores the supplied trailing headers into this instance.</summary> /// <remarks> /// In the common/desired case where response.TrailingHeaders isn't accessed until after the whole payload has been /// received, <see cref="_trailingHeaders" /> will still be null, and we can simply store the supplied instance into /// <see cref="_trailingHeaders" /> and assume ownership of the instance. In the uncommon case where it was accessed, /// we add all of the headers to the existing instance. /// </remarks> internal void StoreReceivedTrailingHeaders(HttpResponseHeaders headers) { Debug.Assert(headers.ContainsTrailingHeaders); if (_trailingHeaders is null) { _trailingHeaders = headers; } else { _trailingHeaders.AddHeaders(headers); } } public HttpRequestMessage? RequestMessage { get { return _requestMessage; } set { CheckDisposed(); if (value is not null && NetEventSource.Log.IsEnabled()) NetEventSource.Associate(this, value); _requestMessage = value; } } public bool IsSuccessStatusCode { get { return ((int)_statusCode >= 200) && ((int)_statusCode <= 299); } } public HttpResponseMessage() : this(DefaultStatusCode) { } public HttpResponseMessage(HttpStatusCode statusCode) { if (((int)statusCode < 0) || ((int)statusCode > 999)) { throw new ArgumentOutOfRangeException(nameof(statusCode)); } _statusCode = statusCode; _version = DefaultResponseVersion; } public HttpResponseMessage EnsureSuccessStatusCode() { if (!IsSuccessStatusCode) { throw new HttpRequestException( SR.Format( System.Globalization.CultureInfo.InvariantCulture, SR.net_http_message_not_success_statuscode, (int)_statusCode, ReasonPhrase), inner: null, _statusCode); } return this; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("StatusCode: "); sb.Append((int)_statusCode); sb.Append(", ReasonPhrase: '"); sb.Append(ReasonPhrase ?? "<null>"); sb.Append("', Version: "); sb.Append(_version); sb.Append(", Content: "); sb.Append(_content == null ? "<null>" : _content.GetType().ToString()); sb.AppendLine(", Headers:"); HeaderUtilities.DumpHeaders(sb, _headers, _content?.Headers); if (_trailingHeaders != null) { sb.AppendLine(", Trailing Headers:"); HeaderUtilities.DumpHeaders(sb, _trailingHeaders); } return sb.ToString(); } private bool ContainsNewLineCharacter(string value) { foreach (char character in value) { if ((character == HttpRuleParser.CR) || (character == HttpRuleParser.LF)) { return true; } } return false; } #region IDisposable Members protected virtual void Dispose(bool disposing) { // The reason for this type to implement IDisposable is that it contains instances of types that implement // IDisposable (content). if (disposing && !_disposed) { _disposed = true; if (_content != null) { _content.Dispose(); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(this.GetType().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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Net.Http.Headers; using System.Text; namespace System.Net.Http { public class HttpResponseMessage : IDisposable { private const HttpStatusCode DefaultStatusCode = HttpStatusCode.OK; private static Version DefaultResponseVersion => HttpVersion.Version11; private HttpStatusCode _statusCode; private HttpResponseHeaders? _headers; private HttpResponseHeaders? _trailingHeaders; private string? _reasonPhrase; private HttpRequestMessage? _requestMessage; private Version _version; private HttpContent? _content; private bool _disposed; public Version Version { get { return _version; } set { #if !PHONE ArgumentNullException.ThrowIfNull(value); #endif CheckDisposed(); _version = value; } } internal void SetVersionWithoutValidation(Version value) => _version = value; [AllowNull] public HttpContent Content { get { return _content ??= new EmptyContent(); } set { CheckDisposed(); if (NetEventSource.Log.IsEnabled()) { if (value == null) { NetEventSource.ContentNull(this); } else { NetEventSource.Associate(this, value); } } _content = value; } } public HttpStatusCode StatusCode { get { return _statusCode; } set { if (((int)value < 0) || ((int)value > 999)) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposed(); _statusCode = value; } } internal void SetStatusCodeWithoutValidation(HttpStatusCode value) => _statusCode = value; public string? ReasonPhrase { get { if (_reasonPhrase != null) { return _reasonPhrase; } // Provide a default if one was not set. return HttpStatusDescription.Get(StatusCode); } set { if ((value != null) && ContainsNewLineCharacter(value)) { throw new FormatException(SR.net_http_reasonphrase_format_error); } CheckDisposed(); _reasonPhrase = value; // It's OK to have a 'null' reason phrase. } } internal void SetReasonPhraseWithoutValidation(string value) => _reasonPhrase = value; public HttpResponseHeaders Headers => _headers ??= new HttpResponseHeaders(); public HttpResponseHeaders TrailingHeaders => _trailingHeaders ??= new HttpResponseHeaders(containsTrailingHeaders: true); /// <summary>Stores the supplied trailing headers into this instance.</summary> /// <remarks> /// In the common/desired case where response.TrailingHeaders isn't accessed until after the whole payload has been /// received, <see cref="_trailingHeaders" /> will still be null, and we can simply store the supplied instance into /// <see cref="_trailingHeaders" /> and assume ownership of the instance. In the uncommon case where it was accessed, /// we add all of the headers to the existing instance. /// </remarks> internal void StoreReceivedTrailingHeaders(HttpResponseHeaders headers) { Debug.Assert(headers.ContainsTrailingHeaders); if (_trailingHeaders is null) { _trailingHeaders = headers; } else { _trailingHeaders.AddHeaders(headers); } } public HttpRequestMessage? RequestMessage { get { return _requestMessage; } set { CheckDisposed(); if (value is not null && NetEventSource.Log.IsEnabled()) NetEventSource.Associate(this, value); _requestMessage = value; } } public bool IsSuccessStatusCode { get { return ((int)_statusCode >= 200) && ((int)_statusCode <= 299); } } public HttpResponseMessage() : this(DefaultStatusCode) { } public HttpResponseMessage(HttpStatusCode statusCode) { if (((int)statusCode < 0) || ((int)statusCode > 999)) { throw new ArgumentOutOfRangeException(nameof(statusCode)); } _statusCode = statusCode; _version = DefaultResponseVersion; } public HttpResponseMessage EnsureSuccessStatusCode() { if (!IsSuccessStatusCode) { throw new HttpRequestException( SR.Format( System.Globalization.CultureInfo.InvariantCulture, SR.net_http_message_not_success_statuscode, (int)_statusCode, ReasonPhrase), inner: null, _statusCode); } return this; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("StatusCode: "); sb.Append((int)_statusCode); sb.Append(", ReasonPhrase: '"); sb.Append(ReasonPhrase ?? "<null>"); sb.Append("', Version: "); sb.Append(_version); sb.Append(", Content: "); sb.Append(_content == null ? "<null>" : _content.GetType().ToString()); sb.AppendLine(", Headers:"); HeaderUtilities.DumpHeaders(sb, _headers, _content?.Headers); if (_trailingHeaders != null) { sb.AppendLine(", Trailing Headers:"); HeaderUtilities.DumpHeaders(sb, _trailingHeaders); } return sb.ToString(); } private bool ContainsNewLineCharacter(string value) { foreach (char character in value) { if ((character == HttpRuleParser.CR) || (character == HttpRuleParser.LF)) { return true; } } return false; } #region IDisposable Members protected virtual void Dispose(bool disposing) { // The reason for this type to implement IDisposable is that it contains instances of types that implement // IDisposable (content). if (disposing && !_disposed) { _disposed = true; if (_content != null) { _content.Dispose(); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(this.GetType().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/libraries/System.Data.Common/tests/System/Data/DataTableTest5.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Copyright (c) 2007 Novell, Inc // // 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.IO; using System.Xml; using System.Xml.Serialization; using Xunit; namespace System.Data.Tests { public class DataTableTest5 : IDisposable { private string _tempFile; private DataSet _dataSet; private DataTable _dummyTable; private DataTable _parentTable1; private DataTable _childTable; private DataTable _secondChildTable; public DataTableTest5() { _tempFile = Path.GetTempFileName(); } public void Dispose() { if (_tempFile != null) File.Delete(_tempFile); } private void WriteXmlSerializable(Stream s, DataTable dt) { XmlWriterSettings ws = new XmlWriterSettings(); using (XmlWriter xw = XmlWriter.Create(s, ws)) { IXmlSerializable idt = dt; xw.WriteStartElement("start"); idt.WriteXml(xw); xw.WriteEndElement(); xw.Close(); } } private void ReadXmlSerializable(Stream s, DataTable dt) { using (XmlReader xr = XmlReader.Create(s)) { ReadXmlSerializable(dt, xr); } } private static void ReadXmlSerializable(DataTable dt, XmlReader xr) { XmlSerializer serializer = new XmlSerializer(dt.GetType()); IXmlSerializable idt = dt; idt.ReadXml(xr); xr.Close(); } private void ReadXmlSerializable(string fileName, DataTable dt) { using (XmlReader xr = XmlReader.Create(fileName)) { ReadXmlSerializable(dt, xr); } } private void MakeParentTable1() { // Create a new Table _parentTable1 = new DataTable("ParentTable"); _dataSet = new DataSet("XmlDataSet"); DataColumn column; DataRow row; // Create new DataColumn, set DataType, // ColumnName and add to Table. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "id"; column.Unique = true; // Add the Column to the DataColumnCollection. _parentTable1.Columns.Add(column); // Create second column column = new DataColumn(); column.DataType = typeof(string); column.ColumnName = "ParentItem"; column.AutoIncrement = false; column.Caption = "ParentItem"; column.Unique = false; // Add the column to the table _parentTable1.Columns.Add(column); // Create third column. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "DepartmentID"; column.Caption = "DepartmentID"; // Add the column to the table. _parentTable1.Columns.Add(column); // Make the ID column the primary key column. DataColumn[] PrimaryKeyColumns = new DataColumn[2]; PrimaryKeyColumns[0] = _parentTable1.Columns["id"]; PrimaryKeyColumns[1] = _parentTable1.Columns["DepartmentID"]; _parentTable1.PrimaryKey = PrimaryKeyColumns; _dataSet.Tables.Add(_parentTable1); // Create three new DataRow objects and add // them to the DataTable for (int i = 0; i <= 2; i++) { row = _parentTable1.NewRow(); row["id"] = i + 1; row["ParentItem"] = "ParentItem " + (i + 1); row["DepartmentID"] = i + 1; _parentTable1.Rows.Add(row); } } private void MakeDummyTable() { // Create a new Table _dataSet = new DataSet(); _dummyTable = new DataTable("DummyTable"); DataColumn column; DataRow row; // Create new DataColumn, set DataType, // ColumnName and add to Table. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "id"; column.Unique = true; // Add the Column to the DataColumnCollection. _dummyTable.Columns.Add(column); // Create second column column = new DataColumn(); column.DataType = typeof(string); column.ColumnName = "DummyItem"; column.AutoIncrement = false; column.Caption = "DummyItem"; column.Unique = false; // Add the column to the table _dummyTable.Columns.Add(column); _dataSet.Tables.Add(_dummyTable); // Create three new DataRow objects and add // them to the DataTable for (int i = 0; i <= 2; i++) { row = _dummyTable.NewRow(); row["id"] = i + 1; row["DummyItem"] = "DummyItem " + (i + 1); _dummyTable.Rows.Add(row); } DataRow row1 = _dummyTable.Rows[1]; _dummyTable.AcceptChanges(); row1.BeginEdit(); row1[1] = "Changed_DummyItem " + 2; row1.EndEdit(); } private void MakeChildTable() { // Create a new Table _childTable = new DataTable("ChildTable"); DataColumn column; DataRow row; // Create first column and add to the DataTable. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "ChildID"; column.AutoIncrement = true; column.Caption = "ID"; column.Unique = true; // Add the column to the DataColumnCollection _childTable.Columns.Add(column); // Create second column column = new DataColumn(); column.DataType = typeof(string); column.ColumnName = "ChildItem"; column.AutoIncrement = false; column.Caption = "ChildItem"; column.Unique = false; _childTable.Columns.Add(column); //Create third column column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "ParentID"; column.AutoIncrement = false; column.Caption = "ParentID"; column.Unique = false; _childTable.Columns.Add(column); _dataSet.Tables.Add(_childTable); // Create three sets of DataRow objects, // five rows each, and add to DataTable. for (int i = 0; i <= 1; i++) { row = _childTable.NewRow(); row["childID"] = i + 1; row["ChildItem"] = "ChildItem " + (i + 1); row["ParentID"] = 1; _childTable.Rows.Add(row); } for (int i = 0; i <= 1; i++) { row = _childTable.NewRow(); row["childID"] = i + 5; row["ChildItem"] = "ChildItem " + (i + 1); row["ParentID"] = 2; _childTable.Rows.Add(row); } for (int i = 0; i <= 1; i++) { row = _childTable.NewRow(); row["childID"] = i + 10; row["ChildItem"] = "ChildItem " + (i + 1); row["ParentID"] = 3; _childTable.Rows.Add(row); } } private void MakeSecondChildTable() { // Create a new Table _secondChildTable = new DataTable("SecondChildTable"); DataColumn column; DataRow row; // Create first column and add to the DataTable. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "ChildID"; column.AutoIncrement = true; column.Caption = "ID"; column.ReadOnly = true; column.Unique = true; // Add the column to the DataColumnCollection. _secondChildTable.Columns.Add(column); // Create second column. column = new DataColumn(); column.DataType = typeof(string); column.ColumnName = "ChildItem"; column.AutoIncrement = false; column.Caption = "ChildItem"; column.ReadOnly = false; column.Unique = false; _secondChildTable.Columns.Add(column); //Create third column. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "ParentID"; column.AutoIncrement = false; column.Caption = "ParentID"; column.ReadOnly = false; column.Unique = false; _secondChildTable.Columns.Add(column); //Create fourth column. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "DepartmentID"; column.Caption = "DepartmentID"; column.Unique = false; _secondChildTable.Columns.Add(column); _dataSet.Tables.Add(_secondChildTable); // Create three sets of DataRow objects, // five rows each, and add to DataTable. for (int i = 0; i <= 1; i++) { row = _secondChildTable.NewRow(); row["childID"] = i + 1; row["ChildItem"] = "SecondChildItem " + (i + 1); row["ParentID"] = 1; row["DepartmentID"] = 1; _secondChildTable.Rows.Add(row); } for (int i = 0; i <= 1; i++) { row = _secondChildTable.NewRow(); row["childID"] = i + 5; row["ChildItem"] = "SecondChildItem " + (i + 1); row["ParentID"] = 2; row["DepartmentID"] = 2; _secondChildTable.Rows.Add(row); } for (int i = 0; i <= 1; i++) { row = _secondChildTable.NewRow(); row["childID"] = i + 10; row["ChildItem"] = "SecondChildItem " + (i + 1); row["ParentID"] = 3; row["DepartmentID"] = 3; _secondChildTable.Rows.Add(row); } } private void MakeDataRelation() { DataColumn parentColumn = _dataSet.Tables["ParentTable"].Columns["id"]; DataColumn childColumn = _dataSet.Tables["ChildTable"].Columns["ParentID"]; DataRelation relation = new DataRelation("ParentChild_Relation1", parentColumn, childColumn); _dataSet.Tables["ChildTable"].ParentRelations.Add(relation); DataColumn[] parentColumn1 = new DataColumn[2]; DataColumn[] childColumn1 = new DataColumn[2]; parentColumn1[0] = _dataSet.Tables["ParentTable"].Columns["id"]; parentColumn1[1] = _dataSet.Tables["ParentTable"].Columns["DepartmentID"]; childColumn1[0] = _dataSet.Tables["SecondChildTable"].Columns["ParentID"]; childColumn1[1] = _dataSet.Tables["SecondChildTable"].Columns["DepartmentID"]; DataRelation secondRelation = new DataRelation("ParentChild_Relation2", parentColumn1, childColumn1); _dataSet.Tables["SecondChildTable"].ParentRelations.Add(secondRelation); } private void MakeDataRelation(DataTable dt) { DataColumn parentColumn = dt.Columns["id"]; DataColumn childColumn = _dataSet.Tables["ChildTable"].Columns["ParentID"]; DataRelation relation = new DataRelation("ParentChild_Relation1", parentColumn, childColumn); _dataSet.Tables["ChildTable"].ParentRelations.Add(relation); DataColumn[] parentColumn1 = new DataColumn[2]; DataColumn[] childColumn1 = new DataColumn[2]; parentColumn1[0] = dt.Columns["id"]; parentColumn1[1] = dt.Columns["DepartmentID"]; childColumn1[0] = _dataSet.Tables["SecondChildTable"].Columns["ParentID"]; childColumn1[1] = _dataSet.Tables["SecondChildTable"].Columns["DepartmentID"]; DataRelation secondRelation = new DataRelation("ParentChild_Relation2", parentColumn1, childColumn1); _dataSet.Tables["SecondChildTable"].ParentRelations.Add(secondRelation); } //Test properties of a table which does not belongs to a DataSet private void VerifyTableSchema(DataTable table, string tableName, DataSet ds) { //Test Schema //Check Properties of Table Assert.Equal(string.Empty, table.Namespace); Assert.Equal(ds, table.DataSet); Assert.Equal(3, table.Columns.Count); Assert.False(table.CaseSensitive); Assert.Equal(tableName, table.TableName); Assert.Equal(2, table.Constraints.Count); Assert.Equal(string.Empty, table.Prefix); Assert.Equal(2, table.Constraints.Count); Assert.Equal(typeof(UniqueConstraint), table.Constraints[0].GetType()); Assert.Equal(typeof(UniqueConstraint), table.Constraints[1].GetType()); Assert.Equal(2, table.PrimaryKey.Length); Assert.Equal("id", table.PrimaryKey[0].ToString()); Assert.Equal("DepartmentID", table.PrimaryKey[1].ToString()); Assert.Equal(0, table.ParentRelations.Count); Assert.Equal(0, table.ChildRelations.Count); //Check properties of each column //First Column DataColumn col = table.Columns[0]; Assert.False(col.AllowDBNull); Assert.False(col.AutoIncrement); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("id", col.Caption); Assert.Equal("id", col.ColumnName); Assert.Equal(typeof(int), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.False(col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(0, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ParentTable", col.Table.ToString()); Assert.True(col.Unique); //Second Column col = table.Columns[1]; Assert.True(col.AllowDBNull); Assert.False(col.AutoIncrement); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("ParentItem", col.Caption); Assert.Equal("ParentItem", col.ColumnName); Assert.Equal(typeof(string), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.False(col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(1, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ParentTable", col.Table.ToString()); Assert.False(col.Unique); //Third Column col = table.Columns[2]; Assert.False(col.AllowDBNull); Assert.False(col.AutoIncrement); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("DepartmentID", col.Caption); Assert.Equal("DepartmentID", col.ColumnName); Assert.Equal(typeof(int), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.False(col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(2, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ParentTable", col.Table.ToString()); Assert.False(col.Unique); //Test the Xml Assert.Equal(3, table.Rows.Count); //Test values of each row DataRow row = table.Rows[0]; Assert.Equal(1, row["id"]); Assert.Equal("ParentItem 1", row["ParentItem"]); Assert.Equal(1, row["DepartmentID"]); row = table.Rows[1]; Assert.Equal(2, row["id"]); Assert.Equal("ParentItem 2", row["ParentItem"]); Assert.Equal(2, row["DepartmentID"]); row = table.Rows[2]; Assert.Equal(3, row["id"]); Assert.Equal("ParentItem 3", row["ParentItem"]); Assert.Equal(3, row["DepartmentID"]); } [Fact] public void XmlTest1() { //Make a table without any relations MakeParentTable1(); _dataSet.Tables.Remove(_parentTable1); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table = new DataTable("ParentTable"); //Read the Xml and the Schema into a table which does not belongs to any DataSet ReadXmlSerializable(_tempFile, table); VerifyTableSchema(table, _parentTable1.TableName, null);//parentTable1.DataSet); } [Fact] public void XmlTest2() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table = new DataTable("ParentTable"); DataSet ds = new DataSet("XmlDataSet"); ds.Tables.Add(table); //Read the Xml and the Schema into a table which already belongs to a DataSet //and the table name matches with the table in the source XML ReadXmlSerializable(_tempFile, table); VerifyTableSchema(table, _parentTable1.TableName, ds); } [Fact] public void XmlTest3() { //Create a parent table and create child tables MakeParentTable1(); MakeChildTable(); MakeSecondChildTable(); //Relate the parent and the children MakeDataRelation(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table = new DataTable(); ReadXmlSerializable(_tempFile, table); VerifyTableSchema(table, _parentTable1.TableName, null); } [Fact] public void XmlTest4() { //Create a parent table and create child tables MakeParentTable1(); MakeChildTable(); MakeSecondChildTable(); //Relate the parent and the children MakeDataRelation(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { //WriteXml on any of the children WriteXmlSerializable(stream, _childTable); } DataTable table = new DataTable(); ReadXmlSerializable(_tempFile, table); //Test Schema //Check Properties of Table Assert.Equal(string.Empty, table.Namespace); Assert.Null(table.DataSet); Assert.Equal(3, table.Columns.Count); Assert.False(table.CaseSensitive); Assert.Equal("ChildTable", table.TableName); Assert.Equal(string.Empty, table.Prefix); Assert.Equal(1, table.Constraints.Count); Assert.Equal("Constraint1", table.Constraints[0].ToString()); Assert.Equal(typeof(UniqueConstraint), table.Constraints[0].GetType()); Assert.Equal(0, table.PrimaryKey.Length); Assert.Equal(0, table.ParentRelations.Count); Assert.Equal(0, table.ChildRelations.Count); //Check properties of each column //First Column DataColumn col = table.Columns[0]; Assert.True(col.AllowDBNull); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("ChildID", col.ColumnName); Assert.Equal(typeof(int), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.False(col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(0, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ChildTable", col.Table.ToString()); Assert.True(col.Unique); //Second Column col = table.Columns[1]; Assert.True(col.AllowDBNull); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("ChildItem", col.Caption); Assert.Equal("ChildItem", col.ColumnName); Assert.Equal(typeof(string), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.False(col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(1, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ChildTable", col.Table.ToString()); Assert.False(col.Unique); //Third Column col = table.Columns[2]; Assert.True(col.AllowDBNull); Assert.False(col.AutoIncrement); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("ParentID", col.Caption); Assert.Equal("ParentID", col.ColumnName); Assert.Equal(typeof(int), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.False(col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(2, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ChildTable", col.Table.ToString()); Assert.False(col.Unique); //Test the Xml Assert.Equal(6, table.Rows.Count); //Test values of each row DataRow row = table.Rows[0]; Assert.Equal(1, row["ChildID"]); Assert.Equal("ChildItem 1", row["ChildItem"]); Assert.Equal(1, row["ParentID"]); row = table.Rows[1]; Assert.Equal(2, row["ChildID"]); Assert.Equal("ChildItem 2", row["ChildItem"]); Assert.Equal(1, row["ParentID"]); row = table.Rows[2]; Assert.Equal(5, row["ChildID"]); Assert.Equal("ChildItem 1", row["ChildItem"]); Assert.Equal(2, row["ParentID"]); row = table.Rows[3]; Assert.Equal(6, row["ChildID"]); Assert.Equal("ChildItem 2", row["ChildItem"]); Assert.Equal(2, row["ParentID"]); row = table.Rows[4]; Assert.Equal(10, row["ChildID"]); Assert.Equal("ChildItem 1", row["ChildItem"]); Assert.Equal(3, row["ParentID"]); row = table.Rows[5]; Assert.Equal(11, row["ChildID"]); Assert.Equal("ChildItem 2", row["ChildItem"]); Assert.Equal(3, row["ParentID"]); } [Fact] public void XmlTest5() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); stream.Close(); } DataTable table = new DataTable("ParentTable"); DataSet dataSet = new DataSet("XmlDataSet"); dataSet.Tables.Add(table); table.Columns.Add(new DataColumn("id", typeof(string))); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(1, table.Columns.Count); Assert.Equal(typeof(string), table.Columns[0].DataType); Assert.NotNull(table.DataSet); //Check Rows DataRow row = table.Rows[0]; Assert.Equal("1", row[0]); row = table.Rows[1]; Assert.Equal("2", row[0]); row = table.Rows[2]; Assert.Equal("3", row[0]); } [Fact] public void XmlTest6() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); stream.Close(); } //Create a target table which has nomatching column(s) names DataTable table = new DataTable("ParentTable"); DataSet dataSet = new DataSet("XmlDataSet"); dataSet.Tables.Add(table); table.Columns.Add(new DataColumn("sid", typeof(string))); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { // ReadXml does not read anything as the column // names are not matching ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(1, table.Columns.Count); Assert.Equal("sid", table.Columns[0].ColumnName); Assert.Equal(typeof(string), table.Columns[0].DataType); Assert.NotNull(table.DataSet); } [Fact] public void XmlTest7() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); stream.Close(); } //Create a target table which has matching // column(s) name and an extra column DataTable table = new DataTable("ParentTable"); table.Columns.Add(new DataColumn("id", typeof(int))); table.Columns.Add(new DataColumn("ParentItem", typeof(string))); table.Columns.Add(new DataColumn("DepartmentID", typeof(int))); table.Columns.Add(new DataColumn("DummyColumn", typeof(string))); DataSet dataSet = new DataSet("XmlDataSet"); dataSet.Tables.Add(table); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(4, table.Columns.Count); Assert.NotNull(table.DataSet); //Check the Columns Assert.Equal("id", table.Columns[0].ColumnName); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal("ParentItem", table.Columns[1].ColumnName); Assert.Equal(typeof(string), table.Columns[1].DataType); Assert.Equal("DepartmentID", table.Columns[2].ColumnName); Assert.Equal(typeof(int), table.Columns[2].DataType); Assert.Equal("DummyColumn", table.Columns[3].ColumnName); Assert.Equal(typeof(string), table.Columns[3].DataType); //Check the rows DataRow row = table.Rows[0]; Assert.Equal(1, row["id"]); Assert.Equal("ParentItem 1", row["ParentItem"]); Assert.Equal(1, row["DepartmentID"]); row = table.Rows[1]; Assert.Equal(2, row["id"]); Assert.Equal("ParentItem 2", row["ParentItem"]); Assert.Equal(2, row["DepartmentID"]); row = table.Rows[2]; Assert.Equal(3, row["id"]); Assert.Equal("ParentItem 3", row["ParentItem"]); Assert.Equal(3, row["DepartmentID"]); } [Fact] public void XmlTest8() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table = new DataTable("ParentTable"); DataSet dataSet = new DataSet("XmlDataSet"); dataSet.Tables.Add(table); table.Columns.Add(new DataColumn("id", typeof(int))); table.Columns.Add(new DataColumn("DepartmentID", typeof(int))); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(2, table.Columns.Count); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal(typeof(int), table.Columns[1].DataType); Assert.NotNull(table.DataSet); //Check rows DataRow row = table.Rows[0]; Assert.Equal(1, row[0]); Assert.Equal(1, row[1]); row = table.Rows[1]; Assert.Equal(2, row[0]); Assert.Equal(2, row[1]); row = table.Rows[2]; Assert.Equal(3, row[0]); Assert.Equal(3, row[1]); } [Fact] public void XmlTest9() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataSet ds = new DataSet(); DataTable table = new DataTable("ParentTable"); table.Columns.Add(new DataColumn("id", typeof(int))); ds.Tables.Add(table); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(1, table.Columns.Count); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal("System.Data.DataSet", table.DataSet.ToString()); Assert.Equal("NewDataSet", table.DataSet.DataSetName); //Check the rows DataRow row = table.Rows[0]; Assert.Equal(1, row[0]); row = table.Rows[1]; Assert.Equal(2, row[0]); row = table.Rows[2]; Assert.Equal(3, row[0]); } [Fact] public void XmlTest10() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataSet ds = new DataSet(); DataTable table = new DataTable("ParentTable"); table.Columns.Add(new DataColumn("id", typeof(int))); table.Columns.Add(new DataColumn("DepartmentID", typeof(string))); ds.Tables.Add(table); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal("NewDataSet", table.DataSet.DataSetName); Assert.Equal(3, table.Rows.Count); Assert.Equal(2, table.Columns.Count); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal(typeof(string), table.Columns[1].DataType); //Check rows DataRow row = table.Rows[0]; Assert.Equal(1, row[0]); Assert.Equal("1", row[1]); row = table.Rows[1]; Assert.Equal(2, row[0]); Assert.Equal("2", row[1]); row = table.Rows[2]; Assert.Equal(3, row[0]); Assert.Equal("3", row[1]); } [Fact] public void XmlTest11() { MakeDummyTable(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _dummyTable); } //Create a table and set the table name DataTable table = new DataTable("DummyTable"); //define the table schame partially table.Columns.Add(new DataColumn("DummyItem", typeof(string))); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Null(table.DataSet); Assert.Equal(1, table.Columns.Count); Assert.Equal(typeof(string), table.Columns[0].DataType); Assert.Equal(3, table.Rows.Count); //Check Rows DataRow row = table.Rows[0]; Assert.Equal("DummyItem 1", row[0]); Assert.Equal(DataRowState.Unchanged, row.RowState); row = table.Rows[1]; Assert.Equal("Changed_DummyItem 2", row[0]); Assert.Equal(DataRowState.Modified, row.RowState); row = table.Rows[2]; Assert.Equal("DummyItem 3", row[0]); Assert.Equal(DataRowState.Unchanged, row.RowState); } [Fact] public void XmlTest14() { MakeParentTable1(); MakeChildTable(); MakeSecondChildTable(); MakeDataRelation(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table1 = new DataTable("ParentTable"); table1.Columns.Add(new DataColumn(_parentTable1.Columns[0].ColumnName, typeof(int))); table1.Columns.Add(new DataColumn(_parentTable1.Columns[1].ColumnName, typeof(string))); table1.Columns.Add(new DataColumn(_parentTable1.Columns[2].ColumnName, typeof(int))); ReadXmlSerializable(_tempFile, table1); Assert.Null(table1.DataSet); Assert.Equal("ParentTable", table1.TableName); Assert.Equal(3, table1.Columns.Count); Assert.Equal(typeof(int), table1.Columns[0].DataType); Assert.Equal(typeof(string), table1.Columns[1].DataType); Assert.Equal(typeof(int), table1.Columns[2].DataType); Assert.Equal(0, table1.ChildRelations.Count); Assert.Equal(3, table1.Rows.Count); //Check the row DataRow row = table1.Rows[0]; Assert.Equal(1, row[0]); Assert.Equal("ParentItem 1", row[1]); Assert.Equal(1, row[2]); row = table1.Rows[1]; Assert.Equal(2, row[0]); Assert.Equal("ParentItem 2", row[1]); Assert.Equal(2, row[2]); row = table1.Rows[2]; Assert.Equal(3, row[0]); Assert.Equal("ParentItem 3", row[1]); Assert.Equal(3, row[2]); } [Fact] public void XmlTest15() { MakeDummyTable(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _dummyTable); } Assert.Equal(3, _dummyTable.Rows.Count); DataSet dataSet = new DataSet("HelloWorldDataSet"); DataTable table = new DataTable("DummyTable"); table.Columns.Add(new DataColumn("DummyItem", typeof(string))); dataSet.Tables.Add(table); //Call ReadXml on a table which belong to a DataSet ReadXmlSerializable(_tempFile, table); Assert.Equal("HelloWorldDataSet", table.DataSet.DataSetName); Assert.Equal(1, table.Columns.Count); Assert.Equal(typeof(string), table.Columns[0].DataType); Assert.Equal(3, table.Rows.Count); //Check Rows DataRow row = table.Rows[0]; Assert.Equal("DummyItem 1", row[0]); Assert.Equal(DataRowState.Unchanged, row.RowState); row = table.Rows[1]; Assert.Equal("Changed_DummyItem 2", row[0]); Assert.Equal(DataRowState.Modified, row.RowState); row = table.Rows[2]; Assert.Equal("DummyItem 3", row[0]); Assert.Equal(DataRowState.Unchanged, row.RowState); } [Fact] public void XmlTest16() { DataSet ds = new DataSet(); DataTable parent = new DataTable("Parent"); parent.Columns.Add(new DataColumn("col1", typeof(int))); parent.Columns.Add(new DataColumn("col2", typeof(string))); parent.Columns[0].Unique = true; DataTable child1 = new DataTable("Child1"); child1.Columns.Add(new DataColumn("col3", typeof(int))); child1.Columns.Add(new DataColumn("col4", typeof(string))); child1.Columns.Add(new DataColumn("col5", typeof(int))); child1.Columns[2].Unique = true; DataTable child2 = new DataTable("Child2"); child2.Columns.Add(new DataColumn("col6", typeof(int))); child2.Columns.Add(new DataColumn("col7")); parent.Rows.Add(new object[] { 1, "P_" }); parent.Rows.Add(new object[] { 2, "P_" }); child1.Rows.Add(new object[] { 1, "C1_", 3 }); child1.Rows.Add(new object[] { 1, "C1_", 4 }); child1.Rows.Add(new object[] { 2, "C1_", 5 }); child1.Rows.Add(new object[] { 2, "C1_", 6 }); child2.Rows.Add(new object[] { 3, "C2_" }); child2.Rows.Add(new object[] { 3, "C2_" }); child2.Rows.Add(new object[] { 4, "C2_" }); child2.Rows.Add(new object[] { 4, "C2_" }); child2.Rows.Add(new object[] { 5, "C2_" }); child2.Rows.Add(new object[] { 5, "C2_" }); child2.Rows.Add(new object[] { 6, "C2_" }); child2.Rows.Add(new object[] { 6, "C2_" }); ds.Tables.Add(parent); ds.Tables.Add(child1); ds.Tables.Add(child2); DataRelation relation = new DataRelation("Relation1", parent.Columns[0], child1.Columns[0]); parent.ChildRelations.Add(relation); relation = new DataRelation("Relation2", child1.Columns[2], child2.Columns[0]); child1.ChildRelations.Add(relation); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, parent); } DataTable table = new DataTable(); ReadXmlSerializable(_tempFile, table); Assert.Equal("Parent", table.TableName); Assert.Equal(2, table.Columns.Count); Assert.Equal(2, table.Rows.Count); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal(typeof(string), table.Columns[1].DataType); Assert.Equal(1, table.Constraints.Count); Assert.Equal(typeof(UniqueConstraint), table.Constraints[0].GetType()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Copyright (c) 2007 Novell, Inc // // 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.IO; using System.Xml; using System.Xml.Serialization; using Xunit; namespace System.Data.Tests { public class DataTableTest5 : IDisposable { private string _tempFile; private DataSet _dataSet; private DataTable _dummyTable; private DataTable _parentTable1; private DataTable _childTable; private DataTable _secondChildTable; public DataTableTest5() { _tempFile = Path.GetTempFileName(); } public void Dispose() { if (_tempFile != null) File.Delete(_tempFile); } private void WriteXmlSerializable(Stream s, DataTable dt) { XmlWriterSettings ws = new XmlWriterSettings(); using (XmlWriter xw = XmlWriter.Create(s, ws)) { IXmlSerializable idt = dt; xw.WriteStartElement("start"); idt.WriteXml(xw); xw.WriteEndElement(); xw.Close(); } } private void ReadXmlSerializable(Stream s, DataTable dt) { using (XmlReader xr = XmlReader.Create(s)) { ReadXmlSerializable(dt, xr); } } private static void ReadXmlSerializable(DataTable dt, XmlReader xr) { XmlSerializer serializer = new XmlSerializer(dt.GetType()); IXmlSerializable idt = dt; idt.ReadXml(xr); xr.Close(); } private void ReadXmlSerializable(string fileName, DataTable dt) { using (XmlReader xr = XmlReader.Create(fileName)) { ReadXmlSerializable(dt, xr); } } private void MakeParentTable1() { // Create a new Table _parentTable1 = new DataTable("ParentTable"); _dataSet = new DataSet("XmlDataSet"); DataColumn column; DataRow row; // Create new DataColumn, set DataType, // ColumnName and add to Table. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "id"; column.Unique = true; // Add the Column to the DataColumnCollection. _parentTable1.Columns.Add(column); // Create second column column = new DataColumn(); column.DataType = typeof(string); column.ColumnName = "ParentItem"; column.AutoIncrement = false; column.Caption = "ParentItem"; column.Unique = false; // Add the column to the table _parentTable1.Columns.Add(column); // Create third column. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "DepartmentID"; column.Caption = "DepartmentID"; // Add the column to the table. _parentTable1.Columns.Add(column); // Make the ID column the primary key column. DataColumn[] PrimaryKeyColumns = new DataColumn[2]; PrimaryKeyColumns[0] = _parentTable1.Columns["id"]; PrimaryKeyColumns[1] = _parentTable1.Columns["DepartmentID"]; _parentTable1.PrimaryKey = PrimaryKeyColumns; _dataSet.Tables.Add(_parentTable1); // Create three new DataRow objects and add // them to the DataTable for (int i = 0; i <= 2; i++) { row = _parentTable1.NewRow(); row["id"] = i + 1; row["ParentItem"] = "ParentItem " + (i + 1); row["DepartmentID"] = i + 1; _parentTable1.Rows.Add(row); } } private void MakeDummyTable() { // Create a new Table _dataSet = new DataSet(); _dummyTable = new DataTable("DummyTable"); DataColumn column; DataRow row; // Create new DataColumn, set DataType, // ColumnName and add to Table. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "id"; column.Unique = true; // Add the Column to the DataColumnCollection. _dummyTable.Columns.Add(column); // Create second column column = new DataColumn(); column.DataType = typeof(string); column.ColumnName = "DummyItem"; column.AutoIncrement = false; column.Caption = "DummyItem"; column.Unique = false; // Add the column to the table _dummyTable.Columns.Add(column); _dataSet.Tables.Add(_dummyTable); // Create three new DataRow objects and add // them to the DataTable for (int i = 0; i <= 2; i++) { row = _dummyTable.NewRow(); row["id"] = i + 1; row["DummyItem"] = "DummyItem " + (i + 1); _dummyTable.Rows.Add(row); } DataRow row1 = _dummyTable.Rows[1]; _dummyTable.AcceptChanges(); row1.BeginEdit(); row1[1] = "Changed_DummyItem " + 2; row1.EndEdit(); } private void MakeChildTable() { // Create a new Table _childTable = new DataTable("ChildTable"); DataColumn column; DataRow row; // Create first column and add to the DataTable. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "ChildID"; column.AutoIncrement = true; column.Caption = "ID"; column.Unique = true; // Add the column to the DataColumnCollection _childTable.Columns.Add(column); // Create second column column = new DataColumn(); column.DataType = typeof(string); column.ColumnName = "ChildItem"; column.AutoIncrement = false; column.Caption = "ChildItem"; column.Unique = false; _childTable.Columns.Add(column); //Create third column column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "ParentID"; column.AutoIncrement = false; column.Caption = "ParentID"; column.Unique = false; _childTable.Columns.Add(column); _dataSet.Tables.Add(_childTable); // Create three sets of DataRow objects, // five rows each, and add to DataTable. for (int i = 0; i <= 1; i++) { row = _childTable.NewRow(); row["childID"] = i + 1; row["ChildItem"] = "ChildItem " + (i + 1); row["ParentID"] = 1; _childTable.Rows.Add(row); } for (int i = 0; i <= 1; i++) { row = _childTable.NewRow(); row["childID"] = i + 5; row["ChildItem"] = "ChildItem " + (i + 1); row["ParentID"] = 2; _childTable.Rows.Add(row); } for (int i = 0; i <= 1; i++) { row = _childTable.NewRow(); row["childID"] = i + 10; row["ChildItem"] = "ChildItem " + (i + 1); row["ParentID"] = 3; _childTable.Rows.Add(row); } } private void MakeSecondChildTable() { // Create a new Table _secondChildTable = new DataTable("SecondChildTable"); DataColumn column; DataRow row; // Create first column and add to the DataTable. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "ChildID"; column.AutoIncrement = true; column.Caption = "ID"; column.ReadOnly = true; column.Unique = true; // Add the column to the DataColumnCollection. _secondChildTable.Columns.Add(column); // Create second column. column = new DataColumn(); column.DataType = typeof(string); column.ColumnName = "ChildItem"; column.AutoIncrement = false; column.Caption = "ChildItem"; column.ReadOnly = false; column.Unique = false; _secondChildTable.Columns.Add(column); //Create third column. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "ParentID"; column.AutoIncrement = false; column.Caption = "ParentID"; column.ReadOnly = false; column.Unique = false; _secondChildTable.Columns.Add(column); //Create fourth column. column = new DataColumn(); column.DataType = typeof(int); column.ColumnName = "DepartmentID"; column.Caption = "DepartmentID"; column.Unique = false; _secondChildTable.Columns.Add(column); _dataSet.Tables.Add(_secondChildTable); // Create three sets of DataRow objects, // five rows each, and add to DataTable. for (int i = 0; i <= 1; i++) { row = _secondChildTable.NewRow(); row["childID"] = i + 1; row["ChildItem"] = "SecondChildItem " + (i + 1); row["ParentID"] = 1; row["DepartmentID"] = 1; _secondChildTable.Rows.Add(row); } for (int i = 0; i <= 1; i++) { row = _secondChildTable.NewRow(); row["childID"] = i + 5; row["ChildItem"] = "SecondChildItem " + (i + 1); row["ParentID"] = 2; row["DepartmentID"] = 2; _secondChildTable.Rows.Add(row); } for (int i = 0; i <= 1; i++) { row = _secondChildTable.NewRow(); row["childID"] = i + 10; row["ChildItem"] = "SecondChildItem " + (i + 1); row["ParentID"] = 3; row["DepartmentID"] = 3; _secondChildTable.Rows.Add(row); } } private void MakeDataRelation() { DataColumn parentColumn = _dataSet.Tables["ParentTable"].Columns["id"]; DataColumn childColumn = _dataSet.Tables["ChildTable"].Columns["ParentID"]; DataRelation relation = new DataRelation("ParentChild_Relation1", parentColumn, childColumn); _dataSet.Tables["ChildTable"].ParentRelations.Add(relation); DataColumn[] parentColumn1 = new DataColumn[2]; DataColumn[] childColumn1 = new DataColumn[2]; parentColumn1[0] = _dataSet.Tables["ParentTable"].Columns["id"]; parentColumn1[1] = _dataSet.Tables["ParentTable"].Columns["DepartmentID"]; childColumn1[0] = _dataSet.Tables["SecondChildTable"].Columns["ParentID"]; childColumn1[1] = _dataSet.Tables["SecondChildTable"].Columns["DepartmentID"]; DataRelation secondRelation = new DataRelation("ParentChild_Relation2", parentColumn1, childColumn1); _dataSet.Tables["SecondChildTable"].ParentRelations.Add(secondRelation); } private void MakeDataRelation(DataTable dt) { DataColumn parentColumn = dt.Columns["id"]; DataColumn childColumn = _dataSet.Tables["ChildTable"].Columns["ParentID"]; DataRelation relation = new DataRelation("ParentChild_Relation1", parentColumn, childColumn); _dataSet.Tables["ChildTable"].ParentRelations.Add(relation); DataColumn[] parentColumn1 = new DataColumn[2]; DataColumn[] childColumn1 = new DataColumn[2]; parentColumn1[0] = dt.Columns["id"]; parentColumn1[1] = dt.Columns["DepartmentID"]; childColumn1[0] = _dataSet.Tables["SecondChildTable"].Columns["ParentID"]; childColumn1[1] = _dataSet.Tables["SecondChildTable"].Columns["DepartmentID"]; DataRelation secondRelation = new DataRelation("ParentChild_Relation2", parentColumn1, childColumn1); _dataSet.Tables["SecondChildTable"].ParentRelations.Add(secondRelation); } //Test properties of a table which does not belongs to a DataSet private void VerifyTableSchema(DataTable table, string tableName, DataSet ds) { //Test Schema //Check Properties of Table Assert.Equal(string.Empty, table.Namespace); Assert.Equal(ds, table.DataSet); Assert.Equal(3, table.Columns.Count); Assert.False(table.CaseSensitive); Assert.Equal(tableName, table.TableName); Assert.Equal(2, table.Constraints.Count); Assert.Equal(string.Empty, table.Prefix); Assert.Equal(2, table.Constraints.Count); Assert.Equal(typeof(UniqueConstraint), table.Constraints[0].GetType()); Assert.Equal(typeof(UniqueConstraint), table.Constraints[1].GetType()); Assert.Equal(2, table.PrimaryKey.Length); Assert.Equal("id", table.PrimaryKey[0].ToString()); Assert.Equal("DepartmentID", table.PrimaryKey[1].ToString()); Assert.Equal(0, table.ParentRelations.Count); Assert.Equal(0, table.ChildRelations.Count); //Check properties of each column //First Column DataColumn col = table.Columns[0]; Assert.False(col.AllowDBNull); Assert.False(col.AutoIncrement); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("id", col.Caption); Assert.Equal("id", col.ColumnName); Assert.Equal(typeof(int), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.False(col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(0, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ParentTable", col.Table.ToString()); Assert.True(col.Unique); //Second Column col = table.Columns[1]; Assert.True(col.AllowDBNull); Assert.False(col.AutoIncrement); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("ParentItem", col.Caption); Assert.Equal("ParentItem", col.ColumnName); Assert.Equal(typeof(string), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.False(col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(1, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ParentTable", col.Table.ToString()); Assert.False(col.Unique); //Third Column col = table.Columns[2]; Assert.False(col.AllowDBNull); Assert.False(col.AutoIncrement); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("DepartmentID", col.Caption); Assert.Equal("DepartmentID", col.ColumnName); Assert.Equal(typeof(int), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.False(col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(2, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ParentTable", col.Table.ToString()); Assert.False(col.Unique); //Test the Xml Assert.Equal(3, table.Rows.Count); //Test values of each row DataRow row = table.Rows[0]; Assert.Equal(1, row["id"]); Assert.Equal("ParentItem 1", row["ParentItem"]); Assert.Equal(1, row["DepartmentID"]); row = table.Rows[1]; Assert.Equal(2, row["id"]); Assert.Equal("ParentItem 2", row["ParentItem"]); Assert.Equal(2, row["DepartmentID"]); row = table.Rows[2]; Assert.Equal(3, row["id"]); Assert.Equal("ParentItem 3", row["ParentItem"]); Assert.Equal(3, row["DepartmentID"]); } [Fact] public void XmlTest1() { //Make a table without any relations MakeParentTable1(); _dataSet.Tables.Remove(_parentTable1); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table = new DataTable("ParentTable"); //Read the Xml and the Schema into a table which does not belongs to any DataSet ReadXmlSerializable(_tempFile, table); VerifyTableSchema(table, _parentTable1.TableName, null);//parentTable1.DataSet); } [Fact] public void XmlTest2() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table = new DataTable("ParentTable"); DataSet ds = new DataSet("XmlDataSet"); ds.Tables.Add(table); //Read the Xml and the Schema into a table which already belongs to a DataSet //and the table name matches with the table in the source XML ReadXmlSerializable(_tempFile, table); VerifyTableSchema(table, _parentTable1.TableName, ds); } [Fact] public void XmlTest3() { //Create a parent table and create child tables MakeParentTable1(); MakeChildTable(); MakeSecondChildTable(); //Relate the parent and the children MakeDataRelation(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table = new DataTable(); ReadXmlSerializable(_tempFile, table); VerifyTableSchema(table, _parentTable1.TableName, null); } [Fact] public void XmlTest4() { //Create a parent table and create child tables MakeParentTable1(); MakeChildTable(); MakeSecondChildTable(); //Relate the parent and the children MakeDataRelation(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { //WriteXml on any of the children WriteXmlSerializable(stream, _childTable); } DataTable table = new DataTable(); ReadXmlSerializable(_tempFile, table); //Test Schema //Check Properties of Table Assert.Equal(string.Empty, table.Namespace); Assert.Null(table.DataSet); Assert.Equal(3, table.Columns.Count); Assert.False(table.CaseSensitive); Assert.Equal("ChildTable", table.TableName); Assert.Equal(string.Empty, table.Prefix); Assert.Equal(1, table.Constraints.Count); Assert.Equal("Constraint1", table.Constraints[0].ToString()); Assert.Equal(typeof(UniqueConstraint), table.Constraints[0].GetType()); Assert.Equal(0, table.PrimaryKey.Length); Assert.Equal(0, table.ParentRelations.Count); Assert.Equal(0, table.ChildRelations.Count); //Check properties of each column //First Column DataColumn col = table.Columns[0]; Assert.True(col.AllowDBNull); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("ChildID", col.ColumnName); Assert.Equal(typeof(int), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.False(col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(0, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ChildTable", col.Table.ToString()); Assert.True(col.Unique); //Second Column col = table.Columns[1]; Assert.True(col.AllowDBNull); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("ChildItem", col.Caption); Assert.Equal("ChildItem", col.ColumnName); Assert.Equal(typeof(string), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.False(col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(1, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ChildTable", col.Table.ToString()); Assert.False(col.Unique); //Third Column col = table.Columns[2]; Assert.True(col.AllowDBNull); Assert.False(col.AutoIncrement); Assert.Equal(0, col.AutoIncrementSeed); Assert.Equal(1, col.AutoIncrementStep); Assert.Equal("Element", col.ColumnMapping.ToString()); Assert.Equal("ParentID", col.Caption); Assert.Equal("ParentID", col.ColumnName); Assert.Equal(typeof(int), col.DataType); Assert.Equal(string.Empty, col.DefaultValue.ToString()); Assert.False(col.DesignMode); Assert.Equal("System.Data.PropertyCollection", col.ExtendedProperties.ToString()); Assert.Equal(-1, col.MaxLength); Assert.Equal(2, col.Ordinal); Assert.Equal(string.Empty, col.Prefix); Assert.Equal("ChildTable", col.Table.ToString()); Assert.False(col.Unique); //Test the Xml Assert.Equal(6, table.Rows.Count); //Test values of each row DataRow row = table.Rows[0]; Assert.Equal(1, row["ChildID"]); Assert.Equal("ChildItem 1", row["ChildItem"]); Assert.Equal(1, row["ParentID"]); row = table.Rows[1]; Assert.Equal(2, row["ChildID"]); Assert.Equal("ChildItem 2", row["ChildItem"]); Assert.Equal(1, row["ParentID"]); row = table.Rows[2]; Assert.Equal(5, row["ChildID"]); Assert.Equal("ChildItem 1", row["ChildItem"]); Assert.Equal(2, row["ParentID"]); row = table.Rows[3]; Assert.Equal(6, row["ChildID"]); Assert.Equal("ChildItem 2", row["ChildItem"]); Assert.Equal(2, row["ParentID"]); row = table.Rows[4]; Assert.Equal(10, row["ChildID"]); Assert.Equal("ChildItem 1", row["ChildItem"]); Assert.Equal(3, row["ParentID"]); row = table.Rows[5]; Assert.Equal(11, row["ChildID"]); Assert.Equal("ChildItem 2", row["ChildItem"]); Assert.Equal(3, row["ParentID"]); } [Fact] public void XmlTest5() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); stream.Close(); } DataTable table = new DataTable("ParentTable"); DataSet dataSet = new DataSet("XmlDataSet"); dataSet.Tables.Add(table); table.Columns.Add(new DataColumn("id", typeof(string))); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(1, table.Columns.Count); Assert.Equal(typeof(string), table.Columns[0].DataType); Assert.NotNull(table.DataSet); //Check Rows DataRow row = table.Rows[0]; Assert.Equal("1", row[0]); row = table.Rows[1]; Assert.Equal("2", row[0]); row = table.Rows[2]; Assert.Equal("3", row[0]); } [Fact] public void XmlTest6() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); stream.Close(); } //Create a target table which has nomatching column(s) names DataTable table = new DataTable("ParentTable"); DataSet dataSet = new DataSet("XmlDataSet"); dataSet.Tables.Add(table); table.Columns.Add(new DataColumn("sid", typeof(string))); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { // ReadXml does not read anything as the column // names are not matching ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(1, table.Columns.Count); Assert.Equal("sid", table.Columns[0].ColumnName); Assert.Equal(typeof(string), table.Columns[0].DataType); Assert.NotNull(table.DataSet); } [Fact] public void XmlTest7() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); stream.Close(); } //Create a target table which has matching // column(s) name and an extra column DataTable table = new DataTable("ParentTable"); table.Columns.Add(new DataColumn("id", typeof(int))); table.Columns.Add(new DataColumn("ParentItem", typeof(string))); table.Columns.Add(new DataColumn("DepartmentID", typeof(int))); table.Columns.Add(new DataColumn("DummyColumn", typeof(string))); DataSet dataSet = new DataSet("XmlDataSet"); dataSet.Tables.Add(table); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(4, table.Columns.Count); Assert.NotNull(table.DataSet); //Check the Columns Assert.Equal("id", table.Columns[0].ColumnName); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal("ParentItem", table.Columns[1].ColumnName); Assert.Equal(typeof(string), table.Columns[1].DataType); Assert.Equal("DepartmentID", table.Columns[2].ColumnName); Assert.Equal(typeof(int), table.Columns[2].DataType); Assert.Equal("DummyColumn", table.Columns[3].ColumnName); Assert.Equal(typeof(string), table.Columns[3].DataType); //Check the rows DataRow row = table.Rows[0]; Assert.Equal(1, row["id"]); Assert.Equal("ParentItem 1", row["ParentItem"]); Assert.Equal(1, row["DepartmentID"]); row = table.Rows[1]; Assert.Equal(2, row["id"]); Assert.Equal("ParentItem 2", row["ParentItem"]); Assert.Equal(2, row["DepartmentID"]); row = table.Rows[2]; Assert.Equal(3, row["id"]); Assert.Equal("ParentItem 3", row["ParentItem"]); Assert.Equal(3, row["DepartmentID"]); } [Fact] public void XmlTest8() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table = new DataTable("ParentTable"); DataSet dataSet = new DataSet("XmlDataSet"); dataSet.Tables.Add(table); table.Columns.Add(new DataColumn("id", typeof(int))); table.Columns.Add(new DataColumn("DepartmentID", typeof(int))); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(2, table.Columns.Count); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal(typeof(int), table.Columns[1].DataType); Assert.NotNull(table.DataSet); //Check rows DataRow row = table.Rows[0]; Assert.Equal(1, row[0]); Assert.Equal(1, row[1]); row = table.Rows[1]; Assert.Equal(2, row[0]); Assert.Equal(2, row[1]); row = table.Rows[2]; Assert.Equal(3, row[0]); Assert.Equal(3, row[1]); } [Fact] public void XmlTest9() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataSet ds = new DataSet(); DataTable table = new DataTable("ParentTable"); table.Columns.Add(new DataColumn("id", typeof(int))); ds.Tables.Add(table); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal(3, table.Rows.Count); Assert.Equal(1, table.Columns.Count); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal("System.Data.DataSet", table.DataSet.ToString()); Assert.Equal("NewDataSet", table.DataSet.DataSetName); //Check the rows DataRow row = table.Rows[0]; Assert.Equal(1, row[0]); row = table.Rows[1]; Assert.Equal(2, row[0]); row = table.Rows[2]; Assert.Equal(3, row[0]); } [Fact] public void XmlTest10() { MakeParentTable1(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataSet ds = new DataSet(); DataTable table = new DataTable("ParentTable"); table.Columns.Add(new DataColumn("id", typeof(int))); table.Columns.Add(new DataColumn("DepartmentID", typeof(string))); ds.Tables.Add(table); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Equal("ParentTable", table.TableName); Assert.Equal("NewDataSet", table.DataSet.DataSetName); Assert.Equal(3, table.Rows.Count); Assert.Equal(2, table.Columns.Count); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal(typeof(string), table.Columns[1].DataType); //Check rows DataRow row = table.Rows[0]; Assert.Equal(1, row[0]); Assert.Equal("1", row[1]); row = table.Rows[1]; Assert.Equal(2, row[0]); Assert.Equal("2", row[1]); row = table.Rows[2]; Assert.Equal(3, row[0]); Assert.Equal("3", row[1]); } [Fact] public void XmlTest11() { MakeDummyTable(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _dummyTable); } //Create a table and set the table name DataTable table = new DataTable("DummyTable"); //define the table schame partially table.Columns.Add(new DataColumn("DummyItem", typeof(string))); using (FileStream stream = new FileStream(_tempFile, FileMode.Open)) { ReadXmlSerializable(stream, table); } Assert.Null(table.DataSet); Assert.Equal(1, table.Columns.Count); Assert.Equal(typeof(string), table.Columns[0].DataType); Assert.Equal(3, table.Rows.Count); //Check Rows DataRow row = table.Rows[0]; Assert.Equal("DummyItem 1", row[0]); Assert.Equal(DataRowState.Unchanged, row.RowState); row = table.Rows[1]; Assert.Equal("Changed_DummyItem 2", row[0]); Assert.Equal(DataRowState.Modified, row.RowState); row = table.Rows[2]; Assert.Equal("DummyItem 3", row[0]); Assert.Equal(DataRowState.Unchanged, row.RowState); } [Fact] public void XmlTest14() { MakeParentTable1(); MakeChildTable(); MakeSecondChildTable(); MakeDataRelation(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _parentTable1); } DataTable table1 = new DataTable("ParentTable"); table1.Columns.Add(new DataColumn(_parentTable1.Columns[0].ColumnName, typeof(int))); table1.Columns.Add(new DataColumn(_parentTable1.Columns[1].ColumnName, typeof(string))); table1.Columns.Add(new DataColumn(_parentTable1.Columns[2].ColumnName, typeof(int))); ReadXmlSerializable(_tempFile, table1); Assert.Null(table1.DataSet); Assert.Equal("ParentTable", table1.TableName); Assert.Equal(3, table1.Columns.Count); Assert.Equal(typeof(int), table1.Columns[0].DataType); Assert.Equal(typeof(string), table1.Columns[1].DataType); Assert.Equal(typeof(int), table1.Columns[2].DataType); Assert.Equal(0, table1.ChildRelations.Count); Assert.Equal(3, table1.Rows.Count); //Check the row DataRow row = table1.Rows[0]; Assert.Equal(1, row[0]); Assert.Equal("ParentItem 1", row[1]); Assert.Equal(1, row[2]); row = table1.Rows[1]; Assert.Equal(2, row[0]); Assert.Equal("ParentItem 2", row[1]); Assert.Equal(2, row[2]); row = table1.Rows[2]; Assert.Equal(3, row[0]); Assert.Equal("ParentItem 3", row[1]); Assert.Equal(3, row[2]); } [Fact] public void XmlTest15() { MakeDummyTable(); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, _dummyTable); } Assert.Equal(3, _dummyTable.Rows.Count); DataSet dataSet = new DataSet("HelloWorldDataSet"); DataTable table = new DataTable("DummyTable"); table.Columns.Add(new DataColumn("DummyItem", typeof(string))); dataSet.Tables.Add(table); //Call ReadXml on a table which belong to a DataSet ReadXmlSerializable(_tempFile, table); Assert.Equal("HelloWorldDataSet", table.DataSet.DataSetName); Assert.Equal(1, table.Columns.Count); Assert.Equal(typeof(string), table.Columns[0].DataType); Assert.Equal(3, table.Rows.Count); //Check Rows DataRow row = table.Rows[0]; Assert.Equal("DummyItem 1", row[0]); Assert.Equal(DataRowState.Unchanged, row.RowState); row = table.Rows[1]; Assert.Equal("Changed_DummyItem 2", row[0]); Assert.Equal(DataRowState.Modified, row.RowState); row = table.Rows[2]; Assert.Equal("DummyItem 3", row[0]); Assert.Equal(DataRowState.Unchanged, row.RowState); } [Fact] public void XmlTest16() { DataSet ds = new DataSet(); DataTable parent = new DataTable("Parent"); parent.Columns.Add(new DataColumn("col1", typeof(int))); parent.Columns.Add(new DataColumn("col2", typeof(string))); parent.Columns[0].Unique = true; DataTable child1 = new DataTable("Child1"); child1.Columns.Add(new DataColumn("col3", typeof(int))); child1.Columns.Add(new DataColumn("col4", typeof(string))); child1.Columns.Add(new DataColumn("col5", typeof(int))); child1.Columns[2].Unique = true; DataTable child2 = new DataTable("Child2"); child2.Columns.Add(new DataColumn("col6", typeof(int))); child2.Columns.Add(new DataColumn("col7")); parent.Rows.Add(new object[] { 1, "P_" }); parent.Rows.Add(new object[] { 2, "P_" }); child1.Rows.Add(new object[] { 1, "C1_", 3 }); child1.Rows.Add(new object[] { 1, "C1_", 4 }); child1.Rows.Add(new object[] { 2, "C1_", 5 }); child1.Rows.Add(new object[] { 2, "C1_", 6 }); child2.Rows.Add(new object[] { 3, "C2_" }); child2.Rows.Add(new object[] { 3, "C2_" }); child2.Rows.Add(new object[] { 4, "C2_" }); child2.Rows.Add(new object[] { 4, "C2_" }); child2.Rows.Add(new object[] { 5, "C2_" }); child2.Rows.Add(new object[] { 5, "C2_" }); child2.Rows.Add(new object[] { 6, "C2_" }); child2.Rows.Add(new object[] { 6, "C2_" }); ds.Tables.Add(parent); ds.Tables.Add(child1); ds.Tables.Add(child2); DataRelation relation = new DataRelation("Relation1", parent.Columns[0], child1.Columns[0]); parent.ChildRelations.Add(relation); relation = new DataRelation("Relation2", child1.Columns[2], child2.Columns[0]); child1.ChildRelations.Add(relation); using (FileStream stream = new FileStream(_tempFile, FileMode.Create)) { WriteXmlSerializable(stream, parent); } DataTable table = new DataTable(); ReadXmlSerializable(_tempFile, table); Assert.Equal("Parent", table.TableName); Assert.Equal(2, table.Columns.Count); Assert.Equal(2, table.Rows.Count); Assert.Equal(typeof(int), table.Columns[0].DataType); Assert.Equal(typeof(string), table.Columns[1].DataType); Assert.Equal(1, table.Constraints.Count); Assert.Equal(typeof(UniqueConstraint), table.Constraints[0].GetType()); } } }
-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.TypeConverter/src/System/ComponentModel/LicenseContext.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.Reflection; namespace System.ComponentModel { /// <summary> /// Specifies when the licensed object can be used. /// </summary> public class LicenseContext : IServiceProvider { /// <summary> /// When overridden in a derived class, gets a value that specifies when a license can be used. /// </summary> public virtual LicenseUsageMode UsageMode => LicenseUsageMode.Runtime; /// <summary> /// When overridden in a derived class, gets a saved license /// key for the specified type, from the specified resource assembly. /// </summary> public virtual string? GetSavedLicenseKey(Type type, Assembly? resourceAssembly) => null; /// <summary> /// When overridden in a derived class, will return an object that implements the asked for service. /// </summary> public virtual object? GetService(Type type) => null; /// <summary> /// When overridden in a derived class, sets a license key for the specified type. /// </summary> public virtual void SetSavedLicenseKey(Type type, string key) { // no-op; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; namespace System.ComponentModel { /// <summary> /// Specifies when the licensed object can be used. /// </summary> public class LicenseContext : IServiceProvider { /// <summary> /// When overridden in a derived class, gets a value that specifies when a license can be used. /// </summary> public virtual LicenseUsageMode UsageMode => LicenseUsageMode.Runtime; /// <summary> /// When overridden in a derived class, gets a saved license /// key for the specified type, from the specified resource assembly. /// </summary> public virtual string? GetSavedLicenseKey(Type type, Assembly? resourceAssembly) => null; /// <summary> /// When overridden in a derived class, will return an object that implements the asked for service. /// </summary> public virtual object? GetService(Type type) => null; /// <summary> /// When overridden in a derived class, sets a license key for the specified type. /// </summary> public virtual void SetSavedLicenseKey(Type type, string key) { // no-op; } } }
-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.Drawing.Common/src/System/Drawing/Text/HotkeyPrefix.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.Drawing.Text { /// <summary> /// Specifies the type of display for hotkey prefixes for text. /// </summary> public enum HotkeyPrefix { /// <summary> /// No hotkey prefix. /// </summary> None = 0, /// <summary> /// Display the hotkey prefix. /// </summary> Show = 1, /// <summary> /// Do not display the hotkey prefix. /// </summary> Hide = 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.Drawing.Text { /// <summary> /// Specifies the type of display for hotkey prefixes for text. /// </summary> public enum HotkeyPrefix { /// <summary> /// No hotkey prefix. /// </summary> None = 0, /// <summary> /// Display the hotkey prefix. /// </summary> Show = 1, /// <summary> /// Do not display the hotkey prefix. /// </summary> Hide = 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/tests/JIT/Regression/JitBlue/devdiv_911875/DevDiv_911875.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; using System.Runtime.InteropServices; public class Repro { public float x; public float y; private static int Main() { byte[] buf = new byte[8]; WriteFloat(buf, 0, 123.0F); WriteFloat(buf, 4, 456.0F); Repro pt = new Repro(); Test(pt, buf); if (Convert.ToInt32(pt.x) != 123 || Convert.ToInt32(pt.y) != 456) { Console.WriteLine("FAIL!"); Console.WriteLine("Unexpected values for pt.x and pt.y."); Console.WriteLine(pt.x); Console.WriteLine(pt.y); return 101; } Console.WriteLine("PASS!"); return 100; } public static void Test(object obj, byte[] buf) { ((Repro)obj).x = ReadFloat(buf, 0); ((Repro)obj).y = ReadFloat(buf, 4); } public static int ReadInt(byte[] buf, int offset) { return (buf[offset + 0] << 24) + (buf[offset + 1] << 16) + (buf[offset + 2] << 8) + (buf[offset + 3] << 0); } public static float ReadFloat(byte[] buf, int offset) { return IntBitsToFloat(ReadInt(buf, offset)); } public static void WriteInt(byte[] buf, int offset, int val) { buf[offset + 3] = (byte)(val); buf[offset + 2] = (byte)(val >> 8); buf[offset + 1] = (byte)(val >> 16); buf[offset] = (byte)(val >> 24); } public static void WriteFloat(byte[] buf, int offset, float value) { WriteInt(buf, offset, FloatToRawIntBits(value)); } public static float IntBitsToFloat(int value) { FloatConverter converter = new FloatConverter(); return FloatConverter.ToFloat(value, ref converter); } public static int FloatToRawIntBits(float f) { FloatConverter converter = new FloatConverter(); return FloatConverter.ToInt(f, ref converter); } } [StructLayout(LayoutKind.Explicit)] public struct FloatConverter { [FieldOffset(0)] private float _f; [FieldOffset(0)] private int _i; public static int ToInt(float value, ref FloatConverter converter) { converter._f = value; return converter._i; } public static float ToFloat(int value, ref FloatConverter converter) { converter._i = value; return converter._f; } }
// 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; using System.Runtime.InteropServices; public class Repro { public float x; public float y; private static int Main() { byte[] buf = new byte[8]; WriteFloat(buf, 0, 123.0F); WriteFloat(buf, 4, 456.0F); Repro pt = new Repro(); Test(pt, buf); if (Convert.ToInt32(pt.x) != 123 || Convert.ToInt32(pt.y) != 456) { Console.WriteLine("FAIL!"); Console.WriteLine("Unexpected values for pt.x and pt.y."); Console.WriteLine(pt.x); Console.WriteLine(pt.y); return 101; } Console.WriteLine("PASS!"); return 100; } public static void Test(object obj, byte[] buf) { ((Repro)obj).x = ReadFloat(buf, 0); ((Repro)obj).y = ReadFloat(buf, 4); } public static int ReadInt(byte[] buf, int offset) { return (buf[offset + 0] << 24) + (buf[offset + 1] << 16) + (buf[offset + 2] << 8) + (buf[offset + 3] << 0); } public static float ReadFloat(byte[] buf, int offset) { return IntBitsToFloat(ReadInt(buf, offset)); } public static void WriteInt(byte[] buf, int offset, int val) { buf[offset + 3] = (byte)(val); buf[offset + 2] = (byte)(val >> 8); buf[offset + 1] = (byte)(val >> 16); buf[offset] = (byte)(val >> 24); } public static void WriteFloat(byte[] buf, int offset, float value) { WriteInt(buf, offset, FloatToRawIntBits(value)); } public static float IntBitsToFloat(int value) { FloatConverter converter = new FloatConverter(); return FloatConverter.ToFloat(value, ref converter); } public static int FloatToRawIntBits(float f) { FloatConverter converter = new FloatConverter(); return FloatConverter.ToInt(f, ref converter); } } [StructLayout(LayoutKind.Explicit)] public struct FloatConverter { [FieldOffset(0)] private float _f; [FieldOffset(0)] private int _i; public static int ToInt(float value, ref FloatConverter converter) { converter._f = value; return converter._i; } public static float ToFloat(int value, ref FloatConverter converter) { converter._i = value; return converter._f; } }
-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/HorizontalSubtract.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; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics; namespace IntelHardwareIntrinsicTest { class Program { const int Pass = 100; const int Fail = 0; static unsafe int Main(string[] args) { int testResult = Pass; if (Avx.IsSupported) { using (TestTable<float> floatTable = new TestTable<float>(new float[8] {22, -1, -50, 0, 22, -1, -50, 0 }, new float[8] { 22, -1, -50, 0, 22, -1, -50, 0 }, new float[8])) using (TestTable<double> doubleTable = new TestTable<double>(new double[4] { 1, -5, 100, 0 }, new double[4] { 22, -1, -50, 0 }, new double[4])) { var vf1 = Unsafe.Read<Vector256<float>>(floatTable.inArray1Ptr); var vf2 = Unsafe.Read<Vector256<float>>(floatTable.inArray2Ptr); var vf3 = Avx.HorizontalSubtract(vf1, vf2); Unsafe.Write(floatTable.outArrayPtr, vf3); if (!floatTable.CheckResult((left, right, result) => (left[0] - left[1] == result[0]) && (right[0] - right[1] == result[2]) && (left[2] - left[3] == result[1]) && (right[2] - right[3] == result[3]) && (left[4] - left[5] == result[4]) && (right[4] - right[5] == result[6]) && (left[6] - left[7] == result[5]) && (right[6] - right[7] == result[7]))) { Console.WriteLine("Avx HorizontalAdd failed on float:"); foreach (var item in floatTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } var vd1 = Unsafe.Read<Vector256<double>>(doubleTable.inArray1Ptr); var vd2 = Unsafe.Read<Vector256<double>>(doubleTable.inArray2Ptr); var vd3 = Avx.HorizontalSubtract(vd1, vd2); Unsafe.Write(doubleTable.outArrayPtr, vd3); if (!doubleTable.CheckResult((left, right, result) => (left[0] - left[1] == result[0]) && (right[0] - right[1] == result[1]) && (left[2] - left[3] == result[2]) && (right[2] - right[3] == result[3]))) { Console.WriteLine("Avx HorizontalAdd failed on double:"); foreach (var item in doubleTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } } return testResult; } public unsafe struct TestTable<T> : IDisposable where T : struct { public T[] inArray1; public T[] inArray2; public T[] outArray; public void* inArray1Ptr => inHandle1.AddrOfPinnedObject().ToPointer(); public void* inArray2Ptr => inHandle2.AddrOfPinnedObject().ToPointer(); public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer(); GCHandle inHandle1; GCHandle inHandle2; GCHandle outHandle; public TestTable(T[] a, T[] b, T[] c) { this.inArray1 = a; this.inArray2 = b; this.outArray = c; inHandle1 = GCHandle.Alloc(inArray1, GCHandleType.Pinned); inHandle2 = GCHandle.Alloc(inArray2, GCHandleType.Pinned); outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned); } public bool CheckResult(Func<T[], T[], T[], bool> check) { return check(inArray1, inArray2, outArray); } public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } } } }
// 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; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics; namespace IntelHardwareIntrinsicTest { class Program { const int Pass = 100; const int Fail = 0; static unsafe int Main(string[] args) { int testResult = Pass; if (Avx.IsSupported) { using (TestTable<float> floatTable = new TestTable<float>(new float[8] {22, -1, -50, 0, 22, -1, -50, 0 }, new float[8] { 22, -1, -50, 0, 22, -1, -50, 0 }, new float[8])) using (TestTable<double> doubleTable = new TestTable<double>(new double[4] { 1, -5, 100, 0 }, new double[4] { 22, -1, -50, 0 }, new double[4])) { var vf1 = Unsafe.Read<Vector256<float>>(floatTable.inArray1Ptr); var vf2 = Unsafe.Read<Vector256<float>>(floatTable.inArray2Ptr); var vf3 = Avx.HorizontalSubtract(vf1, vf2); Unsafe.Write(floatTable.outArrayPtr, vf3); if (!floatTable.CheckResult((left, right, result) => (left[0] - left[1] == result[0]) && (right[0] - right[1] == result[2]) && (left[2] - left[3] == result[1]) && (right[2] - right[3] == result[3]) && (left[4] - left[5] == result[4]) && (right[4] - right[5] == result[6]) && (left[6] - left[7] == result[5]) && (right[6] - right[7] == result[7]))) { Console.WriteLine("Avx HorizontalAdd failed on float:"); foreach (var item in floatTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } var vd1 = Unsafe.Read<Vector256<double>>(doubleTable.inArray1Ptr); var vd2 = Unsafe.Read<Vector256<double>>(doubleTable.inArray2Ptr); var vd3 = Avx.HorizontalSubtract(vd1, vd2); Unsafe.Write(doubleTable.outArrayPtr, vd3); if (!doubleTable.CheckResult((left, right, result) => (left[0] - left[1] == result[0]) && (right[0] - right[1] == result[1]) && (left[2] - left[3] == result[2]) && (right[2] - right[3] == result[3]))) { Console.WriteLine("Avx HorizontalAdd failed on double:"); foreach (var item in doubleTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } } return testResult; } public unsafe struct TestTable<T> : IDisposable where T : struct { public T[] inArray1; public T[] inArray2; public T[] outArray; public void* inArray1Ptr => inHandle1.AddrOfPinnedObject().ToPointer(); public void* inArray2Ptr => inHandle2.AddrOfPinnedObject().ToPointer(); public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer(); GCHandle inHandle1; GCHandle inHandle2; GCHandle outHandle; public TestTable(T[] a, T[] b, T[] c) { this.inArray1 = a; this.inArray2 = b; this.outArray = c; inHandle1 = GCHandle.Alloc(inArray1, GCHandleType.Pinned); inHandle2 = GCHandle.Alloc(inArray2, GCHandleType.Pinned); outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned); } public bool CheckResult(Func<T[], T[], T[], bool> check) { return check(inArray1, inArray2, outArray); } public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } } } }
-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.Extensions.Logging/tests/DI.Common/Common/src/XunitLoggerProvider.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.Linq; using System.Text; using Xunit.Abstractions; namespace Microsoft.Extensions.Logging.Testing { public class XunitLoggerProvider : ILoggerProvider { private readonly ITestOutputHelper _output; private readonly LogLevel _minLevel; private readonly DateTimeOffset? _logStart; public XunitLoggerProvider(ITestOutputHelper output) : this(output, LogLevel.Trace) { } public XunitLoggerProvider(ITestOutputHelper output, LogLevel minLevel) : this(output, minLevel, null) { } public XunitLoggerProvider(ITestOutputHelper output, LogLevel minLevel, DateTimeOffset? logStart) { _output = output; _minLevel = minLevel; _logStart = logStart; } public ILogger CreateLogger(string categoryName) { return new XunitLogger(_output, categoryName, _minLevel, _logStart); } public void Dispose() { } } public class XunitLogger : ILogger { private static readonly string[] NewLineChars = new[] { Environment.NewLine }; private readonly string _category; private readonly LogLevel _minLogLevel; private readonly ITestOutputHelper _output; private DateTimeOffset? _logStart; public XunitLogger(ITestOutputHelper output, string category, LogLevel minLogLevel, DateTimeOffset? logStart) { _minLogLevel = minLogLevel; _category = category; _output = output; _logStart = logStart; } public void Log<TState>( LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { if (!IsEnabled(logLevel)) { return; } // Buffer the message into a single string in order to avoid shearing the message when running across multiple threads. var messageBuilder = new StringBuilder(); var timestamp = _logStart.HasValue ? $"{(DateTimeOffset.UtcNow - _logStart.Value).TotalSeconds.ToString("N3")}s" : DateTimeOffset.UtcNow.ToString("s"); var firstLinePrefix = $"| [{timestamp}] {_category} {logLevel}: "; var lines = formatter(state, exception).Split(NewLineChars, StringSplitOptions.RemoveEmptyEntries); messageBuilder.AppendLine(firstLinePrefix + lines.FirstOrDefault() ?? string.Empty); var additionalLinePrefix = "|" + new string(' ', firstLinePrefix.Length - 1); foreach (var line in lines.Skip(1)) { messageBuilder.AppendLine(additionalLinePrefix + line); } if (exception != null) { lines = exception.ToString().Split(NewLineChars, StringSplitOptions.RemoveEmptyEntries); additionalLinePrefix = "| "; foreach (var line in lines) { messageBuilder.AppendLine(additionalLinePrefix + line); } } // Remove the last line-break, because ITestOutputHelper only has WriteLine. var message = messageBuilder.ToString(); if (message.EndsWith(Environment.NewLine)) { message = message.Substring(0, message.Length - Environment.NewLine.Length); } try { _output.WriteLine(message); } catch (Exception) { // We could fail because we're on a background thread and our captured ITestOutputHelper is // busted (if the test "completed" before the background thread fired). // So, ignore this. There isn't really anything we can do but hope the // caller has additional loggers registered } } public bool IsEnabled(LogLevel logLevel) => logLevel >= _minLogLevel; public IDisposable BeginScope<TState>(TState state) => new NullScope(); private class NullScope : IDisposable { public void Dispose() { } } } }
// 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.Linq; using System.Text; using Xunit.Abstractions; namespace Microsoft.Extensions.Logging.Testing { public class XunitLoggerProvider : ILoggerProvider { private readonly ITestOutputHelper _output; private readonly LogLevel _minLevel; private readonly DateTimeOffset? _logStart; public XunitLoggerProvider(ITestOutputHelper output) : this(output, LogLevel.Trace) { } public XunitLoggerProvider(ITestOutputHelper output, LogLevel minLevel) : this(output, minLevel, null) { } public XunitLoggerProvider(ITestOutputHelper output, LogLevel minLevel, DateTimeOffset? logStart) { _output = output; _minLevel = minLevel; _logStart = logStart; } public ILogger CreateLogger(string categoryName) { return new XunitLogger(_output, categoryName, _minLevel, _logStart); } public void Dispose() { } } public class XunitLogger : ILogger { private static readonly string[] NewLineChars = new[] { Environment.NewLine }; private readonly string _category; private readonly LogLevel _minLogLevel; private readonly ITestOutputHelper _output; private DateTimeOffset? _logStart; public XunitLogger(ITestOutputHelper output, string category, LogLevel minLogLevel, DateTimeOffset? logStart) { _minLogLevel = minLogLevel; _category = category; _output = output; _logStart = logStart; } public void Log<TState>( LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { if (!IsEnabled(logLevel)) { return; } // Buffer the message into a single string in order to avoid shearing the message when running across multiple threads. var messageBuilder = new StringBuilder(); var timestamp = _logStart.HasValue ? $"{(DateTimeOffset.UtcNow - _logStart.Value).TotalSeconds.ToString("N3")}s" : DateTimeOffset.UtcNow.ToString("s"); var firstLinePrefix = $"| [{timestamp}] {_category} {logLevel}: "; var lines = formatter(state, exception).Split(NewLineChars, StringSplitOptions.RemoveEmptyEntries); messageBuilder.AppendLine(firstLinePrefix + lines.FirstOrDefault() ?? string.Empty); var additionalLinePrefix = "|" + new string(' ', firstLinePrefix.Length - 1); foreach (var line in lines.Skip(1)) { messageBuilder.AppendLine(additionalLinePrefix + line); } if (exception != null) { lines = exception.ToString().Split(NewLineChars, StringSplitOptions.RemoveEmptyEntries); additionalLinePrefix = "| "; foreach (var line in lines) { messageBuilder.AppendLine(additionalLinePrefix + line); } } // Remove the last line-break, because ITestOutputHelper only has WriteLine. var message = messageBuilder.ToString(); if (message.EndsWith(Environment.NewLine)) { message = message.Substring(0, message.Length - Environment.NewLine.Length); } try { _output.WriteLine(message); } catch (Exception) { // We could fail because we're on a background thread and our captured ITestOutputHelper is // busted (if the test "completed" before the background thread fired). // So, ignore this. There isn't really anything we can do but hope the // caller has additional loggers registered } } public bool IsEnabled(LogLevel logLevel) => logLevel >= _minLogLevel; public IDisposable BeginScope<TState>(TState state) => new NullScope(); private class NullScope : IDisposable { public void Dispose() { } } } }
-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/DuplicateToVector128.UInt16.31.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 DuplicateToVector128_UInt16_31() { var test = new ImmOpTest__DuplicateToVector128_UInt16_31(); if (test.IsSupported) { // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); } 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 ImmOpTest__DuplicateToVector128_UInt16_31 { private struct DataTable { private byte[] outArray; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] outArray, int alignment) { int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.outArray = new byte[alignment * 2]; this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; } public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private static readonly int LargestVectorSize = 16; private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private DataTable _dataTable; public ImmOpTest__DuplicateToVector128_UInt16_31() { Succeeded = true; _dataTable = new DataTable(new UInt16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); var result = AdvSimd.DuplicateToVector128( (UInt16)31 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.DuplicateToVector128), new Type[] { typeof(UInt16) }) .Invoke(null, new object[] { (UInt16)31 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.outArrayPtr); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(void* result, [CallerMemberName] string method = "") { UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(outArray, method); } private void ValidateResult(UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != 31) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 31) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.DuplicateToVector128)}<UInt16>(31): {method} failed:"); 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 DuplicateToVector128_UInt16_31() { var test = new ImmOpTest__DuplicateToVector128_UInt16_31(); if (test.IsSupported) { // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); } 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 ImmOpTest__DuplicateToVector128_UInt16_31 { private struct DataTable { private byte[] outArray; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] outArray, int alignment) { int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.outArray = new byte[alignment * 2]; this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; } public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private static readonly int LargestVectorSize = 16; private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private DataTable _dataTable; public ImmOpTest__DuplicateToVector128_UInt16_31() { Succeeded = true; _dataTable = new DataTable(new UInt16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); var result = AdvSimd.DuplicateToVector128( (UInt16)31 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.DuplicateToVector128), new Type[] { typeof(UInt16) }) .Invoke(null, new object[] { (UInt16)31 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.outArrayPtr); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(void* result, [CallerMemberName] string method = "") { UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(outArray, method); } private void ValidateResult(UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != 31) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 31) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.DuplicateToVector128)}<UInt16>(31): {method} failed:"); 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/Interop/PInvoke/Generics/GenericsTest.Point2D.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.InteropServices; using Xunit; unsafe partial class GenericsNative { [DllImport(nameof(GenericsNative))] public static extern Point2<double> GetPoint2D(double e00, double e01); [DllImport(nameof(GenericsNative))] public static extern void GetPoint2DOut(double e00, double e01, Point2<double>* value); [DllImport(nameof(GenericsNative))] public static extern void GetPoint2DOut(double e00, double e01, out Point2<double> value); [DllImport(nameof(GenericsNative))] public static extern Point2<double>* GetPoint2DPtr(double e00, double e01); [DllImport(nameof(GenericsNative), EntryPoint = "GetPoint2DPtr")] public static extern ref readonly Point2<double> GetPoint2DRef(double e00, double e01); [DllImport(nameof(GenericsNative))] public static extern Point2<double> AddPoint2D(Point2<double> lhs, Point2<double> rhs); [DllImport(nameof(GenericsNative))] public static extern Point2<double> AddPoint2Ds(Point2<double>* pValues, int count); [DllImport(nameof(GenericsNative))] public static extern Point2<double> AddPoint2Ds([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] Point2<double>[] pValues, int count); [DllImport(nameof(GenericsNative))] public static extern Point2<double> AddPoint2Ds(in Point2<double> pValues, int count); } unsafe partial class GenericsTest { private static void TestPoint2D() { GenericsNative.Point2<double> value = GenericsNative.GetPoint2D(1.0, 2.0); Assert.Equal(value.e00, 1.0); Assert.Equal(value.e01, 2.0); GenericsNative.Point2<double> value2; GenericsNative.GetPoint2DOut(1.0, 2.0, &value2); Assert.Equal(value2.e00, 1.0); Assert.Equal(value2.e01, 2.0); GenericsNative.GetPoint2DOut(1.0, 2.0, out GenericsNative.Point2<double> value3); Assert.Equal(value3.e00, 1.0); Assert.Equal(value3.e01, 2.0); GenericsNative.Point2<double>* value4 = GenericsNative.GetPoint2DPtr(1.0, 2.0); Assert.Equal(value4->e00, 1.0); Assert.Equal(value4->e01, 2.0); ref readonly GenericsNative.Point2<double> value5 = ref GenericsNative.GetPoint2DRef(1.0, 2.0); Assert.Equal(value5.e00, 1.0); Assert.Equal(value5.e01, 2.0); GenericsNative.Point2<double> result = GenericsNative.AddPoint2D(value, value); Assert.Equal(result.e00, 2.0); Assert.Equal(result.e01, 4.0); GenericsNative.Point2<double>[] values = new GenericsNative.Point2<double>[] { value, value2, value3, *value4, value5 }; fixed (GenericsNative.Point2<double>* pValues = &values[0]) { GenericsNative.Point2<double> result2 = GenericsNative.AddPoint2Ds(pValues, values.Length); Assert.Equal(result2.e00, 5.0); Assert.Equal(result2.e01, 10.0); } GenericsNative.Point2<double> result3 = GenericsNative.AddPoint2Ds(values, values.Length); Assert.Equal(result3.e00, 5.0); Assert.Equal(result3.e01, 10.0); GenericsNative.Point2<double> result4 = GenericsNative.AddPoint2Ds(in values[0], values.Length); Assert.Equal(result4.e00, 5.0); Assert.Equal(result4.e01, 10.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.InteropServices; using Xunit; unsafe partial class GenericsNative { [DllImport(nameof(GenericsNative))] public static extern Point2<double> GetPoint2D(double e00, double e01); [DllImport(nameof(GenericsNative))] public static extern void GetPoint2DOut(double e00, double e01, Point2<double>* value); [DllImport(nameof(GenericsNative))] public static extern void GetPoint2DOut(double e00, double e01, out Point2<double> value); [DllImport(nameof(GenericsNative))] public static extern Point2<double>* GetPoint2DPtr(double e00, double e01); [DllImport(nameof(GenericsNative), EntryPoint = "GetPoint2DPtr")] public static extern ref readonly Point2<double> GetPoint2DRef(double e00, double e01); [DllImport(nameof(GenericsNative))] public static extern Point2<double> AddPoint2D(Point2<double> lhs, Point2<double> rhs); [DllImport(nameof(GenericsNative))] public static extern Point2<double> AddPoint2Ds(Point2<double>* pValues, int count); [DllImport(nameof(GenericsNative))] public static extern Point2<double> AddPoint2Ds([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] Point2<double>[] pValues, int count); [DllImport(nameof(GenericsNative))] public static extern Point2<double> AddPoint2Ds(in Point2<double> pValues, int count); } unsafe partial class GenericsTest { private static void TestPoint2D() { GenericsNative.Point2<double> value = GenericsNative.GetPoint2D(1.0, 2.0); Assert.Equal(value.e00, 1.0); Assert.Equal(value.e01, 2.0); GenericsNative.Point2<double> value2; GenericsNative.GetPoint2DOut(1.0, 2.0, &value2); Assert.Equal(value2.e00, 1.0); Assert.Equal(value2.e01, 2.0); GenericsNative.GetPoint2DOut(1.0, 2.0, out GenericsNative.Point2<double> value3); Assert.Equal(value3.e00, 1.0); Assert.Equal(value3.e01, 2.0); GenericsNative.Point2<double>* value4 = GenericsNative.GetPoint2DPtr(1.0, 2.0); Assert.Equal(value4->e00, 1.0); Assert.Equal(value4->e01, 2.0); ref readonly GenericsNative.Point2<double> value5 = ref GenericsNative.GetPoint2DRef(1.0, 2.0); Assert.Equal(value5.e00, 1.0); Assert.Equal(value5.e01, 2.0); GenericsNative.Point2<double> result = GenericsNative.AddPoint2D(value, value); Assert.Equal(result.e00, 2.0); Assert.Equal(result.e01, 4.0); GenericsNative.Point2<double>[] values = new GenericsNative.Point2<double>[] { value, value2, value3, *value4, value5 }; fixed (GenericsNative.Point2<double>* pValues = &values[0]) { GenericsNative.Point2<double> result2 = GenericsNative.AddPoint2Ds(pValues, values.Length); Assert.Equal(result2.e00, 5.0); Assert.Equal(result2.e01, 10.0); } GenericsNative.Point2<double> result3 = GenericsNative.AddPoint2Ds(values, values.Length); Assert.Equal(result3.e00, 5.0); Assert.Equal(result3.e01, 10.0); GenericsNative.Point2<double> result4 = GenericsNative.AddPoint2Ds(in values[0], values.Length); Assert.Equal(result4.e00, 5.0); Assert.Equal(result4.e01, 10.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.Drawing.Common/src/System/Drawing/SizeConverter.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.Drawing { using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.Win32; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Globalization; using System.Reflection; /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter"]/*' /> /// <devdoc> /// SizeConverter is a class that can be used to convert /// Size from one data type to another. Access this /// class through the TypeDescriptor. /// </devdoc> public class SizeConverter : TypeConverter { /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.CanConvertFrom"]/*' /> /// <devdoc> /// Determines if this converter can convert an object in the given source /// type to the native type of the converter. /// </devdoc> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.CanConvertTo"]/*' /> /// <devdoc> /// <para>Gets a value indicating whether this converter can /// convert an object to the given destination type using the context.</para> /// </devdoc> public override bool CanConvertTo(ITypeDescriptorContext context, [NotNullWhen(true)] Type? destinationType) { if (destinationType == typeof(InstanceDescriptor)) { return true; } return base.CanConvertTo(context, destinationType); } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.ConvertFrom"]/*' /> /// <devdoc> /// Converts the given object to the converter's native type. /// </devdoc> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string strValue = value as string; if (strValue != null) { string text = strValue.Trim(); if (text.Length == 0) { return null; } else { // Parse 2 integer values. // if (culture == null) { culture = CultureInfo.CurrentCulture; } char sep = culture.TextInfo.ListSeparator[0]; string[] tokens = text.Split(sep); int[] values = new int[tokens.Length]; TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int)); for (int i = 0; i < values.Length; i++) { // Note: ConvertFromString will raise exception if value cannot be converted. values[i] = (int)intConverter.ConvertFromString(context, culture, tokens[i]); } if (values.Length == 2) { return new Size(values[0], values[1]); } else { throw new ArgumentException(SR.Format(SR.TextParseFailedFormat, text, "Width,Height")); } } } return base.ConvertFrom(context, culture, value); } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.ConvertTo"]/*' /> /// <devdoc> /// Converts the given object to another type. The most common types to convert /// are to and from a string object. The default implementation will make a call /// to ToString on the object if the object is valid and if the destination /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// </devdoc> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == null) { throw new ArgumentNullException(nameof(destinationType)); } if (value is Size){ if (destinationType == typeof(string)) { Size size = (Size)value; if (culture == null) { culture = CultureInfo.CurrentCulture; } string sep = culture.TextInfo.ListSeparator + " "; TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int)); string[] args = new string[2]; int nArg = 0; // Note: ConvertToString will raise exception if value cannot be converted. args[nArg++] = intConverter.ConvertToString(context, culture, size.Width); args[nArg++] = intConverter.ConvertToString(context, culture, size.Height); return string.Join(sep, args); } if (destinationType == typeof(InstanceDescriptor)) { Size size = (Size)value; ConstructorInfo ctor = typeof(Size).GetConstructor(new Type[] {typeof(int), typeof(int)}); if (ctor != null) { return new InstanceDescriptor(ctor, new object[] {size.Width, size.Height}); } } } return base.ConvertTo(context, culture, value, destinationType); } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.CreateInstance"]/*' /> /// <devdoc> /// Creates an instance of this type given a set of property values /// for the object. This is useful for objects that are immutable, but still /// want to provide changable properties. /// </devdoc> public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) { if ( propertyValues == null ){ throw new ArgumentNullException( nameof(propertyValues) ); } object width = propertyValues["Width"]; object height = propertyValues["Height"]; if (width == null || height == null || !(width is int) || !(height is int)) { throw new ArgumentException(SR.PropertyValueInvalidEntry); } return new Size((int)width, (int)height); } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.GetCreateInstanceSupported"]/*' /> /// <devdoc> /// Determines if changing a value on this object should require a call to /// CreateInstance to create a new value. /// </devdoc> public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) { return true; } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.GetProperties"]/*' /> /// <devdoc> /// Retrieves the set of properties for this type. By default, a type has /// does not return any properties. An easy implementation of this method /// can just call TypeDescriptor.GetProperties for the correct data type. /// </devdoc> public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(Size), attributes); return props.Sort(new string[] {"Width", "Height"}); } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.GetPropertiesSupported"]/*' /> /// <devdoc> /// Determines if this object supports properties. By default, this /// is false. /// </devdoc> public override bool GetPropertiesSupported(ITypeDescriptorContext context) { return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Drawing { using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.Win32; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Globalization; using System.Reflection; /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter"]/*' /> /// <devdoc> /// SizeConverter is a class that can be used to convert /// Size from one data type to another. Access this /// class through the TypeDescriptor. /// </devdoc> public class SizeConverter : TypeConverter { /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.CanConvertFrom"]/*' /> /// <devdoc> /// Determines if this converter can convert an object in the given source /// type to the native type of the converter. /// </devdoc> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.CanConvertTo"]/*' /> /// <devdoc> /// <para>Gets a value indicating whether this converter can /// convert an object to the given destination type using the context.</para> /// </devdoc> public override bool CanConvertTo(ITypeDescriptorContext context, [NotNullWhen(true)] Type? destinationType) { if (destinationType == typeof(InstanceDescriptor)) { return true; } return base.CanConvertTo(context, destinationType); } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.ConvertFrom"]/*' /> /// <devdoc> /// Converts the given object to the converter's native type. /// </devdoc> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string strValue = value as string; if (strValue != null) { string text = strValue.Trim(); if (text.Length == 0) { return null; } else { // Parse 2 integer values. // if (culture == null) { culture = CultureInfo.CurrentCulture; } char sep = culture.TextInfo.ListSeparator[0]; string[] tokens = text.Split(sep); int[] values = new int[tokens.Length]; TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int)); for (int i = 0; i < values.Length; i++) { // Note: ConvertFromString will raise exception if value cannot be converted. values[i] = (int)intConverter.ConvertFromString(context, culture, tokens[i]); } if (values.Length == 2) { return new Size(values[0], values[1]); } else { throw new ArgumentException(SR.Format(SR.TextParseFailedFormat, text, "Width,Height")); } } } return base.ConvertFrom(context, culture, value); } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.ConvertTo"]/*' /> /// <devdoc> /// Converts the given object to another type. The most common types to convert /// are to and from a string object. The default implementation will make a call /// to ToString on the object if the object is valid and if the destination /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// </devdoc> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == null) { throw new ArgumentNullException(nameof(destinationType)); } if (value is Size){ if (destinationType == typeof(string)) { Size size = (Size)value; if (culture == null) { culture = CultureInfo.CurrentCulture; } string sep = culture.TextInfo.ListSeparator + " "; TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int)); string[] args = new string[2]; int nArg = 0; // Note: ConvertToString will raise exception if value cannot be converted. args[nArg++] = intConverter.ConvertToString(context, culture, size.Width); args[nArg++] = intConverter.ConvertToString(context, culture, size.Height); return string.Join(sep, args); } if (destinationType == typeof(InstanceDescriptor)) { Size size = (Size)value; ConstructorInfo ctor = typeof(Size).GetConstructor(new Type[] {typeof(int), typeof(int)}); if (ctor != null) { return new InstanceDescriptor(ctor, new object[] {size.Width, size.Height}); } } } return base.ConvertTo(context, culture, value, destinationType); } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.CreateInstance"]/*' /> /// <devdoc> /// Creates an instance of this type given a set of property values /// for the object. This is useful for objects that are immutable, but still /// want to provide changable properties. /// </devdoc> public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) { if ( propertyValues == null ){ throw new ArgumentNullException( nameof(propertyValues) ); } object width = propertyValues["Width"]; object height = propertyValues["Height"]; if (width == null || height == null || !(width is int) || !(height is int)) { throw new ArgumentException(SR.PropertyValueInvalidEntry); } return new Size((int)width, (int)height); } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.GetCreateInstanceSupported"]/*' /> /// <devdoc> /// Determines if changing a value on this object should require a call to /// CreateInstance to create a new value. /// </devdoc> public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) { return true; } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.GetProperties"]/*' /> /// <devdoc> /// Retrieves the set of properties for this type. By default, a type has /// does not return any properties. An easy implementation of this method /// can just call TypeDescriptor.GetProperties for the correct data type. /// </devdoc> public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(Size), attributes); return props.Sort(new string[] {"Width", "Height"}); } /// <include file='doc\SizeConverter.uex' path='docs/doc[@for="SizeConverter.GetPropertiesSupported"]/*' /> /// <devdoc> /// Determines if this object supports properties. By default, this /// is false. /// </devdoc> public override bool GetPropertiesSupported(ITypeDescriptorContext context) { return true; } } }
-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.Int16.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_Int16() { var test = new SimpleBinaryOpTest__CompareEqual_Vector64_Int16(); 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_Int16 { 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(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); 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<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, 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<Int16> _fld1; public Vector64<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareEqual_Vector64_Int16 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_Int16 testClass) { fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(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<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector64<Int16> _clsVar1; private static Vector64<Int16> _clsVar2; private Vector64<Int16> _fld1; private Vector64<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareEqual_Vector64_Int16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); } public SimpleBinaryOpTest__CompareEqual_Vector64_Int16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[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<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_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((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_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<Int16>), typeof(Vector64<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(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<Int16>), typeof(Vector64<Int16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(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<Int16>* pClsVar1 = &_clsVar1) fixed (Vector64<Int16>* pClsVar2 = &_clsVar2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((Int16*)(pClsVar1)), AdvSimd.LoadVector64((Int16*)(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<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int16>>(_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((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int16*)(_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_Int16(); 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_Int16(); fixed (Vector64<Int16>* pFld1 = &test._fld1) fixed (Vector64<Int16>* pFld2 = &test._fld2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(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<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(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((Int16*)(&test._fld1)), AdvSimd.LoadVector64((Int16*)(&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<Int16> op1, Vector64<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] 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)}<Int16>(Vector64<Int16>, Vector64<Int16>): {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_Int16() { var test = new SimpleBinaryOpTest__CompareEqual_Vector64_Int16(); 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_Int16 { 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(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); 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<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, 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<Int16> _fld1; public Vector64<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareEqual_Vector64_Int16 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_Int16 testClass) { fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(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<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector64<Int16> _clsVar1; private static Vector64<Int16> _clsVar2; private Vector64<Int16> _fld1; private Vector64<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareEqual_Vector64_Int16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); } public SimpleBinaryOpTest__CompareEqual_Vector64_Int16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[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<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_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((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_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<Int16>), typeof(Vector64<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(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<Int16>), typeof(Vector64<Int16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(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<Int16>* pClsVar1 = &_clsVar1) fixed (Vector64<Int16>* pClsVar2 = &_clsVar2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((Int16*)(pClsVar1)), AdvSimd.LoadVector64((Int16*)(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<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int16>>(_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((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int16*)(_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_Int16(); 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_Int16(); fixed (Vector64<Int16>* pFld1 = &test._fld1) fixed (Vector64<Int16>* pFld2 = &test._fld2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(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<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(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((Int16*)(&test._fld1)), AdvSimd.LoadVector64((Int16*)(&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<Int16> op1, Vector64<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] 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)}<Int16>(Vector64<Int16>, Vector64<Int16>): {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.Runtime/tests/TrimmingTests/DefaultValueAttributeCtorTest.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.Globalization; /// <summary> /// Tests that System.ComponentModel.TypeConverter.ConvertFromInvariantString /// is not trimmed out when needed by DefaultValueAttribute in a trimmed application. /// </summary> class Program { static int Main(string[] args) { TypeDescriptor.AddAttributes(typeof(string), new TypeConverterAttribute(typeof(MyStringConverter))); var attribute = new DefaultValueAttribute(typeof(string), "Hello, world!"); return (string)attribute.Value == "Hello, world!trivia" ? 100 : -1; } private class MyStringConverter : StringConverter { /// <summary> /// Converts the specified value object to a string object. /// </summary> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { return (string)value + "trivia"; } throw new NotSupportedException(); } } }
// 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.Globalization; /// <summary> /// Tests that System.ComponentModel.TypeConverter.ConvertFromInvariantString /// is not trimmed out when needed by DefaultValueAttribute in a trimmed application. /// </summary> class Program { static int Main(string[] args) { TypeDescriptor.AddAttributes(typeof(string), new TypeConverterAttribute(typeof(MyStringConverter))); var attribute = new DefaultValueAttribute(typeof(string), "Hello, world!"); return (string)attribute.Value == "Hello, world!trivia" ? 100 : -1; } private class MyStringConverter : StringConverter { /// <summary> /// Converts the specified value object to a string object. /// </summary> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { return (string)value + "trivia"; } throw new NotSupportedException(); } } }
-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/wasm/debugger/DebuggerTestSuite/AssignmentTests.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.Linq; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using Xunit; namespace DebuggerTests { public class AssignmentTests : DebuggerTestBase { public static TheoryData<string, JObject, JObject> GetTestData => new TheoryData<string, JObject, JObject> { { "MONO_TYPE_OBJECT", TObject("object", is_null: true), TObject("object") }, { "MONO_TYPE_CLASS", TObject("DebuggerTests.MONO_TYPE_CLASS", is_null: true), TObject("DebuggerTests.MONO_TYPE_CLASS") }, { "MONO_TYPE_BOOLEAN", TBool(default), TBool(true) }, { "MONO_TYPE_CHAR", TChar('\u0000'), TChar('a') }, { "MONO_TYPE_STRING", TString(default), TString("hello") }, { "MONO_TYPE_ENUM", TEnum("DebuggerTests.RGB", "Red"), TEnum("DebuggerTests.RGB", "Blue") }, { "MONO_TYPE_ARRAY", TObject("byte[]", is_null: true), TArray("byte[]", "byte[2]") }, { "MONO_TYPE_VALUETYPE", TValueType("DebuggerTests.Point"), TValueType("DebuggerTests.Point") }, { "MONO_TYPE_VALUETYPE2", TValueType("System.Decimal","0"), TValueType("System.Decimal", "1.1") }, { "MONO_TYPE_GENERICINST", TObject("System.Func<int>", is_null: true), TDelegate("System.Func<int>", "int Prepare ()") }, { "MONO_TYPE_FNPTR", TPointer("*()", is_null: true), TPointer("*()") }, { "MONO_TYPE_PTR", TPointer("int*", is_null: true), TPointer("int*") }, { "MONO_TYPE_I1", TNumber(0), TNumber(-1) }, { "MONO_TYPE_I2", TNumber(0), TNumber(-1) }, { "MONO_TYPE_I4", TNumber(0), TNumber(-1) }, { "MONO_TYPE_I8", TNumber(0), TNumber(-1) }, { "MONO_TYPE_U1", TNumber(0), TNumber(1) }, { "MONO_TYPE_U2", TNumber(0), TNumber(1) }, { "MONO_TYPE_U4", TNumber(0), TNumber(1) }, { "MONO_TYPE_U8", TNumber(0), TNumber(1) }, { "MONO_TYPE_R4", TNumber(0), TNumber("3.1415") }, //this is also the value that we see if we debug using VS { "MONO_TYPE_R8", TNumber(0), TNumber("3.1415") }, }; [Theory] [MemberData("GetTestData")] async Task InspectVariableBeforeAndAfterAssignment(string clazz, JObject checkDefault, JObject checkValue) { await SetBreakpointInMethod("debugger-test", "DebuggerTests." + clazz, "Prepare", 2); await EvaluateAndCheck("window.setTimeout(function() { invoke_static_method('[debugger-test] DebuggerTests." + clazz + ":Prepare'); })", null, -1, -1, "Prepare"); // 1) check un-assigned variables await StepAndCheck(StepKind.Into, "dotnet://debugger-test.dll/debugger-assignment-test.cs", -1, -1, "TestedMethod", locals_fn: async (locals) => { Assert.Equal(2, locals.Count()); await Check(locals, "r", checkDefault); await Task.CompletedTask; } ); // 2) check assigned variables await StepAndCheck(StepKind.Over, "dotnet://debugger-test.dll/debugger-assignment-test.cs", -1, -1, "TestedMethod", times: 3, locals_fn: async (locals) => { Assert.Equal(2, locals.Count()); await Check(locals, "r", checkValue); await Task.CompletedTask; } ); } } }
// 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.Linq; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using Xunit; namespace DebuggerTests { public class AssignmentTests : DebuggerTestBase { public static TheoryData<string, JObject, JObject> GetTestData => new TheoryData<string, JObject, JObject> { { "MONO_TYPE_OBJECT", TObject("object", is_null: true), TObject("object") }, { "MONO_TYPE_CLASS", TObject("DebuggerTests.MONO_TYPE_CLASS", is_null: true), TObject("DebuggerTests.MONO_TYPE_CLASS") }, { "MONO_TYPE_BOOLEAN", TBool(default), TBool(true) }, { "MONO_TYPE_CHAR", TChar('\u0000'), TChar('a') }, { "MONO_TYPE_STRING", TString(default), TString("hello") }, { "MONO_TYPE_ENUM", TEnum("DebuggerTests.RGB", "Red"), TEnum("DebuggerTests.RGB", "Blue") }, { "MONO_TYPE_ARRAY", TObject("byte[]", is_null: true), TArray("byte[]", "byte[2]") }, { "MONO_TYPE_VALUETYPE", TValueType("DebuggerTests.Point"), TValueType("DebuggerTests.Point") }, { "MONO_TYPE_VALUETYPE2", TValueType("System.Decimal","0"), TValueType("System.Decimal", "1.1") }, { "MONO_TYPE_GENERICINST", TObject("System.Func<int>", is_null: true), TDelegate("System.Func<int>", "int Prepare ()") }, { "MONO_TYPE_FNPTR", TPointer("*()", is_null: true), TPointer("*()") }, { "MONO_TYPE_PTR", TPointer("int*", is_null: true), TPointer("int*") }, { "MONO_TYPE_I1", TNumber(0), TNumber(-1) }, { "MONO_TYPE_I2", TNumber(0), TNumber(-1) }, { "MONO_TYPE_I4", TNumber(0), TNumber(-1) }, { "MONO_TYPE_I8", TNumber(0), TNumber(-1) }, { "MONO_TYPE_U1", TNumber(0), TNumber(1) }, { "MONO_TYPE_U2", TNumber(0), TNumber(1) }, { "MONO_TYPE_U4", TNumber(0), TNumber(1) }, { "MONO_TYPE_U8", TNumber(0), TNumber(1) }, { "MONO_TYPE_R4", TNumber(0), TNumber("3.1415") }, //this is also the value that we see if we debug using VS { "MONO_TYPE_R8", TNumber(0), TNumber("3.1415") }, }; [Theory] [MemberData("GetTestData")] async Task InspectVariableBeforeAndAfterAssignment(string clazz, JObject checkDefault, JObject checkValue) { await SetBreakpointInMethod("debugger-test", "DebuggerTests." + clazz, "Prepare", 2); await EvaluateAndCheck("window.setTimeout(function() { invoke_static_method('[debugger-test] DebuggerTests." + clazz + ":Prepare'); })", null, -1, -1, "Prepare"); // 1) check un-assigned variables await StepAndCheck(StepKind.Into, "dotnet://debugger-test.dll/debugger-assignment-test.cs", -1, -1, "TestedMethod", locals_fn: async (locals) => { Assert.Equal(2, locals.Count()); await Check(locals, "r", checkDefault); await Task.CompletedTask; } ); // 2) check assigned variables await StepAndCheck(StepKind.Over, "dotnet://debugger-test.dll/debugger-assignment-test.cs", -1, -1, "TestedMethod", times: 3, locals_fn: async (locals) => { Assert.Equal(2, locals.Count()); await Check(locals, "r", checkValue); await Task.CompletedTask; } ); } } }
-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/tests/RevocationTests/DynamicRevocationTests.Android.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.Runtime.CompilerServices; using System.Security.Cryptography.X509Certificates.Tests.Common; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests.RevocationTests { public static partial class DynamicRevocationTests { public static bool SupportsDynamicRevocation { get; } = Interop.AndroidCrypto.X509ChainSupportsRevocationOptions(); } }
// 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.Runtime.CompilerServices; using System.Security.Cryptography.X509Certificates.Tests.Common; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests.RevocationTests { public static partial class DynamicRevocationTests { public static bool SupportsDynamicRevocation { get; } = Interop.AndroidCrypto.X509ChainSupportsRevocationOptions(); } }
-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/Interop/COM/NETServer/ColorTesting.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.Drawing; using System.Runtime.InteropServices; [ComVisible(true)] [Guid(Server.Contract.Guids.ColorTesting)] public class ColorTesting : Server.Contract.IColorTesting { public bool AreColorsEqual(Color managed, int native) => ColorTranslator.ToOle(managed) == native; public Color GetRed() => Color.Red; }
// 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.Drawing; using System.Runtime.InteropServices; [ComVisible(true)] [Guid(Server.Contract.Guids.ColorTesting)] public class ColorTesting : Server.Contract.IColorTesting { public bool AreColorsEqual(Color managed, int native) => ColorTranslator.ToOle(managed) == native; public Color GetRed() => Color.Red; }
-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.Extensions.Configuration.Binder/ref/Microsoft.Extensions.Configuration.Binder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace Microsoft.Extensions.Configuration { public partial class BinderOptions { public BinderOptions() { } public bool BindNonPublicProperties { get { throw null; } set { } } public bool ErrorOnUnknownConfiguration { get { throw null; } set { } } } public static partial class ConfigurationBinder { [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("Cannot statically analyze the type of instance so its members may be trimmed")] public static void Bind(this Microsoft.Extensions.Configuration.IConfiguration configuration, object? instance) { } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("Cannot statically analyze the type of instance so its members may be trimmed")] public static void Bind(this Microsoft.Extensions.Configuration.IConfiguration configuration, object? instance, System.Action<Microsoft.Extensions.Configuration.BinderOptions>? configureOptions) { } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("Cannot statically analyze the type of instance so its members may be trimmed")] public static void Bind(this Microsoft.Extensions.Configuration.IConfiguration configuration, string key, object? instance) { } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static object? Get(this Microsoft.Extensions.Configuration.IConfiguration configuration, System.Type type) { throw null; } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static object? Get(this Microsoft.Extensions.Configuration.IConfiguration configuration, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] System.Type type, System.Action<Microsoft.Extensions.Configuration.BinderOptions>? configureOptions) { throw null; } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static object? GetValue(this Microsoft.Extensions.Configuration.IConfiguration configuration, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] System.Type type, string key) { throw null; } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static object? GetValue(this Microsoft.Extensions.Configuration.IConfiguration configuration, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] System.Type type, string key, object defaultValue) { throw null; } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static T? GetValue<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] T>(this Microsoft.Extensions.Configuration.IConfiguration configuration, string key) { throw null; } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static T? GetValue<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] T>(this Microsoft.Extensions.Configuration.IConfiguration configuration, string key, T defaultValue) { throw null; } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static T? Get<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] T>(this Microsoft.Extensions.Configuration.IConfiguration configuration) { throw null; } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static T? Get<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] T>(this Microsoft.Extensions.Configuration.IConfiguration configuration, System.Action<Microsoft.Extensions.Configuration.BinderOptions>? configureOptions) { throw null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace Microsoft.Extensions.Configuration { public partial class BinderOptions { public BinderOptions() { } public bool BindNonPublicProperties { get { throw null; } set { } } public bool ErrorOnUnknownConfiguration { get { throw null; } set { } } } public static partial class ConfigurationBinder { [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("Cannot statically analyze the type of instance so its members may be trimmed")] public static void Bind(this Microsoft.Extensions.Configuration.IConfiguration configuration, object? instance) { } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("Cannot statically analyze the type of instance so its members may be trimmed")] public static void Bind(this Microsoft.Extensions.Configuration.IConfiguration configuration, object? instance, System.Action<Microsoft.Extensions.Configuration.BinderOptions>? configureOptions) { } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("Cannot statically analyze the type of instance so its members may be trimmed")] public static void Bind(this Microsoft.Extensions.Configuration.IConfiguration configuration, string key, object? instance) { } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static object? Get(this Microsoft.Extensions.Configuration.IConfiguration configuration, System.Type type) { throw null; } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static object? Get(this Microsoft.Extensions.Configuration.IConfiguration configuration, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] System.Type type, System.Action<Microsoft.Extensions.Configuration.BinderOptions>? configureOptions) { throw null; } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static object? GetValue(this Microsoft.Extensions.Configuration.IConfiguration configuration, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] System.Type type, string key) { throw null; } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static object? GetValue(this Microsoft.Extensions.Configuration.IConfiguration configuration, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] System.Type type, string key, object defaultValue) { throw null; } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static T? GetValue<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] T>(this Microsoft.Extensions.Configuration.IConfiguration configuration, string key) { throw null; } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static T? GetValue<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] T>(this Microsoft.Extensions.Configuration.IConfiguration configuration, string key, T defaultValue) { throw null; } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static T? Get<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] T>(this Microsoft.Extensions.Configuration.IConfiguration configuration) { throw null; } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.")] public static T? Get<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All)] T>(this Microsoft.Extensions.Configuration.IConfiguration configuration, System.Action<Microsoft.Extensions.Configuration.BinderOptions>? configureOptions) { throw 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.ComponentModel.TypeConverter/src/System/ComponentModel/DataObjectAttribute.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.CodeAnalysis; namespace System.ComponentModel { [AttributeUsage(AttributeTargets.Class)] public sealed class DataObjectAttribute : Attribute { public static readonly DataObjectAttribute DataObject = new DataObjectAttribute(true); public static readonly DataObjectAttribute NonDataObject = new DataObjectAttribute(false); public static readonly DataObjectAttribute Default = NonDataObject; public DataObjectAttribute() : this(true) { } public DataObjectAttribute(bool isDataObject) { IsDataObject = isDataObject; } public bool IsDataObject { get; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj == this) { return true; } return (obj is DataObjectAttribute other) && (other.IsDataObject == IsDataObject); } public override int GetHashCode() => IsDataObject.GetHashCode(); public override bool IsDefaultAttribute() => Equals(Default); } }
// 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.CodeAnalysis; namespace System.ComponentModel { [AttributeUsage(AttributeTargets.Class)] public sealed class DataObjectAttribute : Attribute { public static readonly DataObjectAttribute DataObject = new DataObjectAttribute(true); public static readonly DataObjectAttribute NonDataObject = new DataObjectAttribute(false); public static readonly DataObjectAttribute Default = NonDataObject; public DataObjectAttribute() : this(true) { } public DataObjectAttribute(bool isDataObject) { IsDataObject = isDataObject; } public bool IsDataObject { get; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj == this) { return true; } return (obj is DataObjectAttribute other) && (other.IsDataObject == IsDataObject); } public override int GetHashCode() => IsDataObject.GetHashCode(); public override bool IsDefaultAttribute() => Equals(Default); } }
-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/Internal/NativeFormat/NativeFormatWriter.Primitives.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.IO; using System.Diagnostics; namespace Internal.NativeFormat { internal struct NativePrimitiveEncoder { private byte[] _buffer; private int _size; public void Init() { _buffer = new byte[128]; _size = 0; } public int Size { get { return _size; } } public void Clear() { _size = 0; } public void RollbackTo(int offset) { _size = offset; } public void WriteByte(byte b) { if (_buffer.Length == _size) Array.Resize(ref _buffer, 2 * _buffer.Length); _buffer[_size++] = b; } public void WriteUInt8(byte value) { WriteByte(value); } public void WriteUInt16(ushort value) { WriteByte((byte)value); WriteByte((byte)(value >> 8)); } public void WriteUInt32(uint value) { WriteByte((byte)value); WriteByte((byte)(value >> 8)); WriteByte((byte)(value >> 16)); WriteByte((byte)(value >> 24)); } public void WriteUInt64(ulong value) { WriteUInt32((uint)value); WriteUInt32((uint)(value >> 32)); } public unsafe void WriteFloat(float value) { WriteUInt32(*((uint*)&value)); } public unsafe void WriteDouble(double value) { WriteUInt64(*((ulong*)&value)); } // // Same encoding as what's used by CTL // public void WriteUnsigned(uint d) { if (d < 128) { WriteByte((byte)(d * 2 + 0)); } else if (d < 128 * 128) { WriteByte((byte)(d * 4 + 1)); WriteByte((byte)(d >> 6)); } else if (d < 128 * 128 * 128) { WriteByte((byte)(d * 8 + 3)); WriteByte((byte)(d >> 5)); WriteByte((byte)(d >> 13)); } else if (d < 128 * 128 * 128 * 128) { WriteByte((byte)(d * 16 + 7)); WriteByte((byte)(d >> 4)); WriteByte((byte)(d >> 12)); WriteByte((byte)(d >> 20)); } else { WriteByte((byte)15); WriteUInt32(d); } } public static int GetUnsignedEncodingSize(uint d) { if (d < 128) return 1; if (d < 128 * 128) return 2; if (d < 128 * 128 * 128) return 3; if (d < 128 * 128 * 128 * 128) return 4; return 5; } public void WriteSigned(int i) { uint d = (uint)i; if (d + 64 < 128) { WriteByte((byte)(d * 2 + 0)); } else if (d + 64 * 128 < 128 * 128) { WriteByte((byte)(d * 4 + 1)); WriteByte((byte)(d >> 6)); } else if (d + 64 * 128 * 128 < 128 * 128 * 128) { WriteByte((byte)(d * 8 + 3)); WriteByte((byte)(d >> 5)); WriteByte((byte)(d >> 13)); } else if (d + 64 * 128 * 128 * 128 < 128 * 128 * 128 * 128) { WriteByte((byte)(d * 16 + 7)); WriteByte((byte)(d >> 4)); WriteByte((byte)(d >> 12)); WriteByte((byte)(d >> 20)); } else { WriteByte((byte)15); WriteUInt32(d); } } public void WriteUnsignedLong(ulong i) { if ((uint)i == i) { WriteUnsigned((uint)i); return; } WriteByte((byte)31); WriteUInt64(i); } public void WriteSignedLong(long i) { if ((int)i == i) { WriteSigned((int)i); return; } WriteByte((byte)31); WriteUInt64((ulong)i); } public void PatchByteAt(int offset, byte value) { Debug.Assert(offset < _size); _buffer[offset] = value; } public void Save(Stream stream) { stream.Write(_buffer, 0, _size); } public unsafe bool Save(byte* stream, int streamLength) { if (streamLength < _size) { Debug.Assert(false); return false; } for (int i = 0; i < _size; i++) stream[i] = _buffer[i]; return true; } public byte[] GetBytes() { byte[] retBuffer = new byte[_size]; for (int i = 0; i < _size; i++) retBuffer[i] = _buffer[i]; return retBuffer; } } }
// 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.IO; using System.Diagnostics; namespace Internal.NativeFormat { internal struct NativePrimitiveEncoder { private byte[] _buffer; private int _size; public void Init() { _buffer = new byte[128]; _size = 0; } public int Size { get { return _size; } } public void Clear() { _size = 0; } public void RollbackTo(int offset) { _size = offset; } public void WriteByte(byte b) { if (_buffer.Length == _size) Array.Resize(ref _buffer, 2 * _buffer.Length); _buffer[_size++] = b; } public void WriteUInt8(byte value) { WriteByte(value); } public void WriteUInt16(ushort value) { WriteByte((byte)value); WriteByte((byte)(value >> 8)); } public void WriteUInt32(uint value) { WriteByte((byte)value); WriteByte((byte)(value >> 8)); WriteByte((byte)(value >> 16)); WriteByte((byte)(value >> 24)); } public void WriteUInt64(ulong value) { WriteUInt32((uint)value); WriteUInt32((uint)(value >> 32)); } public unsafe void WriteFloat(float value) { WriteUInt32(*((uint*)&value)); } public unsafe void WriteDouble(double value) { WriteUInt64(*((ulong*)&value)); } // // Same encoding as what's used by CTL // public void WriteUnsigned(uint d) { if (d < 128) { WriteByte((byte)(d * 2 + 0)); } else if (d < 128 * 128) { WriteByte((byte)(d * 4 + 1)); WriteByte((byte)(d >> 6)); } else if (d < 128 * 128 * 128) { WriteByte((byte)(d * 8 + 3)); WriteByte((byte)(d >> 5)); WriteByte((byte)(d >> 13)); } else if (d < 128 * 128 * 128 * 128) { WriteByte((byte)(d * 16 + 7)); WriteByte((byte)(d >> 4)); WriteByte((byte)(d >> 12)); WriteByte((byte)(d >> 20)); } else { WriteByte((byte)15); WriteUInt32(d); } } public static int GetUnsignedEncodingSize(uint d) { if (d < 128) return 1; if (d < 128 * 128) return 2; if (d < 128 * 128 * 128) return 3; if (d < 128 * 128 * 128 * 128) return 4; return 5; } public void WriteSigned(int i) { uint d = (uint)i; if (d + 64 < 128) { WriteByte((byte)(d * 2 + 0)); } else if (d + 64 * 128 < 128 * 128) { WriteByte((byte)(d * 4 + 1)); WriteByte((byte)(d >> 6)); } else if (d + 64 * 128 * 128 < 128 * 128 * 128) { WriteByte((byte)(d * 8 + 3)); WriteByte((byte)(d >> 5)); WriteByte((byte)(d >> 13)); } else if (d + 64 * 128 * 128 * 128 < 128 * 128 * 128 * 128) { WriteByte((byte)(d * 16 + 7)); WriteByte((byte)(d >> 4)); WriteByte((byte)(d >> 12)); WriteByte((byte)(d >> 20)); } else { WriteByte((byte)15); WriteUInt32(d); } } public void WriteUnsignedLong(ulong i) { if ((uint)i == i) { WriteUnsigned((uint)i); return; } WriteByte((byte)31); WriteUInt64(i); } public void WriteSignedLong(long i) { if ((int)i == i) { WriteSigned((int)i); return; } WriteByte((byte)31); WriteUInt64((ulong)i); } public void PatchByteAt(int offset, byte value) { Debug.Assert(offset < _size); _buffer[offset] = value; } public void Save(Stream stream) { stream.Write(_buffer, 0, _size); } public unsafe bool Save(byte* stream, int streamLength) { if (streamLength < _size) { Debug.Assert(false); return false; } for (int i = 0; i < _size; i++) stream[i] = _buffer[i]; return true; } public byte[] GetBytes() { byte[] retBuffer = new byte[_size]; for (int i = 0; i < _size; i++) retBuffer[i] = _buffer[i]; return retBuffer; } } }
-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/InsertScalar.Vector128.UInt64.1.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 InsertScalar_Vector128_UInt64_1() { var test = new InsertScalarTest__InsertScalar_Vector128_UInt64_1(); 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 InsertScalarTest__InsertScalar_Vector128_UInt64_1 { private struct DataTable { private byte[] inArray1; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(UInt64[] inArray1, UInt64[] inArray3, UInt64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = 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.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<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt64, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.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(); 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<UInt64> _fld1; public Vector64<UInt64> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); return testStruct; } public void RunStructFldScenario(InsertScalarTest__InsertScalar_Vector128_UInt64_1 testClass) { var result = AdvSimd.InsertScalar(_fld1, 1, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(InsertScalarTest__InsertScalar_Vector128_UInt64_1 testClass) { fixed (Vector128<UInt64>* pFld1 = &_fld1) fixed (Vector64<UInt64>* pFld2 = &_fld3) { var result = AdvSimd.InsertScalar( AdvSimd.LoadVector128((UInt64*)pFld1), 1, AdvSimd.LoadVector64((UInt64*)pFld2) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector64<UInt64>>() / sizeof(UInt64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly byte ElementIndex = 1; private static UInt64[] _data1 = new UInt64[Op1ElementCount]; private static UInt64[] _data3 = new UInt64[Op3ElementCount]; private static Vector128<UInt64> _clsVar1; private static Vector64<UInt64> _clsVar3; private Vector128<UInt64> _fld1; private Vector64<UInt64> _fld3; private DataTable _dataTable; static InsertScalarTest__InsertScalar_Vector128_UInt64_1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref _clsVar3), ref Unsafe.As<UInt64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); } public InsertScalarTest__InsertScalar_Vector128_UInt64_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref _fld3), ref Unsafe.As<UInt64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data1, _data3, new UInt64[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.InsertScalar( Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), 1, Unsafe.Read<Vector64<UInt64>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.InsertScalar( AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), 1, AdvSimd.LoadVector64((UInt64*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.InsertScalar), new Type[] { typeof(Vector128<UInt64>), typeof(byte), typeof(Vector64<UInt64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), ElementIndex, Unsafe.Read<Vector64<UInt64>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.InsertScalar), new Type[] { typeof(Vector128<UInt64>), typeof(byte), typeof(Vector64<UInt64>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), ElementIndex, AdvSimd.LoadVector64((UInt64*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.InsertScalar( _clsVar1, 1, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1) fixed (Vector64<UInt64>* pClsVar3 = &_clsVar3) { var result = AdvSimd.InsertScalar( AdvSimd.LoadVector128((UInt64*)(pClsVar1)), 1, AdvSimd.LoadVector64((UInt64*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr); var op3 = Unsafe.Read<Vector64<UInt64>>(_dataTable.inArray3Ptr); var result = AdvSimd.InsertScalar(op1, 1, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)); var op3 = AdvSimd.LoadVector64((UInt64*)(_dataTable.inArray3Ptr)); var result = AdvSimd.InsertScalar(op1, 1, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertScalarTest__InsertScalar_Vector128_UInt64_1(); var result = AdvSimd.InsertScalar(test._fld1, 1, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new InsertScalarTest__InsertScalar_Vector128_UInt64_1(); fixed (Vector128<UInt64>* pFld1 = &test._fld1) fixed (Vector64<UInt64>* pFld2 = &test._fld3) { var result = AdvSimd.InsertScalar( AdvSimd.LoadVector128((UInt64*)pFld1), 1, AdvSimd.LoadVector64((UInt64*)pFld2) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.InsertScalar(_fld1, 1, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt64>* pFld1 = &_fld1) fixed (Vector64<UInt64>* pFld2 = &_fld3) { var result = AdvSimd.InsertScalar( AdvSimd.LoadVector128((UInt64*)pFld1), 1, AdvSimd.LoadVector64((UInt64*)pFld2) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.InsertScalar(test._fld1, 1, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.InsertScalar( AdvSimd.LoadVector128((UInt64*)(&test._fld1)), 1, AdvSimd.LoadVector64((UInt64*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, 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<UInt64> op1, Vector64<UInt64> op3, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray3 = new UInt64[Op3ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op3, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray3 = new UInt64[Op3ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(UInt64[] firstOp, UInt64[] thirdOp, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Insert(firstOp, ElementIndex, thirdOp[0], i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.InsertScalar)}<UInt64>(Vector128<UInt64>, 1, Vector64<UInt64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); 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 InsertScalar_Vector128_UInt64_1() { var test = new InsertScalarTest__InsertScalar_Vector128_UInt64_1(); 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 InsertScalarTest__InsertScalar_Vector128_UInt64_1 { private struct DataTable { private byte[] inArray1; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(UInt64[] inArray1, UInt64[] inArray3, UInt64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = 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.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<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt64, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.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(); 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<UInt64> _fld1; public Vector64<UInt64> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); return testStruct; } public void RunStructFldScenario(InsertScalarTest__InsertScalar_Vector128_UInt64_1 testClass) { var result = AdvSimd.InsertScalar(_fld1, 1, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(InsertScalarTest__InsertScalar_Vector128_UInt64_1 testClass) { fixed (Vector128<UInt64>* pFld1 = &_fld1) fixed (Vector64<UInt64>* pFld2 = &_fld3) { var result = AdvSimd.InsertScalar( AdvSimd.LoadVector128((UInt64*)pFld1), 1, AdvSimd.LoadVector64((UInt64*)pFld2) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector64<UInt64>>() / sizeof(UInt64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly byte ElementIndex = 1; private static UInt64[] _data1 = new UInt64[Op1ElementCount]; private static UInt64[] _data3 = new UInt64[Op3ElementCount]; private static Vector128<UInt64> _clsVar1; private static Vector64<UInt64> _clsVar3; private Vector128<UInt64> _fld1; private Vector64<UInt64> _fld3; private DataTable _dataTable; static InsertScalarTest__InsertScalar_Vector128_UInt64_1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref _clsVar3), ref Unsafe.As<UInt64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); } public InsertScalarTest__InsertScalar_Vector128_UInt64_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt64>, byte>(ref _fld3), ref Unsafe.As<UInt64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data1, _data3, new UInt64[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.InsertScalar( Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), 1, Unsafe.Read<Vector64<UInt64>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.InsertScalar( AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), 1, AdvSimd.LoadVector64((UInt64*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.InsertScalar), new Type[] { typeof(Vector128<UInt64>), typeof(byte), typeof(Vector64<UInt64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), ElementIndex, Unsafe.Read<Vector64<UInt64>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.InsertScalar), new Type[] { typeof(Vector128<UInt64>), typeof(byte), typeof(Vector64<UInt64>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), ElementIndex, AdvSimd.LoadVector64((UInt64*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.InsertScalar( _clsVar1, 1, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1) fixed (Vector64<UInt64>* pClsVar3 = &_clsVar3) { var result = AdvSimd.InsertScalar( AdvSimd.LoadVector128((UInt64*)(pClsVar1)), 1, AdvSimd.LoadVector64((UInt64*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr); var op3 = Unsafe.Read<Vector64<UInt64>>(_dataTable.inArray3Ptr); var result = AdvSimd.InsertScalar(op1, 1, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)); var op3 = AdvSimd.LoadVector64((UInt64*)(_dataTable.inArray3Ptr)); var result = AdvSimd.InsertScalar(op1, 1, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertScalarTest__InsertScalar_Vector128_UInt64_1(); var result = AdvSimd.InsertScalar(test._fld1, 1, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new InsertScalarTest__InsertScalar_Vector128_UInt64_1(); fixed (Vector128<UInt64>* pFld1 = &test._fld1) fixed (Vector64<UInt64>* pFld2 = &test._fld3) { var result = AdvSimd.InsertScalar( AdvSimd.LoadVector128((UInt64*)pFld1), 1, AdvSimd.LoadVector64((UInt64*)pFld2) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.InsertScalar(_fld1, 1, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt64>* pFld1 = &_fld1) fixed (Vector64<UInt64>* pFld2 = &_fld3) { var result = AdvSimd.InsertScalar( AdvSimd.LoadVector128((UInt64*)pFld1), 1, AdvSimd.LoadVector64((UInt64*)pFld2) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.InsertScalar(test._fld1, 1, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.InsertScalar( AdvSimd.LoadVector128((UInt64*)(&test._fld1)), 1, AdvSimd.LoadVector64((UInt64*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, 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<UInt64> op1, Vector64<UInt64> op3, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray3 = new UInt64[Op3ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op3, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray3 = new UInt64[Op3ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector64<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(UInt64[] firstOp, UInt64[] thirdOp, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Insert(firstOp, ElementIndex, thirdOp[0], i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.InsertScalar)}<UInt64>(Vector128<UInt64>, 1, Vector64<UInt64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); 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/Microsoft.Extensions.Logging.Abstractions/src/EventId.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 Microsoft.Extensions.Logging { /// <summary> /// Identifies a logging event. The primary identifier is the "Id" property, with the "Name" property providing a short description of this type of event. /// </summary> public readonly struct EventId : IEquatable<EventId> { /// <summary> /// Implicitly creates an EventId from the given <see cref="int"/>. /// </summary> /// <param name="i">The <see cref="int"/> to convert to an EventId.</param> public static implicit operator EventId(int i) { return new EventId(i); } /// <summary> /// Checks if two specified <see cref="EventId"/> instances have the same value. They are equal if they have the same Id. /// </summary> /// <param name="left">The first <see cref="EventId"/>.</param> /// <param name="right">The second <see cref="EventId"/>.</param> /// <returns><see langword="true" /> if the objects are equal.</returns> public static bool operator ==(EventId left, EventId right) { return left.Equals(right); } /// <summary> /// Checks if two specified <see cref="EventId"/> instances have different values. /// </summary> /// <param name="left">The first <see cref="EventId"/>.</param> /// <param name="right">The second <see cref="EventId"/>.</param> /// <returns><see langword="true" /> if the objects are not equal.</returns> public static bool operator !=(EventId left, EventId right) { return !left.Equals(right); } /// <summary> /// Initializes an instance of the <see cref="EventId"/> struct. /// </summary> /// <param name="id">The numeric identifier for this event.</param> /// <param name="name">The name of this event.</param> public EventId(int id, string? name = null) { Id = id; Name = name; } /// <summary> /// Gets the numeric identifier for this event. /// </summary> public int Id { get; } /// <summary> /// Gets the name of this event. /// </summary> public string? Name { get; } /// <inheritdoc /> public override string ToString() { return Name ?? Id.ToString(); } /// <summary> /// Indicates whether the current object is equal to another object of the same type. Two events are equal if they have the same id. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns><see langword="true" /> if the current object is equal to the other parameter; otherwise, <see langword="false" />.</returns> public bool Equals(EventId other) { return Id == other.Id; } /// <inheritdoc /> public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is null) { return false; } return obj is EventId eventId && Equals(eventId); } /// <inheritdoc /> public override int GetHashCode() { return Id; } } }
// 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 Microsoft.Extensions.Logging { /// <summary> /// Identifies a logging event. The primary identifier is the "Id" property, with the "Name" property providing a short description of this type of event. /// </summary> public readonly struct EventId : IEquatable<EventId> { /// <summary> /// Implicitly creates an EventId from the given <see cref="int"/>. /// </summary> /// <param name="i">The <see cref="int"/> to convert to an EventId.</param> public static implicit operator EventId(int i) { return new EventId(i); } /// <summary> /// Checks if two specified <see cref="EventId"/> instances have the same value. They are equal if they have the same Id. /// </summary> /// <param name="left">The first <see cref="EventId"/>.</param> /// <param name="right">The second <see cref="EventId"/>.</param> /// <returns><see langword="true" /> if the objects are equal.</returns> public static bool operator ==(EventId left, EventId right) { return left.Equals(right); } /// <summary> /// Checks if two specified <see cref="EventId"/> instances have different values. /// </summary> /// <param name="left">The first <see cref="EventId"/>.</param> /// <param name="right">The second <see cref="EventId"/>.</param> /// <returns><see langword="true" /> if the objects are not equal.</returns> public static bool operator !=(EventId left, EventId right) { return !left.Equals(right); } /// <summary> /// Initializes an instance of the <see cref="EventId"/> struct. /// </summary> /// <param name="id">The numeric identifier for this event.</param> /// <param name="name">The name of this event.</param> public EventId(int id, string? name = null) { Id = id; Name = name; } /// <summary> /// Gets the numeric identifier for this event. /// </summary> public int Id { get; } /// <summary> /// Gets the name of this event. /// </summary> public string? Name { get; } /// <inheritdoc /> public override string ToString() { return Name ?? Id.ToString(); } /// <summary> /// Indicates whether the current object is equal to another object of the same type. Two events are equal if they have the same id. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns><see langword="true" /> if the current object is equal to the other parameter; otherwise, <see langword="false" />.</returns> public bool Equals(EventId other) { return Id == other.Id; } /// <inheritdoc /> public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is null) { return false; } return obj is EventId eventId && Equals(eventId); } /// <inheritdoc /> public override int GetHashCode() { return Id; } } }
-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-M09/b14475/b14475.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 DefaultNamespace { public class Bug_Cb4270 { public virtual bool runTest() { char c2 = ' '; Console.WriteLine("Next will fall into 'short' loop"); Console.Out.Flush(); for (short aa = 0; aa <= 128; aa++) { Console.WriteLine("aa==" + aa); Console.Out.Flush(); if (aa <= 127) c2 = (char)aa; if (Char.IsWhiteSpace(c2) == true) { Console.Write("IsWhitespace ::: "); Console.WriteLine("(894f) Whitespace for c2==" + c2); } } return true; } public static int Main(String[] args) { Console.WriteLine("Character.IsWhitespace() -- Bug_Cb4270 runTest started."); (new Bug_Cb4270()).runTest(); 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; namespace DefaultNamespace { public class Bug_Cb4270 { public virtual bool runTest() { char c2 = ' '; Console.WriteLine("Next will fall into 'short' loop"); Console.Out.Flush(); for (short aa = 0; aa <= 128; aa++) { Console.WriteLine("aa==" + aa); Console.Out.Flush(); if (aa <= 127) c2 = (char)aa; if (Char.IsWhiteSpace(c2) == true) { Console.Write("IsWhitespace ::: "); Console.WriteLine("(894f) Whitespace for c2==" + c2); } } return true; } public static int Main(String[] args) { Console.WriteLine("Character.IsWhitespace() -- Bug_Cb4270 runTest started."); (new Bug_Cb4270()).runTest(); 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/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/CompareTest.Vector128.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.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 CompareTest_Vector128_Double() { var test = new SimpleBinaryOpTest__CompareTest_Vector128_Double(); 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__CompareTest_Vector128_Double { 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 != 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<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__CompareTest_Vector128_Double testClass) { var result = AdvSimd.Arm64.CompareTest(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareTest_Vector128_Double testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.CompareTest( AdvSimd.LoadVector128((Double*)(pFld1)), AdvSimd.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__CompareTest_Vector128_Double() { 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__CompareTest_Vector128_Double() { 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 => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.CompareTest( 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 = AdvSimd.Arm64.CompareTest( AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((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(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.CompareTest), 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(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.CompareTest), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((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 = AdvSimd.Arm64.CompareTest( _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 = AdvSimd.Arm64.CompareTest( AdvSimd.LoadVector128((Double*)(pClsVar1)), AdvSimd.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 = AdvSimd.Arm64.CompareTest(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.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.CompareTest(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareTest_Vector128_Double(); var result = AdvSimd.Arm64.CompareTest(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__CompareTest_Vector128_Double(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.CompareTest( AdvSimd.LoadVector128((Double*)(pFld1)), AdvSimd.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 = AdvSimd.Arm64.CompareTest(_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 = AdvSimd.Arm64.CompareTest( AdvSimd.LoadVector128((Double*)(pFld1)), AdvSimd.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 = AdvSimd.Arm64.CompareTest(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.Arm64.CompareTest( AdvSimd.LoadVector128((Double*)(&test._fld1)), AdvSimd.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; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(Helpers.CompareTest(left[i], right[i])) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.CompareTest)}<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.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 CompareTest_Vector128_Double() { var test = new SimpleBinaryOpTest__CompareTest_Vector128_Double(); 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__CompareTest_Vector128_Double { 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 != 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<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__CompareTest_Vector128_Double testClass) { var result = AdvSimd.Arm64.CompareTest(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareTest_Vector128_Double testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.CompareTest( AdvSimd.LoadVector128((Double*)(pFld1)), AdvSimd.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__CompareTest_Vector128_Double() { 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__CompareTest_Vector128_Double() { 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 => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.CompareTest( 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 = AdvSimd.Arm64.CompareTest( AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((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(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.CompareTest), 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(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.CompareTest), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((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 = AdvSimd.Arm64.CompareTest( _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 = AdvSimd.Arm64.CompareTest( AdvSimd.LoadVector128((Double*)(pClsVar1)), AdvSimd.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 = AdvSimd.Arm64.CompareTest(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.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.CompareTest(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareTest_Vector128_Double(); var result = AdvSimd.Arm64.CompareTest(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__CompareTest_Vector128_Double(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.CompareTest( AdvSimd.LoadVector128((Double*)(pFld1)), AdvSimd.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 = AdvSimd.Arm64.CompareTest(_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 = AdvSimd.Arm64.CompareTest( AdvSimd.LoadVector128((Double*)(pFld1)), AdvSimd.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 = AdvSimd.Arm64.CompareTest(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.Arm64.CompareTest( AdvSimd.LoadVector128((Double*)(&test._fld1)), AdvSimd.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; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(Helpers.CompareTest(left[i], right[i])) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.CompareTest)}<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/tests/JIT/HardwareIntrinsics/General/Vector64/Sqrt.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 SqrtSingle() { var test = new VectorUnaryOpTest__SqrtSingle(); // 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__SqrtSingle { 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 Vector64<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<Vector64<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__SqrtSingle testClass) { var result = Vector64.Sqrt(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector64<Single> _clsVar1; private Vector64<Single> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__SqrtSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); } public VectorUnaryOpTest__SqrtSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<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 = Vector64.Sqrt( Unsafe.Read<Vector64<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(Vector64).GetMethod(nameof(Vector64.Sqrt), new Type[] { typeof(Vector64<Single>) }); if (method is null) { method = typeof(Vector64).GetMethod(nameof(Vector64.Sqrt), 1, new Type[] { typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Single)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector64.Sqrt( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr); var result = Vector64.Sqrt(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__SqrtSingle(); var result = Vector64.Sqrt(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector64.Sqrt(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector64.Sqrt(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(Vector64<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<Vector64<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<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (float)(MathF.Sqrt(firstOp[0]))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (float)(MathF.Sqrt(firstOp[i]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.Sqrt)}<Single>(Vector64<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 SqrtSingle() { var test = new VectorUnaryOpTest__SqrtSingle(); // 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__SqrtSingle { 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 Vector64<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<Vector64<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__SqrtSingle testClass) { var result = Vector64.Sqrt(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector64<Single> _clsVar1; private Vector64<Single> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__SqrtSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); } public VectorUnaryOpTest__SqrtSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<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 = Vector64.Sqrt( Unsafe.Read<Vector64<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(Vector64).GetMethod(nameof(Vector64.Sqrt), new Type[] { typeof(Vector64<Single>) }); if (method is null) { method = typeof(Vector64).GetMethod(nameof(Vector64.Sqrt), 1, new Type[] { typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Single)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector64.Sqrt( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr); var result = Vector64.Sqrt(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__SqrtSingle(); var result = Vector64.Sqrt(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector64.Sqrt(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector64.Sqrt(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(Vector64<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<Vector64<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<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (float)(MathF.Sqrt(firstOp[0]))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (float)(MathF.Sqrt(firstOp[i]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.Sqrt)}<Single>(Vector64<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,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.Specialized/src/System/Collections/Specialized/OrderedDictionary.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.Serialization; namespace System.Collections.Specialized { /// <devdoc> /// <para> /// OrderedDictionary offers IDictionary syntax with ordering. Objects /// added or inserted in an IOrderedDictionary must have both a key and an index, and /// can be retrieved by either. /// OrderedDictionary is used by the ParameterCollection because MSAccess relies on ordering of /// parameters, while almost all other DBs do not. DataKeyArray also uses it so /// DataKeys can be retrieved by either their name or their index. /// /// OrderedDictionary implements IDeserializationCallback because it needs to have the /// contained ArrayList and Hashtable deserialized before it tries to get its count and objects. /// </para> /// </devdoc> [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class OrderedDictionary : IOrderedDictionary, ISerializable, IDeserializationCallback { private ArrayList? _objectsArray; private Hashtable? _objectsTable; private int _initialCapacity; private IEqualityComparer? _comparer; private bool _readOnly; private readonly SerializationInfo? _siInfo; //A temporary variable which we need during deserialization. private const string KeyComparerName = "KeyComparer"; // Do not rename (binary serialization) private const string ArrayListName = "ArrayList"; // Do not rename (binary serialization) private const string ReadOnlyName = "ReadOnly"; // Do not rename (binary serialization) private const string InitCapacityName = "InitialCapacity"; // Do not rename (binary serialization) public OrderedDictionary() : this(0) { } public OrderedDictionary(int capacity) : this(capacity, null) { } public OrderedDictionary(IEqualityComparer? comparer) : this(0, comparer) { } public OrderedDictionary(int capacity, IEqualityComparer? comparer) { _initialCapacity = capacity; _comparer = comparer; } private OrderedDictionary(OrderedDictionary dictionary) { Debug.Assert(dictionary != null); _readOnly = true; _objectsArray = dictionary._objectsArray; _objectsTable = dictionary._objectsTable; _comparer = dictionary._comparer; _initialCapacity = dictionary._initialCapacity; } protected OrderedDictionary(SerializationInfo info, StreamingContext context) { // We can't do anything with the keys and values until the entire graph has been deserialized // and getting Counts and objects won't fail. For the time being, we'll just cache this. // The graph is not valid until OnDeserialization has been called. _siInfo = info; } /// <devdoc> /// Gets the size of the table. /// </devdoc> public int Count { get { if (_objectsArray == null) { return 0; } return _objectsArray.Count; } } /// <devdoc> /// Indicates that the collection can grow. /// </devdoc> bool IDictionary.IsFixedSize { get { return _readOnly; } } /// <devdoc> /// Indicates that the collection is not read-only /// </devdoc> public bool IsReadOnly { get { return _readOnly; } } /// <devdoc> /// Indicates that this class is not synchronized /// </devdoc> bool ICollection.IsSynchronized { get { return false; } } /// <devdoc> /// Gets the collection of keys in the table in order. /// </devdoc> public ICollection Keys { get { ArrayList objectsArray = EnsureObjectsArray(); Hashtable objectsTable = EnsureObjectsTable(); return new OrderedDictionaryKeyValueCollection(objectsArray, objectsTable, _comparer); } } private ArrayList EnsureObjectsArray() => _objectsArray ??= new ArrayList(_initialCapacity); private Hashtable EnsureObjectsTable() => _objectsTable ??= new Hashtable(_initialCapacity, _comparer); /// <devdoc> /// The SyncRoot object. Not used because IsSynchronized is false /// </devdoc> object ICollection.SyncRoot => this; /// <devdoc> /// Gets or sets the object at the specified index /// </devdoc> public object? this[int index] { get { ArrayList objectsArray = EnsureObjectsArray(); return ((DictionaryEntry)objectsArray[index]!).Value; } set { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } if (_objectsArray == null || index < 0 || index >= _objectsArray.Count) { throw new ArgumentOutOfRangeException(nameof(index)); } ArrayList objectsArray = EnsureObjectsArray(); Hashtable objectsTable = EnsureObjectsTable(); object key = ((DictionaryEntry)objectsArray[index]!).Key; objectsArray[index] = new DictionaryEntry(key, value); objectsTable[key] = value; } } /// <devdoc> /// Gets or sets the object with the specified key /// </devdoc> public object? this[object key] { get { if (_objectsTable == null) { return null; } return _objectsTable[key]; } set { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } Hashtable objectsTable = EnsureObjectsTable(); if (objectsTable.Contains(key)) { objectsTable[key] = value; ArrayList objectsArray = EnsureObjectsArray(); objectsArray[IndexOfKey(key)] = new DictionaryEntry(key, value); } else { Add(key, value); } } } /// <devdoc> /// Returns an arrayList of the values in the table /// </devdoc> public ICollection Values { get { ArrayList objectsArray = EnsureObjectsArray(); return new OrderedDictionaryKeyValueCollection(objectsArray); } } /// <devdoc> /// Adds a new entry to the table with the lowest-available index. /// </devdoc> public void Add(object key, object? value) { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } Hashtable objectsTable = EnsureObjectsTable(); ArrayList objectsArray = EnsureObjectsArray(); objectsTable.Add(key, value); objectsArray.Add(new DictionaryEntry(key, value)); } /// <devdoc> /// Clears all elements in the table. /// </devdoc> public void Clear() { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } if (_objectsTable != null) { _objectsTable.Clear(); } if (_objectsArray != null) { _objectsArray.Clear(); } } /// <devdoc> /// Returns a readonly OrderedDictionary for the given OrderedDictionary. /// </devdoc> public OrderedDictionary AsReadOnly() { return new OrderedDictionary(this); } /// <devdoc> /// Returns true if the key exists in the table, false otherwise. /// </devdoc> public bool Contains(object key!!) { if (_objectsTable == null) { return false; } return _objectsTable.Contains(key); } /// <devdoc> /// Copies the table to an array. This will not preserve order. /// </devdoc> public void CopyTo(Array array, int index) { Hashtable objectsTable = EnsureObjectsTable(); objectsTable.CopyTo(array, index); } private int IndexOfKey(object key) { if (_objectsArray == null) { return -1; } for (int i = 0; i < _objectsArray.Count; i++) { object o = ((DictionaryEntry)_objectsArray[i]!).Key; if (_comparer != null) { if (_comparer.Equals(o, key)) { return i; } } else { if (o.Equals(key)) { return i; } } } return -1; } /// <devdoc> /// Inserts a new object at the given index with the given key. /// </devdoc> public void Insert(int index, object key, object? value) { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } if (index > Count || index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } Hashtable objectsTable = EnsureObjectsTable(); ArrayList objectsArray = EnsureObjectsArray(); objectsTable.Add(key, value); objectsArray.Insert(index, new DictionaryEntry(key, value)); } /// <devdoc> /// Removes the entry at the given index. /// </devdoc> public void RemoveAt(int index) { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } if (index >= Count || index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } Hashtable objectsTable = EnsureObjectsTable(); ArrayList objectsArray = EnsureObjectsArray(); object key = ((DictionaryEntry)objectsArray[index]!).Key; objectsArray.RemoveAt(index); objectsTable.Remove(key); } /// <devdoc> /// Removes the entry with the given key. /// </devdoc> public void Remove(object key) { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } ArgumentNullException.ThrowIfNull(key); int index = IndexOfKey(key); if (index < 0) { return; } Hashtable objectsTable = EnsureObjectsTable(); ArrayList objectsArray = EnsureObjectsArray(); objectsTable.Remove(key); objectsArray.RemoveAt(index); } #region IDictionary implementation public virtual IDictionaryEnumerator GetEnumerator() { ArrayList objectsArray = EnsureObjectsArray(); return new OrderedDictionaryEnumerator(objectsArray, OrderedDictionaryEnumerator.DictionaryEntry); } #endregion #region IEnumerable implementation IEnumerator IEnumerable.GetEnumerator() { ArrayList objectsArray = EnsureObjectsArray(); return new OrderedDictionaryEnumerator(objectsArray, OrderedDictionaryEnumerator.DictionaryEntry); } #endregion #region ISerializable implementation public virtual void GetObjectData(SerializationInfo info!!, StreamingContext context) { info.AddValue(KeyComparerName, _comparer, typeof(IEqualityComparer)); info.AddValue(ReadOnlyName, _readOnly); info.AddValue(InitCapacityName, _initialCapacity); object[] serArray = new object[Count]; ArrayList objectsArray = EnsureObjectsArray(); objectsArray.CopyTo(serArray); info.AddValue(ArrayListName, serArray); } #endregion #region IDeserializationCallback implementation void IDeserializationCallback.OnDeserialization(object? sender) { OnDeserialization(sender); } protected virtual void OnDeserialization(object? sender) { if (_siInfo == null) { throw new SerializationException(SR.Serialization_InvalidOnDeser); } _comparer = (IEqualityComparer?)_siInfo.GetValue(KeyComparerName, typeof(IEqualityComparer)); _readOnly = _siInfo.GetBoolean(ReadOnlyName); _initialCapacity = _siInfo.GetInt32(InitCapacityName); object[]? serArray = (object[]?)_siInfo.GetValue(ArrayListName, typeof(object[])); if (serArray != null) { Hashtable objectsTable = EnsureObjectsTable(); ArrayList objectsArray = EnsureObjectsArray(); foreach (object o in serArray) { DictionaryEntry entry; try { // DictionaryEntry is a value type, so it can only be casted. entry = (DictionaryEntry)o; } catch { throw new SerializationException(SR.OrderedDictionary_SerializationMismatch); } objectsArray.Add(entry); objectsTable.Add(entry.Key, entry.Value); } } } #endregion /// <devdoc> /// OrderedDictionaryEnumerator works just like any other IDictionaryEnumerator, but it retrieves DictionaryEntries /// in the order by index. /// </devdoc> private sealed class OrderedDictionaryEnumerator : IDictionaryEnumerator { private readonly int _objectReturnType; internal const int Keys = 1; internal const int Values = 2; internal const int DictionaryEntry = 3; private readonly IEnumerator _arrayEnumerator; internal OrderedDictionaryEnumerator(ArrayList array, int objectReturnType) { _arrayEnumerator = array.GetEnumerator(); _objectReturnType = objectReturnType; } /// <devdoc> /// Retrieves the current DictionaryEntry. This is the same as Entry, but not strongly-typed. /// </devdoc> public object? Current { get { Debug.Assert(_arrayEnumerator.Current != null); if (_objectReturnType == Keys) { return ((DictionaryEntry)_arrayEnumerator.Current).Key; } if (_objectReturnType == Values) { return ((DictionaryEntry)_arrayEnumerator.Current).Value; } return Entry; } } /// <devdoc> /// Retrieves the current DictionaryEntry /// </devdoc> public DictionaryEntry Entry { get { Debug.Assert(_arrayEnumerator.Current != null); return new DictionaryEntry(((DictionaryEntry)_arrayEnumerator.Current).Key, ((DictionaryEntry)_arrayEnumerator.Current).Value); } } /// <devdoc> /// Retrieves the key of the current DictionaryEntry /// </devdoc> public object Key { get { Debug.Assert(_arrayEnumerator.Current != null); return ((DictionaryEntry)_arrayEnumerator.Current).Key; } } /// <devdoc> /// Retrieves the value of the current DictionaryEntry /// </devdoc> public object? Value { get { Debug.Assert(_arrayEnumerator.Current != null); return ((DictionaryEntry)_arrayEnumerator.Current).Value; } } /// <devdoc> /// Moves the enumerator pointer to the next member /// </devdoc> public bool MoveNext() { return _arrayEnumerator.MoveNext(); } /// <devdoc> /// Resets the enumerator pointer to the beginning. /// </devdoc> public void Reset() { _arrayEnumerator.Reset(); } } /// <devdoc> /// OrderedDictionaryKeyValueCollection implements IList for the Values and Keys properties /// that is "live"- it will reflect changes to the OrderedDictionary on the collection made after the getter /// was called. /// </devdoc> private sealed class OrderedDictionaryKeyValueCollection : IList { private readonly ArrayList _objects; private readonly Hashtable? _objectsTable; private readonly IEqualityComparer? _comparer; public OrderedDictionaryKeyValueCollection(ArrayList array, Hashtable objectsTable, IEqualityComparer? comparer) { _objects = array; _objectsTable = objectsTable; _comparer = comparer; } public OrderedDictionaryKeyValueCollection(ArrayList array) { _objects = array; } private bool IsKeys => _objectsTable is not null; void ICollection.CopyTo(Array array!!, int index) { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index); foreach (object? o in _objects) { Debug.Assert(o != null); array.SetValue(IsKeys ? ((DictionaryEntry)o).Key : ((DictionaryEntry)o).Value, index); index++; } } int ICollection.Count => _objects.Count; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => _objects.SyncRoot; IEnumerator IEnumerable.GetEnumerator() { return new OrderedDictionaryEnumerator(_objects, IsKeys ? OrderedDictionaryEnumerator.Keys : OrderedDictionaryEnumerator.Values); } bool IList.Contains(object? value) { if (IsKeys) { Debug.Assert(_objectsTable is not null); return value != null && _objectsTable.ContainsKey(value); } foreach (object? o in _objects) { Debug.Assert(o != null); if (object.Equals(((DictionaryEntry)o).Value, value)) { return true; } } return false; } int IList.IndexOf(object? value) { for (int i = 0; i < _objects.Count; i++) { if (IsKeys) { object entryKey = ((DictionaryEntry)_objects[i]!).Key; if (_comparer != null) { if (_comparer.Equals(entryKey, value)) { return i; } } else if (entryKey.Equals(value)) { return i; } } else if (object.Equals(((DictionaryEntry)_objects[i]!).Value, value)) { return i; } } return -1; } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; object? IList.this[int index] { get { DictionaryEntry entry = (DictionaryEntry)_objects[index]!; return IsKeys ? entry.Key : entry.Value; } set => throw new NotSupportedException(GetNotSupportedErrorMessage()); } void IList.Insert(int index, object? value) { throw new NotSupportedException(GetNotSupportedErrorMessage()); } void IList.Remove(object? value) { throw new NotSupportedException(GetNotSupportedErrorMessage()); } void IList.RemoveAt(int index) { throw new NotSupportedException(GetNotSupportedErrorMessage()); } int IList.Add(object? value) { throw new NotSupportedException(GetNotSupportedErrorMessage()); } void IList.Clear() { throw new NotSupportedException(GetNotSupportedErrorMessage()); } private string GetNotSupportedErrorMessage() { return IsKeys ? SR.NotSupported_KeyCollectionSet : SR.NotSupported_ValueCollectionSet; } } } }
// 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.Serialization; namespace System.Collections.Specialized { /// <devdoc> /// <para> /// OrderedDictionary offers IDictionary syntax with ordering. Objects /// added or inserted in an IOrderedDictionary must have both a key and an index, and /// can be retrieved by either. /// OrderedDictionary is used by the ParameterCollection because MSAccess relies on ordering of /// parameters, while almost all other DBs do not. DataKeyArray also uses it so /// DataKeys can be retrieved by either their name or their index. /// /// OrderedDictionary implements IDeserializationCallback because it needs to have the /// contained ArrayList and Hashtable deserialized before it tries to get its count and objects. /// </para> /// </devdoc> [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class OrderedDictionary : IOrderedDictionary, ISerializable, IDeserializationCallback { private ArrayList? _objectsArray; private Hashtable? _objectsTable; private int _initialCapacity; private IEqualityComparer? _comparer; private bool _readOnly; private readonly SerializationInfo? _siInfo; //A temporary variable which we need during deserialization. private const string KeyComparerName = "KeyComparer"; // Do not rename (binary serialization) private const string ArrayListName = "ArrayList"; // Do not rename (binary serialization) private const string ReadOnlyName = "ReadOnly"; // Do not rename (binary serialization) private const string InitCapacityName = "InitialCapacity"; // Do not rename (binary serialization) public OrderedDictionary() : this(0) { } public OrderedDictionary(int capacity) : this(capacity, null) { } public OrderedDictionary(IEqualityComparer? comparer) : this(0, comparer) { } public OrderedDictionary(int capacity, IEqualityComparer? comparer) { _initialCapacity = capacity; _comparer = comparer; } private OrderedDictionary(OrderedDictionary dictionary) { Debug.Assert(dictionary != null); _readOnly = true; _objectsArray = dictionary._objectsArray; _objectsTable = dictionary._objectsTable; _comparer = dictionary._comparer; _initialCapacity = dictionary._initialCapacity; } protected OrderedDictionary(SerializationInfo info, StreamingContext context) { // We can't do anything with the keys and values until the entire graph has been deserialized // and getting Counts and objects won't fail. For the time being, we'll just cache this. // The graph is not valid until OnDeserialization has been called. _siInfo = info; } /// <devdoc> /// Gets the size of the table. /// </devdoc> public int Count { get { if (_objectsArray == null) { return 0; } return _objectsArray.Count; } } /// <devdoc> /// Indicates that the collection can grow. /// </devdoc> bool IDictionary.IsFixedSize { get { return _readOnly; } } /// <devdoc> /// Indicates that the collection is not read-only /// </devdoc> public bool IsReadOnly { get { return _readOnly; } } /// <devdoc> /// Indicates that this class is not synchronized /// </devdoc> bool ICollection.IsSynchronized { get { return false; } } /// <devdoc> /// Gets the collection of keys in the table in order. /// </devdoc> public ICollection Keys { get { ArrayList objectsArray = EnsureObjectsArray(); Hashtable objectsTable = EnsureObjectsTable(); return new OrderedDictionaryKeyValueCollection(objectsArray, objectsTable, _comparer); } } private ArrayList EnsureObjectsArray() => _objectsArray ??= new ArrayList(_initialCapacity); private Hashtable EnsureObjectsTable() => _objectsTable ??= new Hashtable(_initialCapacity, _comparer); /// <devdoc> /// The SyncRoot object. Not used because IsSynchronized is false /// </devdoc> object ICollection.SyncRoot => this; /// <devdoc> /// Gets or sets the object at the specified index /// </devdoc> public object? this[int index] { get { ArrayList objectsArray = EnsureObjectsArray(); return ((DictionaryEntry)objectsArray[index]!).Value; } set { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } if (_objectsArray == null || index < 0 || index >= _objectsArray.Count) { throw new ArgumentOutOfRangeException(nameof(index)); } ArrayList objectsArray = EnsureObjectsArray(); Hashtable objectsTable = EnsureObjectsTable(); object key = ((DictionaryEntry)objectsArray[index]!).Key; objectsArray[index] = new DictionaryEntry(key, value); objectsTable[key] = value; } } /// <devdoc> /// Gets or sets the object with the specified key /// </devdoc> public object? this[object key] { get { if (_objectsTable == null) { return null; } return _objectsTable[key]; } set { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } Hashtable objectsTable = EnsureObjectsTable(); if (objectsTable.Contains(key)) { objectsTable[key] = value; ArrayList objectsArray = EnsureObjectsArray(); objectsArray[IndexOfKey(key)] = new DictionaryEntry(key, value); } else { Add(key, value); } } } /// <devdoc> /// Returns an arrayList of the values in the table /// </devdoc> public ICollection Values { get { ArrayList objectsArray = EnsureObjectsArray(); return new OrderedDictionaryKeyValueCollection(objectsArray); } } /// <devdoc> /// Adds a new entry to the table with the lowest-available index. /// </devdoc> public void Add(object key, object? value) { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } Hashtable objectsTable = EnsureObjectsTable(); ArrayList objectsArray = EnsureObjectsArray(); objectsTable.Add(key, value); objectsArray.Add(new DictionaryEntry(key, value)); } /// <devdoc> /// Clears all elements in the table. /// </devdoc> public void Clear() { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } if (_objectsTable != null) { _objectsTable.Clear(); } if (_objectsArray != null) { _objectsArray.Clear(); } } /// <devdoc> /// Returns a readonly OrderedDictionary for the given OrderedDictionary. /// </devdoc> public OrderedDictionary AsReadOnly() { return new OrderedDictionary(this); } /// <devdoc> /// Returns true if the key exists in the table, false otherwise. /// </devdoc> public bool Contains(object key!!) { if (_objectsTable == null) { return false; } return _objectsTable.Contains(key); } /// <devdoc> /// Copies the table to an array. This will not preserve order. /// </devdoc> public void CopyTo(Array array, int index) { Hashtable objectsTable = EnsureObjectsTable(); objectsTable.CopyTo(array, index); } private int IndexOfKey(object key) { if (_objectsArray == null) { return -1; } for (int i = 0; i < _objectsArray.Count; i++) { object o = ((DictionaryEntry)_objectsArray[i]!).Key; if (_comparer != null) { if (_comparer.Equals(o, key)) { return i; } } else { if (o.Equals(key)) { return i; } } } return -1; } /// <devdoc> /// Inserts a new object at the given index with the given key. /// </devdoc> public void Insert(int index, object key, object? value) { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } if (index > Count || index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } Hashtable objectsTable = EnsureObjectsTable(); ArrayList objectsArray = EnsureObjectsArray(); objectsTable.Add(key, value); objectsArray.Insert(index, new DictionaryEntry(key, value)); } /// <devdoc> /// Removes the entry at the given index. /// </devdoc> public void RemoveAt(int index) { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } if (index >= Count || index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } Hashtable objectsTable = EnsureObjectsTable(); ArrayList objectsArray = EnsureObjectsArray(); object key = ((DictionaryEntry)objectsArray[index]!).Key; objectsArray.RemoveAt(index); objectsTable.Remove(key); } /// <devdoc> /// Removes the entry with the given key. /// </devdoc> public void Remove(object key) { if (_readOnly) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } ArgumentNullException.ThrowIfNull(key); int index = IndexOfKey(key); if (index < 0) { return; } Hashtable objectsTable = EnsureObjectsTable(); ArrayList objectsArray = EnsureObjectsArray(); objectsTable.Remove(key); objectsArray.RemoveAt(index); } #region IDictionary implementation public virtual IDictionaryEnumerator GetEnumerator() { ArrayList objectsArray = EnsureObjectsArray(); return new OrderedDictionaryEnumerator(objectsArray, OrderedDictionaryEnumerator.DictionaryEntry); } #endregion #region IEnumerable implementation IEnumerator IEnumerable.GetEnumerator() { ArrayList objectsArray = EnsureObjectsArray(); return new OrderedDictionaryEnumerator(objectsArray, OrderedDictionaryEnumerator.DictionaryEntry); } #endregion #region ISerializable implementation public virtual void GetObjectData(SerializationInfo info!!, StreamingContext context) { info.AddValue(KeyComparerName, _comparer, typeof(IEqualityComparer)); info.AddValue(ReadOnlyName, _readOnly); info.AddValue(InitCapacityName, _initialCapacity); object[] serArray = new object[Count]; ArrayList objectsArray = EnsureObjectsArray(); objectsArray.CopyTo(serArray); info.AddValue(ArrayListName, serArray); } #endregion #region IDeserializationCallback implementation void IDeserializationCallback.OnDeserialization(object? sender) { OnDeserialization(sender); } protected virtual void OnDeserialization(object? sender) { if (_siInfo == null) { throw new SerializationException(SR.Serialization_InvalidOnDeser); } _comparer = (IEqualityComparer?)_siInfo.GetValue(KeyComparerName, typeof(IEqualityComparer)); _readOnly = _siInfo.GetBoolean(ReadOnlyName); _initialCapacity = _siInfo.GetInt32(InitCapacityName); object[]? serArray = (object[]?)_siInfo.GetValue(ArrayListName, typeof(object[])); if (serArray != null) { Hashtable objectsTable = EnsureObjectsTable(); ArrayList objectsArray = EnsureObjectsArray(); foreach (object o in serArray) { DictionaryEntry entry; try { // DictionaryEntry is a value type, so it can only be casted. entry = (DictionaryEntry)o; } catch { throw new SerializationException(SR.OrderedDictionary_SerializationMismatch); } objectsArray.Add(entry); objectsTable.Add(entry.Key, entry.Value); } } } #endregion /// <devdoc> /// OrderedDictionaryEnumerator works just like any other IDictionaryEnumerator, but it retrieves DictionaryEntries /// in the order by index. /// </devdoc> private sealed class OrderedDictionaryEnumerator : IDictionaryEnumerator { private readonly int _objectReturnType; internal const int Keys = 1; internal const int Values = 2; internal const int DictionaryEntry = 3; private readonly IEnumerator _arrayEnumerator; internal OrderedDictionaryEnumerator(ArrayList array, int objectReturnType) { _arrayEnumerator = array.GetEnumerator(); _objectReturnType = objectReturnType; } /// <devdoc> /// Retrieves the current DictionaryEntry. This is the same as Entry, but not strongly-typed. /// </devdoc> public object? Current { get { Debug.Assert(_arrayEnumerator.Current != null); if (_objectReturnType == Keys) { return ((DictionaryEntry)_arrayEnumerator.Current).Key; } if (_objectReturnType == Values) { return ((DictionaryEntry)_arrayEnumerator.Current).Value; } return Entry; } } /// <devdoc> /// Retrieves the current DictionaryEntry /// </devdoc> public DictionaryEntry Entry { get { Debug.Assert(_arrayEnumerator.Current != null); return new DictionaryEntry(((DictionaryEntry)_arrayEnumerator.Current).Key, ((DictionaryEntry)_arrayEnumerator.Current).Value); } } /// <devdoc> /// Retrieves the key of the current DictionaryEntry /// </devdoc> public object Key { get { Debug.Assert(_arrayEnumerator.Current != null); return ((DictionaryEntry)_arrayEnumerator.Current).Key; } } /// <devdoc> /// Retrieves the value of the current DictionaryEntry /// </devdoc> public object? Value { get { Debug.Assert(_arrayEnumerator.Current != null); return ((DictionaryEntry)_arrayEnumerator.Current).Value; } } /// <devdoc> /// Moves the enumerator pointer to the next member /// </devdoc> public bool MoveNext() { return _arrayEnumerator.MoveNext(); } /// <devdoc> /// Resets the enumerator pointer to the beginning. /// </devdoc> public void Reset() { _arrayEnumerator.Reset(); } } /// <devdoc> /// OrderedDictionaryKeyValueCollection implements IList for the Values and Keys properties /// that is "live"- it will reflect changes to the OrderedDictionary on the collection made after the getter /// was called. /// </devdoc> private sealed class OrderedDictionaryKeyValueCollection : IList { private readonly ArrayList _objects; private readonly Hashtable? _objectsTable; private readonly IEqualityComparer? _comparer; public OrderedDictionaryKeyValueCollection(ArrayList array, Hashtable objectsTable, IEqualityComparer? comparer) { _objects = array; _objectsTable = objectsTable; _comparer = comparer; } public OrderedDictionaryKeyValueCollection(ArrayList array) { _objects = array; } private bool IsKeys => _objectsTable is not null; void ICollection.CopyTo(Array array!!, int index) { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index); foreach (object? o in _objects) { Debug.Assert(o != null); array.SetValue(IsKeys ? ((DictionaryEntry)o).Key : ((DictionaryEntry)o).Value, index); index++; } } int ICollection.Count => _objects.Count; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => _objects.SyncRoot; IEnumerator IEnumerable.GetEnumerator() { return new OrderedDictionaryEnumerator(_objects, IsKeys ? OrderedDictionaryEnumerator.Keys : OrderedDictionaryEnumerator.Values); } bool IList.Contains(object? value) { if (IsKeys) { Debug.Assert(_objectsTable is not null); return value != null && _objectsTable.ContainsKey(value); } foreach (object? o in _objects) { Debug.Assert(o != null); if (object.Equals(((DictionaryEntry)o).Value, value)) { return true; } } return false; } int IList.IndexOf(object? value) { for (int i = 0; i < _objects.Count; i++) { if (IsKeys) { object entryKey = ((DictionaryEntry)_objects[i]!).Key; if (_comparer != null) { if (_comparer.Equals(entryKey, value)) { return i; } } else if (entryKey.Equals(value)) { return i; } } else if (object.Equals(((DictionaryEntry)_objects[i]!).Value, value)) { return i; } } return -1; } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; object? IList.this[int index] { get { DictionaryEntry entry = (DictionaryEntry)_objects[index]!; return IsKeys ? entry.Key : entry.Value; } set => throw new NotSupportedException(GetNotSupportedErrorMessage()); } void IList.Insert(int index, object? value) { throw new NotSupportedException(GetNotSupportedErrorMessage()); } void IList.Remove(object? value) { throw new NotSupportedException(GetNotSupportedErrorMessage()); } void IList.RemoveAt(int index) { throw new NotSupportedException(GetNotSupportedErrorMessage()); } int IList.Add(object? value) { throw new NotSupportedException(GetNotSupportedErrorMessage()); } void IList.Clear() { throw new NotSupportedException(GetNotSupportedErrorMessage()); } private string GetNotSupportedErrorMessage() { return IsKeys ? SR.NotSupported_KeyCollectionSet : SR.NotSupported_ValueCollectionSet; } } } }
-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/jit64/valuetypes/nullable/box-unbox/structdef.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #pragma warning disable 0183 // The given expression is always of the provided ('X') type using System; using System.ComponentModel; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Loader; // primitives / CLR Types // interfaces public interface IEmpty { } public interface INotEmpty { void DoNothing(); } // generic interfaces public interface IEmptyGen<T> { } public interface INotEmptyGen<T> { void DoNothing(); } // struct public struct EmptyStruct { } public struct NotEmptyStruct { public int Field; } public struct NotEmptyStructQ { public int? Field; } public struct NotEmptyStructA { public int[] Field; } public struct NotEmptyStructQA { public int?[] Field; } // generic structs public struct EmptyStructGen<T> { } public struct NotEmptyStructGen<T> { public T Field; } public struct NotEmptyStructConstrainedGen<T> where T : struct { public T Field; } public struct NotEmptyStructConstrainedGenA<T> where T : struct { public T[] Field; } public struct NotEmptyStructConstrainedGenQ<T> where T : struct { public T? Field; } public struct NotEmptyStructConstrainedGenQA<T> where T : struct { public T?[] Field; } // nested struct public struct NestedStruct { public struct Nested { } } public struct NestedStructGen<T> { public struct Nested { } } // struct with Field Offset [StructLayout(LayoutKind.Explicit)] public struct ExplicitFieldOffsetStruct { [FieldOffset(0)] public int Field00; [FieldOffset(0x0f)] public int Field15; } // struct with Attributes internal struct MarshalAsStruct { [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] public string StringField; } // struct implement interfaces internal struct ImplementOneInterface : IEmpty { } internal struct ImplementTwoInterface : IEmpty, INotEmpty { public void DoNothing() { } } internal struct ImplementOneInterfaceGen<T> : IEmptyGen<T> { } internal struct ImplementTwoInterfaceGen<T> : IEmptyGen<T>, INotEmptyGen<T> { public void DoNothing() { } } internal struct ImplementAllInterface<T> : IEmpty, INotEmpty, IEmptyGen<T>, INotEmptyGen<T> { public void DoNothing() { } void INotEmptyGen<T>.DoNothing() { } } // enums public enum IntE { start = 1, } public enum ByteE : byte { start = 1, } public enum LongE : long { start = 1, } // other intersting structs public struct WithMultipleGCHandleStruct { public GCHandle H1; public GCHandle H2; public GCHandle H3; public GCHandle H4; public GCHandle H5; } public struct WithOnlyFXTypeStruct { public Guid GUID; public decimal DECIMAL; } public struct MixedAllStruct { public int INT; public int? IntQ; public int?[] IntQA; public string STRING; public IntE INTE; public EmptyClass EMPTYCLASS; public IEmpty IEMPTY; public EmptyStruct EMPTYSTRUCT; public IEmptyGen<int> IEMPTYGEN; public EmptyStructGen<int> EMPTYSTRUCTGEN; public WithOnlyFXTypeStruct WITHONLYFXTYPESTRUCT; public GCHandle GCHANDLE; } // other types public struct EmptyClass { } public struct NotEmptyClass { public int Field; } public struct EmptyClassGen<T> { } public struct NotEmptyClassGen<T> { public T Field; } public struct NotEmptyClassConstrainedGen<T> where T : class { public T Field; } public struct NestedClass { public struct Nested { } } public struct NestedClassGen<T> { public struct Nested { } } internal class ImplementOneInterfaceC : IEmpty { } internal class ImplementTwoInterfaceC : IEmpty, INotEmpty { public void DoNothing() { } } internal class ImplementOneInterfaceGenC<T> : IEmptyGen<T> { } internal class ImplementTwoInterfaceGenC<T> : IEmptyGen<T>, INotEmptyGen<T> { public void DoNothing() { } } internal class ImplementAllInterfaceC<T> : IEmpty, INotEmpty, IEmptyGen<T>, INotEmptyGen<T> { public void DoNothing() { } void INotEmptyGen<T>.DoNothing() { } } public sealed class SealedClass { } public delegate void SimpleDelegate(); public delegate void GenericDelegate<T>(); // ExitCode public static class ExitCode { public static int Failed = 101; public static int Passed = 100; } // Create Value Instance internal static class Helper { public static GCHandle GCHANDLE; static Helper() { GCHANDLE = GCHandle.Alloc(Console.Out); AssemblyLoadContext currentContext = AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly()); if (currentContext != null) { currentContext.Unloading += Context_Unloading; } } private static void Context_Unloading(AssemblyLoadContext obj) { GCHANDLE.Free(); } public static char Create(char val) { return 'c'; } public static bool Create(bool val) { return true; } public static byte Create(byte val) { return 0x08; } public static sbyte Create(sbyte val) { return -0x0e; } public static short Create(short val) { return -0x0f; } public static ushort Create(ushort val) { return 0xff; } public static int Create(int val) { return 100; } public static uint Create(uint val) { return 200; } public static long Create(long val) { return int.MaxValue; } public static ulong Create(ulong val) { return 300; } public static float Create(float val) { return 1.15f; } public static double Create(double val) { return 0.05; } public static decimal Create(decimal val) { return 1.0M; } public static IntPtr Create(IntPtr val) { return (IntPtr)1000; } public static UIntPtr Create(UIntPtr val) { return (UIntPtr)2000; } public static Guid Create(Guid val) { return new Guid("00020810-0001-0000-C000-000000000046"); } public static GCHandle Create(GCHandle val) { return GCHANDLE; } public static ByteE Create(ByteE val) { return (ByteE)9; } public static IntE Create(IntE val) { return (IntE)55; } public static LongE Create(LongE val) { return (LongE)34; } public static EmptyStruct Create(EmptyStruct val) { return new EmptyStruct(); } public static NotEmptyStruct Create(NotEmptyStruct val) { NotEmptyStruct ne = new NotEmptyStruct(); ne.Field = 100; return ne; } public static NotEmptyStructQ Create(NotEmptyStructQ val) { NotEmptyStructQ neq = new NotEmptyStructQ(); neq.Field = 101; return neq; } public static NotEmptyStructA Create(NotEmptyStructA val) { NotEmptyStructA nea = new NotEmptyStructA(); nea.Field = new int[] { 10 }; return nea; } public static NotEmptyStructQA Create(NotEmptyStructQA val) { NotEmptyStructQA neq = new NotEmptyStructQA(); neq.Field = new int?[] { 10 }; return neq; } public static EmptyStructGen<int> Create(EmptyStructGen<int> val) { return new EmptyStructGen<int>(); } public static NotEmptyStructGen<int> Create(NotEmptyStructGen<int> val) { NotEmptyStructGen<int> ne = new NotEmptyStructGen<int>(); ne.Field = 88; return ne; } public static NotEmptyStructConstrainedGen<int> Create(NotEmptyStructConstrainedGen<int> val) { NotEmptyStructConstrainedGen<int> ne = new NotEmptyStructConstrainedGen<int>(); ne.Field = 1010; return ne; } public static NotEmptyStructConstrainedGenA<int> Create(NotEmptyStructConstrainedGenA<int> val) { NotEmptyStructConstrainedGenA<int> neq = new NotEmptyStructConstrainedGenA<int>(); neq.Field = new int[] { 11 }; return neq; } public static NotEmptyStructConstrainedGenQ<int> Create(NotEmptyStructConstrainedGenQ<int> val) { NotEmptyStructConstrainedGenQ<int> neq = new NotEmptyStructConstrainedGenQ<int>(); neq.Field = 12; return neq; } public static NotEmptyStructConstrainedGenQA<int> Create(NotEmptyStructConstrainedGenQA<int> val) { NotEmptyStructConstrainedGenQA<int> neq = new NotEmptyStructConstrainedGenQA<int>(); neq.Field = new int?[] { 17 }; return neq; } public static NestedStruct Create(NestedStruct val) { NestedStruct ns = new NestedStruct(); return ns; } public static NestedStructGen<int> Create(NestedStructGen<int> val) { NestedStructGen<int> nsg = new NestedStructGen<int>(); return nsg; } public static ExplicitFieldOffsetStruct Create(ExplicitFieldOffsetStruct val) { ExplicitFieldOffsetStruct epl = new ExplicitFieldOffsetStruct(); epl.Field00 = 40; epl.Field15 = 15; return epl; } public static MarshalAsStruct Create(MarshalAsStruct val) { MarshalAsStruct ma = new MarshalAsStruct(); ma.StringField = "Nullable"; return ma; } public static ImplementOneInterface Create(ImplementOneInterface val) { ImplementOneInterface imp = new ImplementOneInterface(); return imp; } public static ImplementTwoInterface Create(ImplementTwoInterface val) { ImplementTwoInterface imp = new ImplementTwoInterface(); return imp; } public static ImplementOneInterfaceGen<int> Create(ImplementOneInterfaceGen<int> val) { ImplementOneInterfaceGen<int> imp = new ImplementOneInterfaceGen<int>(); return imp; } public static ImplementTwoInterfaceGen<int> Create(ImplementTwoInterfaceGen<int> val) { ImplementTwoInterfaceGen<int> imp = new ImplementTwoInterfaceGen<int>(); return imp; } public static ImplementAllInterface<int> Create(ImplementAllInterface<int> val) { ImplementAllInterface<int> imp = new ImplementAllInterface<int>(); return imp; } public static WithMultipleGCHandleStruct Create(WithMultipleGCHandleStruct val) { WithMultipleGCHandleStruct mgch = new WithMultipleGCHandleStruct(); mgch.H1 = GCHANDLE; mgch.H2 = GCHANDLE; mgch.H3 = GCHANDLE; mgch.H4 = GCHANDLE; mgch.H5 = GCHANDLE; return mgch; } public static WithOnlyFXTypeStruct Create(WithOnlyFXTypeStruct val) { WithOnlyFXTypeStruct wofx = new WithOnlyFXTypeStruct(); wofx.DECIMAL = 50.0m; wofx.GUID = Create(default(Guid)); return wofx; } public static MixedAllStruct Create(MixedAllStruct val) { MixedAllStruct mas; mas.INT = 10; mas.IntQ = null; mas.IntQA = new int?[] { 10 }; mas.STRING = "Nullable"; mas.INTE = Create(default(IntE)); mas.EMPTYCLASS = new EmptyClass(); mas.IEMPTY = Create(default(ImplementOneInterface)); mas.EMPTYSTRUCT = Create(default(EmptyStruct)); mas.IEMPTYGEN = Create(default(ImplementOneInterfaceGen<int>)); mas.EMPTYSTRUCTGEN = Create(default(EmptyStructGen<int>)); mas.WITHONLYFXTYPESTRUCT = Create(default(WithOnlyFXTypeStruct)); mas.GCHANDLE = Create(default(GCHandle)); return mas; } public static bool Compare(char val, char val1) { return val == val1; } public static bool Compare(bool val, bool val1) { return val == val1; } public static bool Compare(byte val, byte val1) { return val == val1; } public static bool Compare(sbyte val, sbyte val1) { return val == val1; } public static bool Compare(short val, short val1) { return val == val1; } public static bool Compare(ushort val, ushort val1) { return val == val1; } public static bool Compare(int val, int val1) { return val == val1; } public static bool Compare(uint val, uint val1) { return val == val1; } public static bool Compare(long val, long val1) { return val == val1; } public static bool Compare(ulong val, ulong val1) { return val == val1; } public static bool Compare(float val, float val1) { return val == val1; } public static bool Compare(double val, double val1) { return val == val1; } public static bool Compare(decimal val, decimal val1) { return val == val1; } public static bool Compare(IntPtr val, IntPtr val1) { return val == val1; } public static bool Compare(UIntPtr val, UIntPtr val1) { return val == val1; } public static bool Compare(Guid val, Guid val1) { return val == val1; } public static bool Compare(GCHandle val, GCHandle val1) { return val == val1; } public static bool Compare(ByteE val, ByteE val1) { return val == val1; } public static bool Compare(IntE val, IntE val1) { return val == val1; } public static bool Compare(LongE val, LongE val1) { return val == val1; } public static bool Compare(EmptyStruct val, EmptyStruct val1) { return val.Equals(val1); } public static bool Compare(NotEmptyStruct val, NotEmptyStruct val1) { return val.Field == val1.Field; } public static bool Compare(NotEmptyStructQ val, NotEmptyStructQ val1) { return val.Field == val1.Field; } public static bool Compare(NotEmptyStructA val, NotEmptyStructA val1) { return val.Field[0] == val1.Field[0]; } public static bool Compare(NotEmptyStructQA val, NotEmptyStructQA val1) { return val.Field[0] == val1.Field[0]; } public static bool Compare(EmptyStructGen<int> val, EmptyStructGen<int> val1) { return val.Equals(val1); } public static bool Compare(NotEmptyStructGen<int> val, NotEmptyStructGen<int> val1) { return val.Field == val1.Field; } public static bool Compare(NotEmptyStructConstrainedGen<int> val, NotEmptyStructConstrainedGen<int> val1) { return val.Field == val1.Field; } public static bool Compare(NotEmptyStructConstrainedGenA<int> val, NotEmptyStructConstrainedGenA<int> val1) { return val.Field[0] == val1.Field[0]; } public static bool Compare(NotEmptyStructConstrainedGenQ<int> val, NotEmptyStructConstrainedGenQ<int> val1) { return val.Field == val1.Field; } public static bool Compare(NotEmptyStructConstrainedGenQA<int> val, NotEmptyStructConstrainedGenQA<int> val1) { return val.Field[0] == val1.Field[0]; } public static bool Compare(NestedStruct val, NestedStruct val1) { return val.Equals(val1); } public static bool Compare(NestedStructGen<int> val, NestedStructGen<int> val1) { return val.Equals(val1); } public static bool Compare(ExplicitFieldOffsetStruct val, ExplicitFieldOffsetStruct val1) { return (val.Field00 == val1.Field00) && (val.Field15 == val1.Field15); } public static bool Compare(MarshalAsStruct val, MarshalAsStruct val1) { return val.Equals(val1); } public static bool Compare(ImplementOneInterface val, ImplementOneInterface val1) { return (val is IEmpty) && val.Equals(val1); } public static bool Compare(ImplementTwoInterface val, ImplementTwoInterface val1) { return (val is IEmpty) && val is INotEmpty && val.Equals(val1); } public static bool Compare(ImplementOneInterfaceGen<int> val, ImplementOneInterfaceGen<int> val1) { return val is IEmptyGen<int> && val.Equals(val1); } public static bool Compare(ImplementTwoInterfaceGen<int> val, ImplementTwoInterfaceGen<int> val1) { return val is IEmptyGen<int> && val is INotEmptyGen<int> && val.Equals(val1); } public static bool Compare(ImplementAllInterface<int> val, ImplementAllInterface<int> val1) { return val is IEmpty && val is INotEmpty && val is IEmptyGen<int> && val is INotEmptyGen<int> && val.Equals(val1); } public static bool Compare(WithMultipleGCHandleStruct val, WithMultipleGCHandleStruct val1) { return val.H1 == val1.H1 && val.H2 == val1.H2 && val.H3 == val1.H3 && val.H4 == val1.H4 && val.H5 == val1.H5; } public static bool Compare(WithOnlyFXTypeStruct val, WithOnlyFXTypeStruct val1) { return val.GUID == val1.GUID && val.DECIMAL == val1.DECIMAL; } public static bool Compare(MixedAllStruct val, MixedAllStruct val1) { return val.INT == val1.INT && val.IntQ == val1.IntQ && val.IntQA[0] == val1.IntQA[0] && val.STRING == val1.STRING && val.INTE == val1.INTE && val.EMPTYCLASS.Equals(val1.EMPTYCLASS) && val.IEMPTY.Equals(val1.IEMPTY) && Compare(val.EMPTYSTRUCT, val1.EMPTYSTRUCT) && val.IEMPTYGEN.Equals(val1.IEMPTYGEN) && Compare(val.EMPTYSTRUCTGEN, val1.EMPTYSTRUCTGEN) && Compare(val.WITHONLYFXTYPESTRUCT, val1.WITHONLYFXTYPESTRUCT) && Compare(val.GCHANDLE, val1.GCHANDLE); } public static bool Compare(char? val, char val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(bool? val, bool val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(byte? val, byte val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(sbyte? val, sbyte val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(short? val, short val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ushort? val, ushort val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(int? val, int val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(uint? val, uint val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(long? val, long val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ulong? val, ulong val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(float? val, float val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(double? val, double val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(decimal? val, decimal val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(IntPtr? val, IntPtr val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(UIntPtr? val, UIntPtr val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(Guid? val, Guid val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(GCHandle? val, GCHandle val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ByteE? val, ByteE val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(IntE? val, IntE val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(LongE? val, LongE val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(EmptyStruct? val, EmptyStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStruct? val, NotEmptyStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructQ? val, NotEmptyStructQ val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructA? val, NotEmptyStructA val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructQA? val, NotEmptyStructQA val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(EmptyStructGen<int>? val, EmptyStructGen<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructGen<int>? val, NotEmptyStructGen<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructConstrainedGen<int>? val, NotEmptyStructConstrainedGen<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructConstrainedGenA<int>? val, NotEmptyStructConstrainedGenA<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructConstrainedGenQ<int>? val, NotEmptyStructConstrainedGenQ<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructConstrainedGenQA<int>? val, NotEmptyStructConstrainedGenQA<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NestedStruct? val, NestedStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NestedStructGen<int>? val, NestedStructGen<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ExplicitFieldOffsetStruct? val, ExplicitFieldOffsetStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(MarshalAsStruct? val, MarshalAsStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ImplementOneInterface? val, ImplementOneInterface val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ImplementTwoInterface? val, ImplementTwoInterface val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ImplementOneInterfaceGen<int>? val, ImplementOneInterfaceGen<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ImplementTwoInterfaceGen<int>? val, ImplementTwoInterfaceGen<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ImplementAllInterface<int>? val, ImplementAllInterface<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(WithMultipleGCHandleStruct? val, WithMultipleGCHandleStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(WithOnlyFXTypeStruct? val, WithOnlyFXTypeStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(MixedAllStruct? val, MixedAllStruct val1) { return val == null ? false : Compare(val.Value, val1); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #pragma warning disable 0183 // The given expression is always of the provided ('X') type using System; using System.ComponentModel; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Loader; // primitives / CLR Types // interfaces public interface IEmpty { } public interface INotEmpty { void DoNothing(); } // generic interfaces public interface IEmptyGen<T> { } public interface INotEmptyGen<T> { void DoNothing(); } // struct public struct EmptyStruct { } public struct NotEmptyStruct { public int Field; } public struct NotEmptyStructQ { public int? Field; } public struct NotEmptyStructA { public int[] Field; } public struct NotEmptyStructQA { public int?[] Field; } // generic structs public struct EmptyStructGen<T> { } public struct NotEmptyStructGen<T> { public T Field; } public struct NotEmptyStructConstrainedGen<T> where T : struct { public T Field; } public struct NotEmptyStructConstrainedGenA<T> where T : struct { public T[] Field; } public struct NotEmptyStructConstrainedGenQ<T> where T : struct { public T? Field; } public struct NotEmptyStructConstrainedGenQA<T> where T : struct { public T?[] Field; } // nested struct public struct NestedStruct { public struct Nested { } } public struct NestedStructGen<T> { public struct Nested { } } // struct with Field Offset [StructLayout(LayoutKind.Explicit)] public struct ExplicitFieldOffsetStruct { [FieldOffset(0)] public int Field00; [FieldOffset(0x0f)] public int Field15; } // struct with Attributes internal struct MarshalAsStruct { [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] public string StringField; } // struct implement interfaces internal struct ImplementOneInterface : IEmpty { } internal struct ImplementTwoInterface : IEmpty, INotEmpty { public void DoNothing() { } } internal struct ImplementOneInterfaceGen<T> : IEmptyGen<T> { } internal struct ImplementTwoInterfaceGen<T> : IEmptyGen<T>, INotEmptyGen<T> { public void DoNothing() { } } internal struct ImplementAllInterface<T> : IEmpty, INotEmpty, IEmptyGen<T>, INotEmptyGen<T> { public void DoNothing() { } void INotEmptyGen<T>.DoNothing() { } } // enums public enum IntE { start = 1, } public enum ByteE : byte { start = 1, } public enum LongE : long { start = 1, } // other intersting structs public struct WithMultipleGCHandleStruct { public GCHandle H1; public GCHandle H2; public GCHandle H3; public GCHandle H4; public GCHandle H5; } public struct WithOnlyFXTypeStruct { public Guid GUID; public decimal DECIMAL; } public struct MixedAllStruct { public int INT; public int? IntQ; public int?[] IntQA; public string STRING; public IntE INTE; public EmptyClass EMPTYCLASS; public IEmpty IEMPTY; public EmptyStruct EMPTYSTRUCT; public IEmptyGen<int> IEMPTYGEN; public EmptyStructGen<int> EMPTYSTRUCTGEN; public WithOnlyFXTypeStruct WITHONLYFXTYPESTRUCT; public GCHandle GCHANDLE; } // other types public struct EmptyClass { } public struct NotEmptyClass { public int Field; } public struct EmptyClassGen<T> { } public struct NotEmptyClassGen<T> { public T Field; } public struct NotEmptyClassConstrainedGen<T> where T : class { public T Field; } public struct NestedClass { public struct Nested { } } public struct NestedClassGen<T> { public struct Nested { } } internal class ImplementOneInterfaceC : IEmpty { } internal class ImplementTwoInterfaceC : IEmpty, INotEmpty { public void DoNothing() { } } internal class ImplementOneInterfaceGenC<T> : IEmptyGen<T> { } internal class ImplementTwoInterfaceGenC<T> : IEmptyGen<T>, INotEmptyGen<T> { public void DoNothing() { } } internal class ImplementAllInterfaceC<T> : IEmpty, INotEmpty, IEmptyGen<T>, INotEmptyGen<T> { public void DoNothing() { } void INotEmptyGen<T>.DoNothing() { } } public sealed class SealedClass { } public delegate void SimpleDelegate(); public delegate void GenericDelegate<T>(); // ExitCode public static class ExitCode { public static int Failed = 101; public static int Passed = 100; } // Create Value Instance internal static class Helper { public static GCHandle GCHANDLE; static Helper() { GCHANDLE = GCHandle.Alloc(Console.Out); AssemblyLoadContext currentContext = AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly()); if (currentContext != null) { currentContext.Unloading += Context_Unloading; } } private static void Context_Unloading(AssemblyLoadContext obj) { GCHANDLE.Free(); } public static char Create(char val) { return 'c'; } public static bool Create(bool val) { return true; } public static byte Create(byte val) { return 0x08; } public static sbyte Create(sbyte val) { return -0x0e; } public static short Create(short val) { return -0x0f; } public static ushort Create(ushort val) { return 0xff; } public static int Create(int val) { return 100; } public static uint Create(uint val) { return 200; } public static long Create(long val) { return int.MaxValue; } public static ulong Create(ulong val) { return 300; } public static float Create(float val) { return 1.15f; } public static double Create(double val) { return 0.05; } public static decimal Create(decimal val) { return 1.0M; } public static IntPtr Create(IntPtr val) { return (IntPtr)1000; } public static UIntPtr Create(UIntPtr val) { return (UIntPtr)2000; } public static Guid Create(Guid val) { return new Guid("00020810-0001-0000-C000-000000000046"); } public static GCHandle Create(GCHandle val) { return GCHANDLE; } public static ByteE Create(ByteE val) { return (ByteE)9; } public static IntE Create(IntE val) { return (IntE)55; } public static LongE Create(LongE val) { return (LongE)34; } public static EmptyStruct Create(EmptyStruct val) { return new EmptyStruct(); } public static NotEmptyStruct Create(NotEmptyStruct val) { NotEmptyStruct ne = new NotEmptyStruct(); ne.Field = 100; return ne; } public static NotEmptyStructQ Create(NotEmptyStructQ val) { NotEmptyStructQ neq = new NotEmptyStructQ(); neq.Field = 101; return neq; } public static NotEmptyStructA Create(NotEmptyStructA val) { NotEmptyStructA nea = new NotEmptyStructA(); nea.Field = new int[] { 10 }; return nea; } public static NotEmptyStructQA Create(NotEmptyStructQA val) { NotEmptyStructQA neq = new NotEmptyStructQA(); neq.Field = new int?[] { 10 }; return neq; } public static EmptyStructGen<int> Create(EmptyStructGen<int> val) { return new EmptyStructGen<int>(); } public static NotEmptyStructGen<int> Create(NotEmptyStructGen<int> val) { NotEmptyStructGen<int> ne = new NotEmptyStructGen<int>(); ne.Field = 88; return ne; } public static NotEmptyStructConstrainedGen<int> Create(NotEmptyStructConstrainedGen<int> val) { NotEmptyStructConstrainedGen<int> ne = new NotEmptyStructConstrainedGen<int>(); ne.Field = 1010; return ne; } public static NotEmptyStructConstrainedGenA<int> Create(NotEmptyStructConstrainedGenA<int> val) { NotEmptyStructConstrainedGenA<int> neq = new NotEmptyStructConstrainedGenA<int>(); neq.Field = new int[] { 11 }; return neq; } public static NotEmptyStructConstrainedGenQ<int> Create(NotEmptyStructConstrainedGenQ<int> val) { NotEmptyStructConstrainedGenQ<int> neq = new NotEmptyStructConstrainedGenQ<int>(); neq.Field = 12; return neq; } public static NotEmptyStructConstrainedGenQA<int> Create(NotEmptyStructConstrainedGenQA<int> val) { NotEmptyStructConstrainedGenQA<int> neq = new NotEmptyStructConstrainedGenQA<int>(); neq.Field = new int?[] { 17 }; return neq; } public static NestedStruct Create(NestedStruct val) { NestedStruct ns = new NestedStruct(); return ns; } public static NestedStructGen<int> Create(NestedStructGen<int> val) { NestedStructGen<int> nsg = new NestedStructGen<int>(); return nsg; } public static ExplicitFieldOffsetStruct Create(ExplicitFieldOffsetStruct val) { ExplicitFieldOffsetStruct epl = new ExplicitFieldOffsetStruct(); epl.Field00 = 40; epl.Field15 = 15; return epl; } public static MarshalAsStruct Create(MarshalAsStruct val) { MarshalAsStruct ma = new MarshalAsStruct(); ma.StringField = "Nullable"; return ma; } public static ImplementOneInterface Create(ImplementOneInterface val) { ImplementOneInterface imp = new ImplementOneInterface(); return imp; } public static ImplementTwoInterface Create(ImplementTwoInterface val) { ImplementTwoInterface imp = new ImplementTwoInterface(); return imp; } public static ImplementOneInterfaceGen<int> Create(ImplementOneInterfaceGen<int> val) { ImplementOneInterfaceGen<int> imp = new ImplementOneInterfaceGen<int>(); return imp; } public static ImplementTwoInterfaceGen<int> Create(ImplementTwoInterfaceGen<int> val) { ImplementTwoInterfaceGen<int> imp = new ImplementTwoInterfaceGen<int>(); return imp; } public static ImplementAllInterface<int> Create(ImplementAllInterface<int> val) { ImplementAllInterface<int> imp = new ImplementAllInterface<int>(); return imp; } public static WithMultipleGCHandleStruct Create(WithMultipleGCHandleStruct val) { WithMultipleGCHandleStruct mgch = new WithMultipleGCHandleStruct(); mgch.H1 = GCHANDLE; mgch.H2 = GCHANDLE; mgch.H3 = GCHANDLE; mgch.H4 = GCHANDLE; mgch.H5 = GCHANDLE; return mgch; } public static WithOnlyFXTypeStruct Create(WithOnlyFXTypeStruct val) { WithOnlyFXTypeStruct wofx = new WithOnlyFXTypeStruct(); wofx.DECIMAL = 50.0m; wofx.GUID = Create(default(Guid)); return wofx; } public static MixedAllStruct Create(MixedAllStruct val) { MixedAllStruct mas; mas.INT = 10; mas.IntQ = null; mas.IntQA = new int?[] { 10 }; mas.STRING = "Nullable"; mas.INTE = Create(default(IntE)); mas.EMPTYCLASS = new EmptyClass(); mas.IEMPTY = Create(default(ImplementOneInterface)); mas.EMPTYSTRUCT = Create(default(EmptyStruct)); mas.IEMPTYGEN = Create(default(ImplementOneInterfaceGen<int>)); mas.EMPTYSTRUCTGEN = Create(default(EmptyStructGen<int>)); mas.WITHONLYFXTYPESTRUCT = Create(default(WithOnlyFXTypeStruct)); mas.GCHANDLE = Create(default(GCHandle)); return mas; } public static bool Compare(char val, char val1) { return val == val1; } public static bool Compare(bool val, bool val1) { return val == val1; } public static bool Compare(byte val, byte val1) { return val == val1; } public static bool Compare(sbyte val, sbyte val1) { return val == val1; } public static bool Compare(short val, short val1) { return val == val1; } public static bool Compare(ushort val, ushort val1) { return val == val1; } public static bool Compare(int val, int val1) { return val == val1; } public static bool Compare(uint val, uint val1) { return val == val1; } public static bool Compare(long val, long val1) { return val == val1; } public static bool Compare(ulong val, ulong val1) { return val == val1; } public static bool Compare(float val, float val1) { return val == val1; } public static bool Compare(double val, double val1) { return val == val1; } public static bool Compare(decimal val, decimal val1) { return val == val1; } public static bool Compare(IntPtr val, IntPtr val1) { return val == val1; } public static bool Compare(UIntPtr val, UIntPtr val1) { return val == val1; } public static bool Compare(Guid val, Guid val1) { return val == val1; } public static bool Compare(GCHandle val, GCHandle val1) { return val == val1; } public static bool Compare(ByteE val, ByteE val1) { return val == val1; } public static bool Compare(IntE val, IntE val1) { return val == val1; } public static bool Compare(LongE val, LongE val1) { return val == val1; } public static bool Compare(EmptyStruct val, EmptyStruct val1) { return val.Equals(val1); } public static bool Compare(NotEmptyStruct val, NotEmptyStruct val1) { return val.Field == val1.Field; } public static bool Compare(NotEmptyStructQ val, NotEmptyStructQ val1) { return val.Field == val1.Field; } public static bool Compare(NotEmptyStructA val, NotEmptyStructA val1) { return val.Field[0] == val1.Field[0]; } public static bool Compare(NotEmptyStructQA val, NotEmptyStructQA val1) { return val.Field[0] == val1.Field[0]; } public static bool Compare(EmptyStructGen<int> val, EmptyStructGen<int> val1) { return val.Equals(val1); } public static bool Compare(NotEmptyStructGen<int> val, NotEmptyStructGen<int> val1) { return val.Field == val1.Field; } public static bool Compare(NotEmptyStructConstrainedGen<int> val, NotEmptyStructConstrainedGen<int> val1) { return val.Field == val1.Field; } public static bool Compare(NotEmptyStructConstrainedGenA<int> val, NotEmptyStructConstrainedGenA<int> val1) { return val.Field[0] == val1.Field[0]; } public static bool Compare(NotEmptyStructConstrainedGenQ<int> val, NotEmptyStructConstrainedGenQ<int> val1) { return val.Field == val1.Field; } public static bool Compare(NotEmptyStructConstrainedGenQA<int> val, NotEmptyStructConstrainedGenQA<int> val1) { return val.Field[0] == val1.Field[0]; } public static bool Compare(NestedStruct val, NestedStruct val1) { return val.Equals(val1); } public static bool Compare(NestedStructGen<int> val, NestedStructGen<int> val1) { return val.Equals(val1); } public static bool Compare(ExplicitFieldOffsetStruct val, ExplicitFieldOffsetStruct val1) { return (val.Field00 == val1.Field00) && (val.Field15 == val1.Field15); } public static bool Compare(MarshalAsStruct val, MarshalAsStruct val1) { return val.Equals(val1); } public static bool Compare(ImplementOneInterface val, ImplementOneInterface val1) { return (val is IEmpty) && val.Equals(val1); } public static bool Compare(ImplementTwoInterface val, ImplementTwoInterface val1) { return (val is IEmpty) && val is INotEmpty && val.Equals(val1); } public static bool Compare(ImplementOneInterfaceGen<int> val, ImplementOneInterfaceGen<int> val1) { return val is IEmptyGen<int> && val.Equals(val1); } public static bool Compare(ImplementTwoInterfaceGen<int> val, ImplementTwoInterfaceGen<int> val1) { return val is IEmptyGen<int> && val is INotEmptyGen<int> && val.Equals(val1); } public static bool Compare(ImplementAllInterface<int> val, ImplementAllInterface<int> val1) { return val is IEmpty && val is INotEmpty && val is IEmptyGen<int> && val is INotEmptyGen<int> && val.Equals(val1); } public static bool Compare(WithMultipleGCHandleStruct val, WithMultipleGCHandleStruct val1) { return val.H1 == val1.H1 && val.H2 == val1.H2 && val.H3 == val1.H3 && val.H4 == val1.H4 && val.H5 == val1.H5; } public static bool Compare(WithOnlyFXTypeStruct val, WithOnlyFXTypeStruct val1) { return val.GUID == val1.GUID && val.DECIMAL == val1.DECIMAL; } public static bool Compare(MixedAllStruct val, MixedAllStruct val1) { return val.INT == val1.INT && val.IntQ == val1.IntQ && val.IntQA[0] == val1.IntQA[0] && val.STRING == val1.STRING && val.INTE == val1.INTE && val.EMPTYCLASS.Equals(val1.EMPTYCLASS) && val.IEMPTY.Equals(val1.IEMPTY) && Compare(val.EMPTYSTRUCT, val1.EMPTYSTRUCT) && val.IEMPTYGEN.Equals(val1.IEMPTYGEN) && Compare(val.EMPTYSTRUCTGEN, val1.EMPTYSTRUCTGEN) && Compare(val.WITHONLYFXTYPESTRUCT, val1.WITHONLYFXTYPESTRUCT) && Compare(val.GCHANDLE, val1.GCHANDLE); } public static bool Compare(char? val, char val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(bool? val, bool val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(byte? val, byte val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(sbyte? val, sbyte val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(short? val, short val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ushort? val, ushort val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(int? val, int val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(uint? val, uint val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(long? val, long val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ulong? val, ulong val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(float? val, float val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(double? val, double val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(decimal? val, decimal val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(IntPtr? val, IntPtr val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(UIntPtr? val, UIntPtr val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(Guid? val, Guid val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(GCHandle? val, GCHandle val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ByteE? val, ByteE val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(IntE? val, IntE val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(LongE? val, LongE val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(EmptyStruct? val, EmptyStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStruct? val, NotEmptyStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructQ? val, NotEmptyStructQ val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructA? val, NotEmptyStructA val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructQA? val, NotEmptyStructQA val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(EmptyStructGen<int>? val, EmptyStructGen<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructGen<int>? val, NotEmptyStructGen<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructConstrainedGen<int>? val, NotEmptyStructConstrainedGen<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructConstrainedGenA<int>? val, NotEmptyStructConstrainedGenA<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructConstrainedGenQ<int>? val, NotEmptyStructConstrainedGenQ<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NotEmptyStructConstrainedGenQA<int>? val, NotEmptyStructConstrainedGenQA<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NestedStruct? val, NestedStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(NestedStructGen<int>? val, NestedStructGen<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ExplicitFieldOffsetStruct? val, ExplicitFieldOffsetStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(MarshalAsStruct? val, MarshalAsStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ImplementOneInterface? val, ImplementOneInterface val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ImplementTwoInterface? val, ImplementTwoInterface val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ImplementOneInterfaceGen<int>? val, ImplementOneInterfaceGen<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ImplementTwoInterfaceGen<int>? val, ImplementTwoInterfaceGen<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(ImplementAllInterface<int>? val, ImplementAllInterface<int> val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(WithMultipleGCHandleStruct? val, WithMultipleGCHandleStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(WithOnlyFXTypeStruct? val, WithOnlyFXTypeStruct val1) { return val == null ? false : Compare(val.Value, val1); } public static bool Compare(MixedAllStruct? val, MixedAllStruct val1) { return val == null ? false : Compare(val.Value, val1); } }
-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_22583/GitHub_22583.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.InteropServices; // Test case where a type-equvalent delegate is assigned class X { static int F() => 3; public static int Main() { XD x = F; XD y = Lib.GetDelegate(); return x() + y() + 64; } }
// 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.InteropServices; // Test case where a type-equvalent delegate is assigned class X { static int F() => 3; public static int Main() { XD x = F; XD y = Lib.GetDelegate(); return x() + y() + 64; } }
-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/Common/TypeSystemException.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; namespace Internal.TypeSystem { /// <summary> /// Base type for all type system exceptions. /// </summary> public abstract partial class TypeSystemException : Exception { private string[] _arguments; /// <summary> /// Gets the resource string identifier. /// </summary> public ExceptionStringID StringID { get; } /// <summary> /// Gets the formatting arguments for the exception string. /// </summary> public IReadOnlyList<string> Arguments { get { return _arguments; } } public override string Message { get { return GetExceptionString(StringID, _arguments); } } internal TypeSystemException(ExceptionStringID id, params string[] args) { StringID = id; _arguments = args; } private static string GetExceptionString(ExceptionStringID id, string[] args) { string formatString = GetFormatString(id); try { if (formatString != null) { return String.Format(formatString, (object[])args); } } catch {} return "[TEMPORARY EXCEPTION MESSAGE] " + id.ToString() + ": " + String.Join(", ", args); } /// <summary> /// The exception that is thrown when type-loading failures occur. /// </summary> public class TypeLoadException : TypeSystemException { public string TypeName { get; } public string AssemblyName { get; } internal TypeLoadException(ExceptionStringID id, string typeName, string assemblyName, string messageArg) : base(id, new string[] { typeName, assemblyName, messageArg }) { TypeName = typeName; AssemblyName = assemblyName; } internal TypeLoadException(ExceptionStringID id, string typeName, string assemblyName) : base(id, new string[] { typeName, assemblyName }) { TypeName = typeName; AssemblyName = assemblyName; } } /// <summary> /// The exception that is thrown when there is an attempt to access a class member that does not exist /// or that is not declared as public. /// </summary> public abstract class MissingMemberException : TypeSystemException { protected internal MissingMemberException(ExceptionStringID id, params string[] args) : base(id, args) { } } /// <summary> /// The exception that is thrown when there is an attempt to access a method that does not exist. /// </summary> public class MissingMethodException : MissingMemberException { internal MissingMethodException(ExceptionStringID id, params string[] args) : base(id, args) { } } /// <summary> /// The exception that is thrown when there is an attempt to access a field that does not exist. /// </summary> public class MissingFieldException : MissingMemberException { internal MissingFieldException(ExceptionStringID id, params string[] args) : base(id, args) { } } /// <summary> /// The exception that is thrown when an attempt to access a file that does not exist on disk fails. /// </summary> public class FileNotFoundException : TypeSystemException { internal FileNotFoundException(ExceptionStringID id, string fileName) : base(id, fileName) { } } /// <summary> /// The exception that is thrown when a program contains invalid Microsoft intermediate language (MSIL) or metadata. /// Generally this indicates a bug in the compiler that generated the program. /// </summary> public class InvalidProgramException : TypeSystemException { internal InvalidProgramException(ExceptionStringID id, string method) : base(id, method) { } internal InvalidProgramException(ExceptionStringID id) : base(id) { } internal InvalidProgramException() : base(ExceptionStringID.InvalidProgramDefault) { } } public class BadImageFormatException : TypeSystemException { internal BadImageFormatException() : base(ExceptionStringID.BadImageFormatGeneric) { } internal BadImageFormatException(string reason) : base(ExceptionStringID.BadImageFormatSpecific, reason) { } } public class MarshalDirectiveException : TypeSystemException { internal MarshalDirectiveException(ExceptionStringID id) : base(id) { } } } }
// 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; namespace Internal.TypeSystem { /// <summary> /// Base type for all type system exceptions. /// </summary> public abstract partial class TypeSystemException : Exception { private string[] _arguments; /// <summary> /// Gets the resource string identifier. /// </summary> public ExceptionStringID StringID { get; } /// <summary> /// Gets the formatting arguments for the exception string. /// </summary> public IReadOnlyList<string> Arguments { get { return _arguments; } } public override string Message { get { return GetExceptionString(StringID, _arguments); } } internal TypeSystemException(ExceptionStringID id, params string[] args) { StringID = id; _arguments = args; } private static string GetExceptionString(ExceptionStringID id, string[] args) { string formatString = GetFormatString(id); try { if (formatString != null) { return String.Format(formatString, (object[])args); } } catch {} return "[TEMPORARY EXCEPTION MESSAGE] " + id.ToString() + ": " + String.Join(", ", args); } /// <summary> /// The exception that is thrown when type-loading failures occur. /// </summary> public class TypeLoadException : TypeSystemException { public string TypeName { get; } public string AssemblyName { get; } internal TypeLoadException(ExceptionStringID id, string typeName, string assemblyName, string messageArg) : base(id, new string[] { typeName, assemblyName, messageArg }) { TypeName = typeName; AssemblyName = assemblyName; } internal TypeLoadException(ExceptionStringID id, string typeName, string assemblyName) : base(id, new string[] { typeName, assemblyName }) { TypeName = typeName; AssemblyName = assemblyName; } } /// <summary> /// The exception that is thrown when there is an attempt to access a class member that does not exist /// or that is not declared as public. /// </summary> public abstract class MissingMemberException : TypeSystemException { protected internal MissingMemberException(ExceptionStringID id, params string[] args) : base(id, args) { } } /// <summary> /// The exception that is thrown when there is an attempt to access a method that does not exist. /// </summary> public class MissingMethodException : MissingMemberException { internal MissingMethodException(ExceptionStringID id, params string[] args) : base(id, args) { } } /// <summary> /// The exception that is thrown when there is an attempt to access a field that does not exist. /// </summary> public class MissingFieldException : MissingMemberException { internal MissingFieldException(ExceptionStringID id, params string[] args) : base(id, args) { } } /// <summary> /// The exception that is thrown when an attempt to access a file that does not exist on disk fails. /// </summary> public class FileNotFoundException : TypeSystemException { internal FileNotFoundException(ExceptionStringID id, string fileName) : base(id, fileName) { } } /// <summary> /// The exception that is thrown when a program contains invalid Microsoft intermediate language (MSIL) or metadata. /// Generally this indicates a bug in the compiler that generated the program. /// </summary> public class InvalidProgramException : TypeSystemException { internal InvalidProgramException(ExceptionStringID id, string method) : base(id, method) { } internal InvalidProgramException(ExceptionStringID id) : base(id) { } internal InvalidProgramException() : base(ExceptionStringID.InvalidProgramDefault) { } } public class BadImageFormatException : TypeSystemException { internal BadImageFormatException() : base(ExceptionStringID.BadImageFormatGeneric) { } internal BadImageFormatException(string reason) : base(ExceptionStringID.BadImageFormatSpecific, reason) { } } public class MarshalDirectiveException : TypeSystemException { internal MarshalDirectiveException(ExceptionStringID id) : base(id) { } } } }
-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.TypeConverter/tests/DataObjectFieldAttributeTests.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.ComponentModel.Tests { public class DataObjectFieldAttributeTests { [Theory] [InlineData(true)] [InlineData(false)] public void Ctor_PrimaryKey(bool primaryKey) { var attribute = new DataObjectFieldAttribute(primaryKey); Assert.Equal(primaryKey, attribute.PrimaryKey); Assert.False(attribute.IsIdentity); Assert.False(attribute.IsNullable); Assert.Equal(-1, attribute.Length); } [Theory] [InlineData(true, true)] [InlineData(false, false)] public void Ctor_PrimaryKey_IsIdentity(bool primaryKey, bool isIdentity) { var attribute = new DataObjectFieldAttribute(primaryKey, isIdentity); Assert.Equal(primaryKey, attribute.PrimaryKey); Assert.Equal(isIdentity, attribute.IsIdentity); Assert.False(attribute.IsNullable); Assert.Equal(-1, attribute.Length); } [Theory] [InlineData(true, true, true)] [InlineData(false, false, false)] public void Ctor_PrimaryKey_IsIdentity_IsNullable(bool primaryKey, bool isIdentity, bool isNullable) { var attribute = new DataObjectFieldAttribute(primaryKey, isIdentity, isNullable); Assert.Equal(primaryKey, attribute.PrimaryKey); Assert.Equal(isIdentity, attribute.IsIdentity); Assert.Equal(isIdentity, attribute.IsNullable); Assert.Equal(-1, attribute.Length); } [Theory] [InlineData(true, true, true, 10)] [InlineData(false, false, false, -1)] public void Ctor_PrimaryKey_IsIdentity_IsNullable_Length(bool primaryKey, bool isIdentity, bool isNullable, int length) { var attribute = new DataObjectFieldAttribute(primaryKey, isIdentity, isNullable, length); Assert.Equal(primaryKey, attribute.PrimaryKey); Assert.Equal(isIdentity, attribute.IsIdentity); Assert.Equal(isIdentity, attribute.IsNullable); Assert.Equal(length, attribute.Length); } public static IEnumerable<object[]> Equals_TestData() { var attribute = new DataObjectFieldAttribute(true, true, true, 10); yield return new object[] { attribute, attribute, true }; yield return new object[] { attribute, new DataObjectFieldAttribute(true, true, true, 10), true }; yield return new object[] { attribute, new DataObjectFieldAttribute(false, true, true, 10), false }; yield return new object[] { attribute, new DataObjectFieldAttribute(true, false, true, 10), false }; yield return new object[] { attribute, new DataObjectFieldAttribute(true, true, false, 10), false }; yield return new object[] { attribute, new DataObjectFieldAttribute(true, true, true, 9), false }; yield return new object[] { attribute, new object(), false }; yield return new object[] { attribute, null, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public void Equals_Other_ReturnsExpected(DataObjectFieldAttribute attribute, object other, bool expected) { Assert.Equal(expected, attribute.Equals(other)); } [Fact] public void GetHashCode_InvokeMultipleTimes_ReturnsSame() { var attribute = new DataObjectFieldAttribute(false); Assert.Equal(attribute.GetHashCode(), attribute.GetHashCode()); } } }
// 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.ComponentModel.Tests { public class DataObjectFieldAttributeTests { [Theory] [InlineData(true)] [InlineData(false)] public void Ctor_PrimaryKey(bool primaryKey) { var attribute = new DataObjectFieldAttribute(primaryKey); Assert.Equal(primaryKey, attribute.PrimaryKey); Assert.False(attribute.IsIdentity); Assert.False(attribute.IsNullable); Assert.Equal(-1, attribute.Length); } [Theory] [InlineData(true, true)] [InlineData(false, false)] public void Ctor_PrimaryKey_IsIdentity(bool primaryKey, bool isIdentity) { var attribute = new DataObjectFieldAttribute(primaryKey, isIdentity); Assert.Equal(primaryKey, attribute.PrimaryKey); Assert.Equal(isIdentity, attribute.IsIdentity); Assert.False(attribute.IsNullable); Assert.Equal(-1, attribute.Length); } [Theory] [InlineData(true, true, true)] [InlineData(false, false, false)] public void Ctor_PrimaryKey_IsIdentity_IsNullable(bool primaryKey, bool isIdentity, bool isNullable) { var attribute = new DataObjectFieldAttribute(primaryKey, isIdentity, isNullable); Assert.Equal(primaryKey, attribute.PrimaryKey); Assert.Equal(isIdentity, attribute.IsIdentity); Assert.Equal(isIdentity, attribute.IsNullable); Assert.Equal(-1, attribute.Length); } [Theory] [InlineData(true, true, true, 10)] [InlineData(false, false, false, -1)] public void Ctor_PrimaryKey_IsIdentity_IsNullable_Length(bool primaryKey, bool isIdentity, bool isNullable, int length) { var attribute = new DataObjectFieldAttribute(primaryKey, isIdentity, isNullable, length); Assert.Equal(primaryKey, attribute.PrimaryKey); Assert.Equal(isIdentity, attribute.IsIdentity); Assert.Equal(isIdentity, attribute.IsNullable); Assert.Equal(length, attribute.Length); } public static IEnumerable<object[]> Equals_TestData() { var attribute = new DataObjectFieldAttribute(true, true, true, 10); yield return new object[] { attribute, attribute, true }; yield return new object[] { attribute, new DataObjectFieldAttribute(true, true, true, 10), true }; yield return new object[] { attribute, new DataObjectFieldAttribute(false, true, true, 10), false }; yield return new object[] { attribute, new DataObjectFieldAttribute(true, false, true, 10), false }; yield return new object[] { attribute, new DataObjectFieldAttribute(true, true, false, 10), false }; yield return new object[] { attribute, new DataObjectFieldAttribute(true, true, true, 9), false }; yield return new object[] { attribute, new object(), false }; yield return new object[] { attribute, null, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public void Equals_Other_ReturnsExpected(DataObjectFieldAttribute attribute, object other, bool expected) { Assert.Equal(expected, attribute.Equals(other)); } [Fact] public void GetHashCode_InvokeMultipleTimes_ReturnsSame() { var attribute = new DataObjectFieldAttribute(false); Assert.Equal(attribute.GetHashCode(), attribute.GetHashCode()); } } }
-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/Vector128/Dot.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\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 DotUInt16() { var test = new VectorBinaryOpTest__DotUInt16(); // 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__DotUInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); 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<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 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 Vector128<UInt16> _fld1; public Vector128<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<Vector128<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__DotUInt16 testClass) { var result = Vector128.Dot(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector128<UInt16> _clsVar1; private static Vector128<UInt16> _clsVar2; private Vector128<UInt16> _fld1; private Vector128<UInt16> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__DotUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); } public VectorBinaryOpTest__DotUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<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, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.Dot( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector128).GetMethod(nameof(Vector128.Dot), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.Dot), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(UInt16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (UInt16)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.Dot( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr); var result = Vector128.Dot(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__DotUInt16(); var result = Vector128.Dot(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.Dot(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.Dot(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(Vector128<UInt16> op1, Vector128<UInt16> op2, UInt16 result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, UInt16 result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(UInt16[] left, UInt16[] right, UInt16 result, [CallerMemberName] string method = "") { bool succeeded = true; UInt16 actualResult = default; UInt16 intermResult = default; for (var i = 0; i < Op1ElementCount; i++) { if ((i % Vector128<UInt16>.Count) == 0) { actualResult += intermResult; intermResult = default; } intermResult += (UInt16)(left[i] * right[i]); } actualResult += intermResult; if (actualResult != result) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.Dot)}<UInt16>(Vector128<UInt16>, Vector128<UInt16>): {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 DotUInt16() { var test = new VectorBinaryOpTest__DotUInt16(); // 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__DotUInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); 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<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 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 Vector128<UInt16> _fld1; public Vector128<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<Vector128<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__DotUInt16 testClass) { var result = Vector128.Dot(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector128<UInt16> _clsVar1; private static Vector128<UInt16> _clsVar2; private Vector128<UInt16> _fld1; private Vector128<UInt16> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__DotUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); } public VectorBinaryOpTest__DotUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<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, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.Dot( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector128).GetMethod(nameof(Vector128.Dot), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.Dot), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(UInt16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (UInt16)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.Dot( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr); var result = Vector128.Dot(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__DotUInt16(); var result = Vector128.Dot(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.Dot(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.Dot(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(Vector128<UInt16> op1, Vector128<UInt16> op2, UInt16 result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, UInt16 result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(UInt16[] left, UInt16[] right, UInt16 result, [CallerMemberName] string method = "") { bool succeeded = true; UInt16 actualResult = default; UInt16 intermResult = default; for (var i = 0; i < Op1ElementCount; i++) { if ((i % Vector128<UInt16>.Count) == 0) { actualResult += intermResult; intermResult = default; } intermResult += (UInt16)(left[i] * right[i]); } actualResult += intermResult; if (actualResult != result) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.Dot)}<UInt16>(Vector128<UInt16>, Vector128<UInt16>): {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,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/Common/src/System/StringExtensions.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; namespace System { internal static class StringExtensions { internal static string SubstringTrim(this string value, int startIndex, int length) { Debug.Assert(value != null, "string must be non-null"); Debug.Assert(startIndex >= 0, "startIndex must be non-negative"); Debug.Assert(length >= 0, "length must be non-negative"); Debug.Assert(startIndex <= value.Length - length, "startIndex + length must be <= value.Length"); if (length == 0) { return string.Empty; } int endIndex = startIndex + length - 1; while (startIndex <= endIndex && char.IsWhiteSpace(value[startIndex])) { startIndex++; } while (endIndex >= startIndex && char.IsWhiteSpace(value[endIndex])) { endIndex--; } int newLength = endIndex - startIndex + 1; Debug.Assert(newLength >= 0 && newLength <= value.Length, "Expected resulting length to be within value's length"); return newLength == 0 ? string.Empty : newLength == value.Length ? value : value.Substring(startIndex, newLength); } } }
// 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; namespace System { internal static class StringExtensions { internal static string SubstringTrim(this string value, int startIndex, int length) { Debug.Assert(value != null, "string must be non-null"); Debug.Assert(startIndex >= 0, "startIndex must be non-negative"); Debug.Assert(length >= 0, "length must be non-negative"); Debug.Assert(startIndex <= value.Length - length, "startIndex + length must be <= value.Length"); if (length == 0) { return string.Empty; } int endIndex = startIndex + length - 1; while (startIndex <= endIndex && char.IsWhiteSpace(value[startIndex])) { startIndex++; } while (endIndex >= startIndex && char.IsWhiteSpace(value[endIndex])) { endIndex--; } int newLength = endIndex - startIndex + 1; Debug.Assert(newLength >= 0 && newLength <= value.Length, "Expected resulting length to be within value's length"); return newLength == 0 ? string.Empty : newLength == value.Length ? value : value.Substring(startIndex, newLength); } } }
-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/UnitTests/SslAuthenticationOptionsTests.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.Security.Authentication; using System.Security.Cryptography.X509Certificates; using Xunit; namespace System.Net.Security.Tests { public class SslAuthenticationOptionsTests { private readonly SslClientAuthenticationOptions _clientOptions = new SslClientAuthenticationOptions(); private readonly SslServerAuthenticationOptions _serverOptions = new SslServerAuthenticationOptions(); [Fact] public void AllowRenegotiation_Get_Set_Succeeds() { Assert.True(_clientOptions.AllowRenegotiation); Assert.False(_serverOptions.AllowRenegotiation); _clientOptions.AllowRenegotiation = true; _serverOptions.AllowRenegotiation = true; Assert.True(_clientOptions.AllowRenegotiation); Assert.True(_serverOptions.AllowRenegotiation); } [Fact] public void ClientCertificateRequired_Get_Set_Succeeds() { Assert.False(_serverOptions.ClientCertificateRequired); _serverOptions.ClientCertificateRequired = true; Assert.True(_serverOptions.ClientCertificateRequired); } [Fact] public void ApplicationProtocols_Get_Set_Succeeds() { Assert.Null(_clientOptions.ApplicationProtocols); Assert.Null(_serverOptions.ApplicationProtocols); List<SslApplicationProtocol> applnProtos = new List<SslApplicationProtocol> { SslApplicationProtocol.Http3, SslApplicationProtocol.Http2, SslApplicationProtocol.Http11 }; _clientOptions.ApplicationProtocols = applnProtos; _serverOptions.ApplicationProtocols = applnProtos; Assert.Equal(applnProtos, _clientOptions.ApplicationProtocols); Assert.Equal(applnProtos, _serverOptions.ApplicationProtocols); } [Fact] public void RemoteCertificateValidationCallback_Get_Set_Succeeds() { Assert.Null(_clientOptions.RemoteCertificateValidationCallback); Assert.Null(_serverOptions.RemoteCertificateValidationCallback); RemoteCertificateValidationCallback callback = (sender, certificate, chain, errors) => { return true; }; _clientOptions.RemoteCertificateValidationCallback = callback; _serverOptions.RemoteCertificateValidationCallback = callback; Assert.Equal(callback, _clientOptions.RemoteCertificateValidationCallback); Assert.Equal(callback, _serverOptions.RemoteCertificateValidationCallback); } [Fact] public void LocalCertificateSelectionCallback_Get_Set_Succeeds() { Assert.Null(_clientOptions.LocalCertificateSelectionCallback); LocalCertificateSelectionCallback callback = (sender, host, localCertificates, remoteCertificate, issuers) => default; _clientOptions.LocalCertificateSelectionCallback = callback; Assert.Equal(callback, _clientOptions.LocalCertificateSelectionCallback); } [Theory] [InlineData("")] [InlineData("\u0bee")] [InlineData("hello")] [InlineData(" \t")] [InlineData(null)] public void TargetHost_Get_Set_Succeeds(string expected) { Assert.Null(_clientOptions.TargetHost); _clientOptions.TargetHost = expected; Assert.Equal(expected, _clientOptions.TargetHost); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/38559")] public void ClientCertificates_Get_Set_Succeeds() { Assert.Null(_clientOptions.ClientCertificates); _clientOptions.ClientCertificates = null; Assert.Null(_clientOptions.ClientCertificates); X509CertificateCollection expected = new X509CertificateCollection(); _clientOptions.ClientCertificates = expected; Assert.Equal(expected, _clientOptions.ClientCertificates); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/38559")] public void ServerCertificate_Get_Set_Succeeds() { Assert.Null(_serverOptions.ServerCertificate); _serverOptions.ServerCertificate = null; Assert.Null(_serverOptions.ServerCertificate); X509Certificate cert = new X509Certificate2(stackalloc byte[0]); _serverOptions.ServerCertificate = cert; Assert.Equal(cert, _serverOptions.ServerCertificate); } [Fact] public void EnabledSslProtocols_Get_Set_Succeeds() { Assert.Equal(SslProtocols.None, _clientOptions.EnabledSslProtocols); Assert.Equal(SslProtocols.None, _serverOptions.EnabledSslProtocols); _clientOptions.EnabledSslProtocols = SslProtocols.Tls12; _serverOptions.EnabledSslProtocols = SslProtocols.Tls12; Assert.Equal(SslProtocols.Tls12, _clientOptions.EnabledSslProtocols); Assert.Equal(SslProtocols.Tls12, _serverOptions.EnabledSslProtocols); } [Fact] public void CheckCertificateRevocation_Get_Set_Succeeds() { Assert.Equal(X509RevocationMode.NoCheck, _clientOptions.CertificateRevocationCheckMode); Assert.Equal(X509RevocationMode.NoCheck, _serverOptions.CertificateRevocationCheckMode); _clientOptions.CertificateRevocationCheckMode = X509RevocationMode.Online; _serverOptions.CertificateRevocationCheckMode = X509RevocationMode.Offline; Assert.Equal(X509RevocationMode.Online, _clientOptions.CertificateRevocationCheckMode); Assert.Equal(X509RevocationMode.Offline, _serverOptions.CertificateRevocationCheckMode); Assert.Throws<ArgumentException>(() => _clientOptions.CertificateRevocationCheckMode = (X509RevocationMode)3); Assert.Throws<ArgumentException>(() => _serverOptions.CertificateRevocationCheckMode = (X509RevocationMode)3); } [Fact] public void EncryptionPolicy_Get_Set_Succeeds() { Assert.Equal(EncryptionPolicy.RequireEncryption, _clientOptions.EncryptionPolicy); Assert.Equal(EncryptionPolicy.RequireEncryption, _serverOptions.EncryptionPolicy); _clientOptions.EncryptionPolicy = EncryptionPolicy.AllowNoEncryption; _serverOptions.EncryptionPolicy = EncryptionPolicy.NoEncryption; Assert.Equal(EncryptionPolicy.AllowNoEncryption, _clientOptions.EncryptionPolicy); Assert.Equal(EncryptionPolicy.NoEncryption, _serverOptions.EncryptionPolicy); Assert.Throws<ArgumentException>(() => _clientOptions.EncryptionPolicy = (EncryptionPolicy)3); Assert.Throws<ArgumentException>(() => _serverOptions.EncryptionPolicy = (EncryptionPolicy)3); } } }
// 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.Security.Authentication; using System.Security.Cryptography.X509Certificates; using Xunit; namespace System.Net.Security.Tests { public class SslAuthenticationOptionsTests { private readonly SslClientAuthenticationOptions _clientOptions = new SslClientAuthenticationOptions(); private readonly SslServerAuthenticationOptions _serverOptions = new SslServerAuthenticationOptions(); [Fact] public void AllowRenegotiation_Get_Set_Succeeds() { Assert.True(_clientOptions.AllowRenegotiation); Assert.False(_serverOptions.AllowRenegotiation); _clientOptions.AllowRenegotiation = true; _serverOptions.AllowRenegotiation = true; Assert.True(_clientOptions.AllowRenegotiation); Assert.True(_serverOptions.AllowRenegotiation); } [Fact] public void ClientCertificateRequired_Get_Set_Succeeds() { Assert.False(_serverOptions.ClientCertificateRequired); _serverOptions.ClientCertificateRequired = true; Assert.True(_serverOptions.ClientCertificateRequired); } [Fact] public void ApplicationProtocols_Get_Set_Succeeds() { Assert.Null(_clientOptions.ApplicationProtocols); Assert.Null(_serverOptions.ApplicationProtocols); List<SslApplicationProtocol> applnProtos = new List<SslApplicationProtocol> { SslApplicationProtocol.Http3, SslApplicationProtocol.Http2, SslApplicationProtocol.Http11 }; _clientOptions.ApplicationProtocols = applnProtos; _serverOptions.ApplicationProtocols = applnProtos; Assert.Equal(applnProtos, _clientOptions.ApplicationProtocols); Assert.Equal(applnProtos, _serverOptions.ApplicationProtocols); } [Fact] public void RemoteCertificateValidationCallback_Get_Set_Succeeds() { Assert.Null(_clientOptions.RemoteCertificateValidationCallback); Assert.Null(_serverOptions.RemoteCertificateValidationCallback); RemoteCertificateValidationCallback callback = (sender, certificate, chain, errors) => { return true; }; _clientOptions.RemoteCertificateValidationCallback = callback; _serverOptions.RemoteCertificateValidationCallback = callback; Assert.Equal(callback, _clientOptions.RemoteCertificateValidationCallback); Assert.Equal(callback, _serverOptions.RemoteCertificateValidationCallback); } [Fact] public void LocalCertificateSelectionCallback_Get_Set_Succeeds() { Assert.Null(_clientOptions.LocalCertificateSelectionCallback); LocalCertificateSelectionCallback callback = (sender, host, localCertificates, remoteCertificate, issuers) => default; _clientOptions.LocalCertificateSelectionCallback = callback; Assert.Equal(callback, _clientOptions.LocalCertificateSelectionCallback); } [Theory] [InlineData("")] [InlineData("\u0bee")] [InlineData("hello")] [InlineData(" \t")] [InlineData(null)] public void TargetHost_Get_Set_Succeeds(string expected) { Assert.Null(_clientOptions.TargetHost); _clientOptions.TargetHost = expected; Assert.Equal(expected, _clientOptions.TargetHost); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/38559")] public void ClientCertificates_Get_Set_Succeeds() { Assert.Null(_clientOptions.ClientCertificates); _clientOptions.ClientCertificates = null; Assert.Null(_clientOptions.ClientCertificates); X509CertificateCollection expected = new X509CertificateCollection(); _clientOptions.ClientCertificates = expected; Assert.Equal(expected, _clientOptions.ClientCertificates); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/38559")] public void ServerCertificate_Get_Set_Succeeds() { Assert.Null(_serverOptions.ServerCertificate); _serverOptions.ServerCertificate = null; Assert.Null(_serverOptions.ServerCertificate); X509Certificate cert = new X509Certificate2(stackalloc byte[0]); _serverOptions.ServerCertificate = cert; Assert.Equal(cert, _serverOptions.ServerCertificate); } [Fact] public void EnabledSslProtocols_Get_Set_Succeeds() { Assert.Equal(SslProtocols.None, _clientOptions.EnabledSslProtocols); Assert.Equal(SslProtocols.None, _serverOptions.EnabledSslProtocols); _clientOptions.EnabledSslProtocols = SslProtocols.Tls12; _serverOptions.EnabledSslProtocols = SslProtocols.Tls12; Assert.Equal(SslProtocols.Tls12, _clientOptions.EnabledSslProtocols); Assert.Equal(SslProtocols.Tls12, _serverOptions.EnabledSslProtocols); } [Fact] public void CheckCertificateRevocation_Get_Set_Succeeds() { Assert.Equal(X509RevocationMode.NoCheck, _clientOptions.CertificateRevocationCheckMode); Assert.Equal(X509RevocationMode.NoCheck, _serverOptions.CertificateRevocationCheckMode); _clientOptions.CertificateRevocationCheckMode = X509RevocationMode.Online; _serverOptions.CertificateRevocationCheckMode = X509RevocationMode.Offline; Assert.Equal(X509RevocationMode.Online, _clientOptions.CertificateRevocationCheckMode); Assert.Equal(X509RevocationMode.Offline, _serverOptions.CertificateRevocationCheckMode); Assert.Throws<ArgumentException>(() => _clientOptions.CertificateRevocationCheckMode = (X509RevocationMode)3); Assert.Throws<ArgumentException>(() => _serverOptions.CertificateRevocationCheckMode = (X509RevocationMode)3); } [Fact] public void EncryptionPolicy_Get_Set_Succeeds() { Assert.Equal(EncryptionPolicy.RequireEncryption, _clientOptions.EncryptionPolicy); Assert.Equal(EncryptionPolicy.RequireEncryption, _serverOptions.EncryptionPolicy); _clientOptions.EncryptionPolicy = EncryptionPolicy.AllowNoEncryption; _serverOptions.EncryptionPolicy = EncryptionPolicy.NoEncryption; Assert.Equal(EncryptionPolicy.AllowNoEncryption, _clientOptions.EncryptionPolicy); Assert.Equal(EncryptionPolicy.NoEncryption, _serverOptions.EncryptionPolicy); Assert.Throws<ArgumentException>(() => _clientOptions.EncryptionPolicy = (EncryptionPolicy)3); Assert.Throws<ArgumentException>(() => _serverOptions.EncryptionPolicy = (EncryptionPolicy)3); } } }
-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/wasm/debugger/DebuggerTestSuite/CallFunctionOnTests.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.Linq; using System.Threading.Tasks; using Microsoft.WebAssembly.Diagnostics; using Newtonsoft.Json.Linq; using Xunit; namespace DebuggerTests { public class CallFunctionOnTests : DebuggerTestBase { // This tests `callFunctionOn` with a function that the vscode-js-debug extension uses // Using this here as a non-trivial test case [Theory] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, 10, false)] [InlineData("big_array_js_test (0);", "/other.js", 10, 1, 0, true)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, 10, false)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 0);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, 0, true)] public async Task CheckVSCodeTestFunction1(string eval_fn, string bp_loc, int line, int col, int len, bool roundtrip) { string vscode_fn0 = "function(){const e={__proto__:this.__proto__},t=Object.getOwnPropertyNames(this);for(let r=0;r<t.length;++r){const n=t[r],i=n>>>0;if(String(i>>>0)===n&&i>>>0!=4294967295)continue;const a=Object.getOwnPropertyDescriptor(this,n);a&&Object.defineProperty(e,n,a)}return e}"; await RunCallFunctionOn(eval_fn, vscode_fn0, "big", bp_loc, line, col, res_array_len: len, roundtrip: roundtrip, test_fn: async (result) => { var is_js = bp_loc.EndsWith(".js", StringComparison.Ordinal); var obj_accessors = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = true, ownProperties = false }), token); if (is_js) await CheckProps(obj_accessors.Value["result"], new { __proto__ = TIgnore() }, "obj_accessors"); else AssertEqual(0, obj_accessors.Value["result"]?.Count(), "obj_accessors-count"); // Check for a __proto__ object // isOwn = true, accessorPropertiesOnly = false var obj_own = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = false, ownProperties = true }), token); await CheckProps(obj_own.Value["result"], new { length = TNumber(len), // __proto__ = TArray (type, 0) // Is this one really required? }, $"obj_own"); }); } void CheckJFunction(JToken actual, string className, string label) { AssertEqual("function", actual["type"]?.Value<string>(), $"{label}-type"); AssertEqual(className, actual["className"]?.Value<string>(), $"{label}-className"); } // This tests `callFunctionOn` with a function that the vscode-js-debug extension uses // Using this here as a non-trivial test case [Theory] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, 10)] [InlineData("big_array_js_test (0);", "/other.js", 10, 1, 0)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, 10)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 0);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, 0)] public async Task CheckVSCodeTestFunction2(string eval_fn, string bp_loc, int line, int col, int len) { var fetch_start_idx = 2; var num_elems_fetch = 3; string vscode_fn1 = "function(e,t){const r={},n=-1===e?0:e,i=-1===t?this.length:e+t;for(let e=n;e<i&&e<this.length;++e){const t=Object.getOwnPropertyDescriptor(this,e);t&&Object.defineProperty(r,e,t)}return r}"; await RunCallFunctionOn(eval_fn, vscode_fn1, "big", bp_loc, line, col, fn_args: JArray.FromObject(new[] { new { @value = fetch_start_idx }, new { @value = num_elems_fetch } }), test_fn: async (result) => { var is_js = bp_loc.EndsWith(".js", StringComparison.Ordinal); // isOwn = false, accessorPropertiesOnly = true var obj_accessors = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = true, ownProperties = false }), token); if (is_js) await CheckProps(obj_accessors.Value["result"], new { __proto__ = TIgnore() }, "obj_accessors"); else AssertEqual(0, obj_accessors.Value["result"]?.Count(), "obj_accessors-count"); // isOwn = true, accessorPropertiesOnly = false var obj_own = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = false, ownProperties = true }), token); var obj_own_val = obj_own.Value["result"]; var num_elems_recd = len == 0 ? 0 : num_elems_fetch; AssertEqual(num_elems_recd, obj_own_val.Count(), $"obj_own-count"); for (int i = fetch_start_idx; i < fetch_start_idx + num_elems_recd; i++) CheckNumber(obj_own_val, i.ToString(), 1000 + i); }); } [Theory] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, false)] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, true)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, false)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, true)] public async Task RunOnArrayReturnEmptyArray(string eval_fn, string bp_loc, int line, int col, bool roundtrip) { var ret_len = 0; await RunCallFunctionOn(eval_fn, "function () { return []; }", "big", bp_loc, line, col, res_array_len: ret_len, roundtrip: roundtrip, test_fn: async (result) => { var is_js = bp_loc.EndsWith(".js", StringComparison.Ordinal); // getProperties (isOwn = false, accessorPropertiesOnly = true) var obj_accessors = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = true, ownProperties = false }), token); if (is_js) await CheckProps(obj_accessors.Value["result"], new { __proto__ = TIgnore() }, "obj_accessors"); else AssertEqual(0, obj_accessors.Value["result"]?.Count(), "obj_accessors-count"); // getProperties (isOwn = true, accessorPropertiesOnly = false) var obj_own = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = false, ownProperties = true }), token); await CheckProps(obj_own.Value["result"], new { length = TNumber(ret_len), }, $"obj_own"); }); } [Theory] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, false)] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, true)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, false)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, true)] public async Task RunOnArrayReturnArray(string eval_fn, string bp_loc, int line, int col, bool roundtrip) { var ret_len = 5; await RunCallFunctionOn(eval_fn, "function (m) { return Object.values (this).filter ((k, i) => i%m == 0); }", "big", bp_loc, line, col, fn_args: JArray.FromObject(new[] { new { value = 2 } }), res_array_len: ret_len, roundtrip: roundtrip, test_fn: async (result) => { var is_js = bp_loc.EndsWith(".js"); // getProperties (own=false) var obj_accessors = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = true, ownProperties = false }), token); if (is_js) await CheckProps(obj_accessors.Value["result"], new { __proto__ = TIgnore() }, "obj_accessors"); else AssertEqual(0, obj_accessors.Value["result"]?.Count(), "obj_accessors-count"); // getProperties (own=true) // isOwn = true, accessorPropertiesOnly = false var obj_own = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = false, ownProperties = true }), token); // AssertEqual (2, obj_own.Value ["result"].Count (), $"{label}-obj_own.count"); var obj_own_val = obj_own.Value["result"]; await CheckProps(obj_own_val, new { length = TNumber(ret_len), }, $"obj_own", num_fields: (ret_len + 1)); for (int i = 0; i < ret_len; i++) CheckNumber(obj_own_val, i.ToString(), i * 2 + 1000); }); } [Theory] [InlineData(false)] [InlineData(true)] public async Task RunOnVTArray(bool roundtrip) => await RunCallFunctionOn( "invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "function (m) { return Object.values (this).filter ((k, i) => i%m == 0); }", "ss_arr", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, fn_args: JArray.FromObject(new[] { new { value = 2 } }), res_array_len: 5, roundtrip: roundtrip, test_fn: async (result) => { var ret_len = 5; // getProperties (own=false) var obj_accessors = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = true, ownProperties = false }), token); AssertEqual(0, obj_accessors.Value["result"]?.Count(), "obj_accessors-count"); // getProperties (own=true) // isOwn = true, accessorPropertiesOnly = false var obj_own = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = false, ownProperties = true }), token); var obj_own_val = obj_own.Value["result"]; await CheckProps(obj_own_val, new { length = TNumber(ret_len), // __proto__ returned by JS }, "obj_own", num_fields: ret_len + 1); for (int i = 0; i < ret_len; i++) { var act_i = await CheckValueType(obj_own_val, i.ToString(), "Math.SimpleStruct"); // Valuetypes can get sent as part of the container's getProperties, so ensure that we can access it var act_i_props = await GetProperties(act_i["value"]["objectId"]?.Value<string>()); await CheckProps(act_i_props, new { dt = TDateTime(new DateTime(2020 + (i * 2), 1, 2, 3, 4, 5)), gs = TValueType("Math.GenericStruct<System.DateTime>") }, "obj_own ss_arr[{i}]"); var gs_props = await GetObjectOnLocals(act_i_props, "gs"); await CheckProps(gs_props, new { List = TObject("System.Collections.Generic.List<System.DateTime>", is_null: true), StringField = TString($"ss_arr # {i * 2} # gs # StringField") }, "obj_own ss_arr[{i}].gs"); } }); [Theory] [InlineData(false)] [InlineData(true)] public async Task RunOnCFOValueTypeResult(bool roundtrip) => await RunCallFunctionOn( eval_fn: "invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", fn_decl: "function () { return this; }", local_name: "simple_struct", bp_loc: "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, roundtrip: roundtrip, test_fn: async (result) => { // getProperties (own=false) var obj_accessors = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = true, ownProperties = false }), token); AssertEqual(0, obj_accessors.Value["result"].Count(), "obj_accessors-count"); // getProperties (own=true) // isOwn = true, accessorPropertiesOnly = false var obj_own = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = false, ownProperties = true }), token); var obj_own_val = obj_own.Value["result"]; var dt = new DateTime(2020, 1, 2, 3, 4, 5); await CheckProps(obj_own_val, new { dt = TDateTime(dt), gs = TValueType("Math.GenericStruct<System.DateTime>") }, $"obj_own-props"); var gs_props = await GetObjectOnLocals(obj_own_val, "gs"); await CheckProps(gs_props, new { List = TObject("System.Collections.Generic.List<System.DateTime>", is_null: true), StringField = TString($"simple_struct # gs # StringField") }, "simple_struct.gs-props"); }); [Theory] [InlineData(false)] [InlineData(true)] public async Task RunOnJSObject(bool roundtrip) => await RunCallFunctionOn( "object_js_test ();", "function () { return this; }", "obj", "/other.js", 19, 1, fn_args: JArray.FromObject(new[] { new { value = 2 } }), roundtrip: roundtrip, test_fn: async (result) => { // getProperties (own=false) var obj_accessors = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = true, ownProperties = false }), token); await CheckProps(obj_accessors.Value["result"], new { __proto__ = TIgnore() }, "obj_accessors"); // getProperties (own=true) // isOwn = true, accessorPropertiesOnly = false var obj_own = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = false, ownProperties = true }), token); var obj_own_val = obj_own.Value["result"]; await CheckProps(obj_own_val, new { a_obj = TObject("Object"), b_arr = TArray("Array", "Array(2)") }, "obj_own"); }); [Theory] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, false)] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, true)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, false)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, true)] public async Task RunOnArrayReturnObjectArrayByValue(string eval_fn, string bp_loc, int line, int col, bool roundtrip) { var ret_len = 5; await RunCallFunctionOn(eval_fn, "function () { return Object.values (this).filter ((k, i) => i%2 == 0); }", "big", bp_loc, line, col, returnByValue: true, roundtrip: roundtrip, test_fn: async (result) => { // Check cfo result AssertEqual(JTokenType.Object, result.Value["result"].Type, "cfo-result-jsontype"); AssertEqual("object", result.Value["result"]["type"]?.Value<string>(), "cfo-res-type"); AssertEqual(JTokenType.Array, result.Value["result"]["value"].Type, "cfo-res-value-jsontype"); var actual = result.Value["result"]?["value"].Values<JToken>().ToArray(); AssertEqual(ret_len, actual.Length, "cfo-res-value-length"); for (int i = 0; i < ret_len; i++) { var exp_num = i * 2 + 1000; if (bp_loc.EndsWith(".js", StringComparison.Ordinal)) AssertEqual(exp_num, actual[i].Value<int>(), $"[{i}]"); else { AssertEqual("number", actual[i]?["type"]?.Value<string>(), $"[{i}]-type"); AssertEqual(exp_num.ToString(), actual[i]?["description"]?.Value<string>(), $"[{i}]-description"); AssertEqual(exp_num, actual[i]?["value"]?.Value<int>(), $"[{i}]-value"); } } await Task.CompletedTask; }); } [Theory] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, false)] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, true)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, false)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, true)] public async Task RunOnArrayReturnArrayByValue(string eval_fn, string bp_loc, int line, int col, bool roundtrip) => await RunCallFunctionOn(eval_fn, "function () { return Object.getOwnPropertyNames (this); }", "big", bp_loc, line, col, returnByValue: true, roundtrip: roundtrip, test_fn: async (result) => { // Check cfo result AssertEqual("object", result.Value["result"]["type"]?.Value<string>(), "cfo-res-type"); var exp = new JArray(); for (int i = 0; i < 10; i++) exp.Add(i.ToString()); exp.Add("length"); var actual = result.Value["result"]?["value"]; if (!JObject.DeepEquals(exp, actual)) { Assert.True(false, $"Results don't match.\nExpected: {exp}\nActual: {actual}"); } await Task.CompletedTask; }); [Theory] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, false)] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, true)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, false)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, true)] public async Task RunOnArrayReturnPrimitive(string eval_fn, string bp_loc, int line, int col, bool return_by_val) { await SetBreakpoint(bp_loc, line, col); // callFunctionOn var eval_expr = $"window.setTimeout(function() {{ {eval_fn} }}, 1);"; var result = await cli.SendCommand("Runtime.evaluate", JObject.FromObject(new { expression = eval_expr }), token); var pause_location = await insp.WaitFor(Inspector.PAUSE); // Um for js we get "scriptId": "6" // CheckLocation (bp_loc, line, col, scripts, pause_location ["callFrames"][0]["location"]); // Check the object at the bp var frame_locals = await GetProperties(pause_location["callFrames"][0]["scopeChain"][0]["object"]["objectId"].Value<string>()); var obj = GetAndAssertObjectWithName(frame_locals, "big"); var obj_id = obj["value"]["objectId"].Value<string>(); var cfo_args = JObject.FromObject(new { functionDeclaration = "function () { return 5; }", objectId = obj_id }); // value of @returnByValue doesn't matter, as the returned value // is a primitive if (return_by_val) cfo_args["returnByValue"] = return_by_val; // callFunctionOn result = await cli.SendCommand("Runtime.callFunctionOn", cfo_args, token); await CheckValue(result.Value["result"], TNumber(5), "cfo-res"); cfo_args = JObject.FromObject(new { functionDeclaration = "function () { return 'test value'; }", objectId = obj_id }); // value of @returnByValue doesn't matter, as the returned value // is a primitive if (return_by_val) cfo_args["returnByValue"] = return_by_val; // callFunctionOn result = await cli.SendCommand("Runtime.callFunctionOn", cfo_args, token); await CheckValue(result.Value["result"], JObject.FromObject(new { type = "string", value = "test value" }), "cfo-res"); cfo_args = JObject.FromObject(new { functionDeclaration = "function () { return null; }", objectId = obj_id }); // value of @returnByValue doesn't matter, as the returned value // is a primitive if (return_by_val) cfo_args["returnByValue"] = return_by_val; // callFunctionOn result = await cli.SendCommand("Runtime.callFunctionOn", cfo_args, token); await CheckValue(result.Value["result"], JObject.Parse("{ type: 'object', subtype: 'null', value: null }"), "cfo-res"); } public static TheoryData<string, string, int, int, bool?> SilentErrorsTestData(bool? silent) => new TheoryData<string, string, int, int, bool?> { { "invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, silent }, { "big_array_js_test (10);", "/other.js", 10, 1, silent } }; [Theory] [MemberData(nameof(SilentErrorsTestData), null)] [MemberData(nameof(SilentErrorsTestData), false)] [MemberData(nameof(SilentErrorsTestData), true)] public async Task CFOWithSilentReturnsErrors(string eval_fn, string bp_loc, int line, int col, bool? silent) { await SetBreakpoint(bp_loc, line, col); // callFunctionOn var eval_expr = "window.setTimeout(function() { " + eval_fn + " }, 1);"; var result = await cli.SendCommand("Runtime.evaluate", JObject.FromObject(new { expression = eval_expr }), token); var pause_location = await insp.WaitFor(Inspector.PAUSE); var frame_locals = await GetProperties(pause_location["callFrames"][0]["scopeChain"][0]["object"]["objectId"].Value<string>()); var obj = GetAndAssertObjectWithName(frame_locals, "big"); var big_obj_id = obj["value"]["objectId"].Value<string>(); var error_msg = "#This is an error message#"; // Check the object at the bp var cfo_args = JObject.FromObject(new { functionDeclaration = $"function () {{ throw Error ('{error_msg}'); }}", objectId = big_obj_id }); if (silent.HasValue) cfo_args["silent"] = silent; // callFunctionOn, Silent does not change the result, except that the error // doesn't get reported, and the execution is NOT paused even with setPauseOnException=true result = await cli.SendCommand("Runtime.callFunctionOn", cfo_args, token); Assert.False(result.IsOk, "result.IsOk"); var hasErrorMessage = result.Error["exceptionDetails"]?["exception"]?["description"]?.Value<string>()?.Contains(error_msg); Assert.True((hasErrorMessage ?? false), "Exception message not found"); } public static TheoryData<string, string, int, int, string, Func<string[], object>, string, bool> GettersTestData(string local_name, bool use_cfo) => new TheoryData<string, string, int, int, string, Func<string[], object>, string, bool> { // Chrome sends this one { "invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:PropertyGettersTest');", "PropertyGettersTest", 30, 12, "function invokeGetter(arrayStr){ let result=this; const properties=JSON.parse(arrayStr); for(let i=0,n=properties.length;i<n;++i){ result=result[properties[i]]; } return result; }", (arg_strs) => JArray.FromObject(arg_strs).ToString(), local_name, use_cfo }, { "invoke_static_method_async ('[debugger-test] DebuggerTests.CallFunctionOnTest:PropertyGettersTestAsync');", "MoveNext", 38, 12, "function invokeGetter(arrayStr){ let result=this; const properties=JSON.parse(arrayStr); for(let i=0,n=properties.length;i<n;++i){ result=result[properties[i]]; } return result; }", (arg_strs) => JArray.FromObject(arg_strs).ToString(), local_name, use_cfo }, // VSCode sends this one { "invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:PropertyGettersTest');", "PropertyGettersTest", 30, 12, "function(e){return this[e]}", (args_str) => args_str?.Length > 0 ? args_str[0] : String.Empty, local_name, use_cfo }, { "invoke_static_method_async ('[debugger-test] DebuggerTests.CallFunctionOnTest:PropertyGettersTestAsync');", "MoveNext", 38, 12, "function(e){return this[e]}", (args_str) => args_str?.Length > 0 ? args_str[0] : String.Empty, local_name, use_cfo } }; [Theory] [MemberData(nameof(GettersTestData), "ptd", false)] [MemberData(nameof(GettersTestData), "ptd", true)] [MemberData(nameof(GettersTestData), "swp", false)] [MemberData(nameof(GettersTestData), "swp", true)] public async Task PropertyGettersTest(string eval_fn, string method_name, int line, int col, string cfo_fn, Func<string[], object> get_args_fn, string local_name, bool use_cfo) => await CheckInspectLocalsAtBreakpointSite( "dotnet://debugger-test.dll/debugger-cfo-test.cs", line, col, method_name, $"window.setTimeout(function() {{ {eval_fn} }}, 1);", use_cfo: use_cfo, wait_for_event_fn: async (pause_location) => { var frame_locals = await GetProperties(pause_location["callFrames"][0]["callFrameId"].Value<string>()); await CheckProps(frame_locals, new { ptd = TObject("DebuggerTests.ClassWithProperties"), swp = TObject("DebuggerTests.StructWithProperties") }, "locals#0"); var obj = GetAndAssertObjectWithName(frame_locals, local_name); var dt = new DateTime(4, 5, 6, 7, 8, 9); var obj_props = await GetProperties(obj?["value"]?["objectId"]?.Value<string>()); await CheckProps(obj_props, new { V = TNumber(0xDEADBEEF), Int = TGetter("Int"), String = TGetter("String"), DT = TGetter("DT"), IntArray = TGetter("IntArray"), DTArray = TGetter("DTArray"), StringField = TString(null), // Auto properties show w/o getters, because they have // a backing field DTAutoProperty = TDateTime(dt) }, local_name); // Invoke getters, and check values dt = new DateTime(3, 4, 5, 6, 7, 8); var res = await InvokeGetter(obj, get_args_fn(new[] { "Int" }), cfo_fn); await CheckValue(res.Value["result"], JObject.FromObject(new { type = "number", value = (0xDEADBEEF + (uint)dt.Month) }), $"{local_name}.Int"); res = await InvokeGetter(obj, get_args_fn(new[] { "String" }), cfo_fn); await CheckValue(res.Value["result"], JObject.FromObject(new { type = "string", value = $"String property, V: 0xDEADBEEF" }), $"{local_name}.String"); res = await InvokeGetter(obj, get_args_fn(new[] { "DT" }), cfo_fn); await CheckValue(res.Value["result"], TDateTime(dt), $"{local_name}.DT"); // Check arrays through getters res = await InvokeGetter(obj, get_args_fn(new[] { "IntArray" }), cfo_fn); await CheckValue(res.Value["result"], TArray("int[]", "int[2]"), $"{local_name}.IntArray"); { var arr_elems = await GetProperties(res.Value["result"]?["objectId"]?.Value<string>()); var exp_elems = new[] { TNumber(10), TNumber(20) }; await CheckProps(arr_elems, exp_elems, $"{local_name}.IntArray"); } res = await InvokeGetter(obj, get_args_fn(new[] { "DTArray" }), cfo_fn); await CheckValue(res.Value["result"], TArray("System.DateTime[]", "System.DateTime[2]"), $"{local_name}.DTArray"); { var dt0 = new DateTime(6, 7, 8, 9, 10, 11); var dt1 = new DateTime(1, 2, 3, 4, 5, 6); var arr_elems = await GetProperties(res.Value["result"]?["objectId"]?.Value<string>()); var exp_elems = new[] { TDateTime(dt0), TDateTime(dt1) }; await CheckProps(arr_elems, exp_elems, $"{local_name}.DTArray"); res = await InvokeGetter(arr_elems[0], "Date"); await CheckDateTimeValue(res.Value["result"], dt0.Date); } }); [Fact] public async Task InvokeInheritedAndPrivateGetters() => await CheckInspectLocalsAtBreakpointSite( $"DebuggerTests.GetPropertiesTests.DerivedClass", "InstanceMethod", 1, "InstanceMethod", $"window.setTimeout(function() {{ invoke_static_method_async ('[debugger-test] DebuggerTests.GetPropertiesTests.DerivedClass:run'); }})", wait_for_event_fn: async (pause_location) => { var frame_id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var frame_locals = await GetProperties(frame_id); var this_obj = GetAndAssertObjectWithName(frame_locals, "this"); var args = new[] { // private ("_DTProp", TDateTime(new DateTime(2200, 5, 6, 7, 8, 9))), // overridden ("DateTimeForOverride", TDateTime(new DateTime(2190, 9, 7, 5, 3, 2))), ("FirstName", TString("DerivedClass#FirstName")), ("StringPropertyForOverrideWithAutoProperty", TString("DerivedClass#StringPropertyForOverrideWithAutoProperty")), // inherited ("_base_dateTime", TDateTime(new DateTime(2134, 5, 7, 1, 9, 2))) }; foreach (var (name, expected) in args) { var res = await InvokeGetter(this_obj, name); await CheckValue(res.Value["result"], expected, name); } }); [Theory] [InlineData("invoke_static_method_async ('[debugger-test] DebuggerTests.CallFunctionOnTest:PropertyGettersTestAsync');", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 38, 12, true)] [InlineData("invoke_static_method_async ('[debugger-test] DebuggerTests.CallFunctionOnTest:PropertyGettersTestAsync');", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 38, 12, false)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:PropertyGettersTest');", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 30, 12, true)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:PropertyGettersTest');", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 30, 12, false)] [InlineData("invoke_getters_js_test ();", "/other.js", 32, 1, false)] [InlineData("invoke_getters_js_test ();", "/other.js", 32, 1, true)] public async Task CheckAccessorsOnObjectsWithCFO(string eval_fn, string bp_loc, int line, int col, bool roundtrip) { await RunCallFunctionOn( eval_fn, "function() { return this; }", "ptd", bp_loc, line, col, roundtrip: roundtrip, test_fn: async (result) => { var is_js = bp_loc.EndsWith(".js"); // Check with `accessorPropertiesOnly=true` var id = result.Value?["result"]?["objectId"]?.Value<string>(); var get_prop_req = JObject.FromObject(new { objectId = id, accessorPropertiesOnly = true }); var res = await GetPropertiesAndCheckAccessors(get_prop_req, 5); Assert.False(res.Value["result"].Any(jt => jt["name"]?.Value<string>() == "StringField"), "StringField shouldn't be returned for `accessorPropertiesOnly`"); // Check with `accessorPropertiesOnly` unset, == false get_prop_req = JObject.FromObject(new { objectId = id, }); res = await GetPropertiesAndCheckAccessors(get_prop_req, 7); Assert.True(res.Value["result"].Any(jt => jt["name"]?.Value<string>() == "StringField"), "StringField should be returned for `accessorPropertiesOnly=false`"); }); async Task<Result> GetPropertiesAndCheckAccessors(JObject get_prop_req, int num_fields) { var res = await cli.SendCommand("Runtime.getProperties", get_prop_req, token); if (!res.IsOk) Assert.True(false, $"Runtime.getProperties failed for {get_prop_req.ToString()}, with Result: {res}"); var accessors = new string[] { "Int", "String", "DT", "IntArray", "DTArray" }; foreach (var name in accessors) { var prop = GetAndAssertObjectWithName(res.Value["result"], name); Assert.True(prop["value"] == null, $"{name} shouldn't have a `value`"); await CheckValue(prop, TGetter(name), $"{name}"); } return res; } } public static TheoryData<string, string, int, int, bool> NegativeTestsData(bool use_cfo = false) => new TheoryData<string, string, int, int, bool> { { "invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:MethodForNegativeTests', null);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 45, 12, use_cfo }, { "negative_cfo_test ();", "/other.js", 64, 1, use_cfo } }; [Theory] [MemberData(nameof(NegativeTestsData), false)] public async Task RunOnInvalidCfoId(string eval_fn, string bp_loc, int line, int col, bool use_cfo) => await RunCallFunctionOn( eval_fn, "function() { return this; }", "ptd", bp_loc, line, col, test_fn: async (cfo_result) => { var ptd_id = cfo_result.Value?["result"]?["objectId"]?.Value<string>(); var cfo_args = JObject.FromObject(new { functionDeclaration = "function () { return 0; }", objectId = ptd_id + "_invalid" }); var res = await cli.SendCommand("Runtime.callFunctionOn", cfo_args, token); Assert.False(res.IsOk); }); [Theory] [MemberData(nameof(NegativeTestsData), false)] public async Task RunOnInvalidThirdSegmentOfObjectId(string eval_fn, string bp_loc, int line, int col, bool use_cfo) { UseCallFunctionOnBeforeGetProperties = use_cfo; await SetBreakpoint(bp_loc, line, col); // callFunctionOn var eval_expr = $"window.setTimeout(function() {{ {eval_fn} }}, 1);"; var result = await cli.SendCommand("Runtime.evaluate", JObject.FromObject(new { expression = eval_expr }), token); var pause_location = await insp.WaitFor(Inspector.PAUSE); var frame_locals = await GetProperties(pause_location["callFrames"][0]["scopeChain"][0]["object"]["objectId"].Value<string>()); var ptd = GetAndAssertObjectWithName(frame_locals, "ptd"); var ptd_id = ptd["value"]["objectId"].Value<string>(); var cfo_args = JObject.FromObject(new { functionDeclaration = "function () { return 0; }", objectId = ptd_id + "_invalid" }); var res = await cli.SendCommand("Runtime.callFunctionOn", cfo_args, token); Assert.False(res.IsOk); } [Theory] [MemberData(nameof(NegativeTestsData), false)] [MemberData(nameof(NegativeTestsData), true)] public async Task InvalidPropertyGetters(string eval_fn, string bp_loc, int line, int col, bool use_cfo) { await SetBreakpoint(bp_loc, line, col); UseCallFunctionOnBeforeGetProperties = use_cfo; // callFunctionOn var eval_expr = $"window.setTimeout(function() {{ {eval_fn} }}, 1);"; await SendCommand("Runtime.evaluate", JObject.FromObject(new { expression = eval_expr })); var pause_location = await insp.WaitFor(Inspector.PAUSE); var frame_locals = await GetProperties(pause_location["callFrames"][0]["scopeChain"][0]["object"]["objectId"].Value<string>()); var ptd = GetAndAssertObjectWithName(frame_locals, "ptd"); var ptd_id = ptd["value"]["objectId"].Value<string>(); var invalid_args = new object[] { "NonExistant", String.Empty, null, 12310 }; foreach (var invalid_arg in invalid_args) { var getter_res = await InvokeGetter(JObject.FromObject(new { value = new { objectId = ptd_id } }), invalid_arg); AssertEqual("undefined", getter_res.Value["result"]?["type"]?.ToString(), $"Expected to get undefined result for non-existant accessor - {invalid_arg}"); } } [Theory] [MemberData(nameof(NegativeTestsData), false)] public async Task ReturnNullFromCFO(string eval_fn, string bp_loc, int line, int col, bool use_cfo) => await RunCallFunctionOn( eval_fn, "function() { return this; }", "ptd", bp_loc, line, col, test_fn: async (result) => { var is_js = bp_loc.EndsWith(".js"); var ptd = JObject.FromObject(new { value = new { objectId = result.Value?["result"]?["objectId"]?.Value<string>() } }); var null_value_json = JObject.Parse("{ 'type': 'object', 'subtype': 'null', 'value': null }"); foreach (var returnByValue in new bool?[] { null, false, true }) { var res = await InvokeGetter(ptd, "StringField", returnByValue: returnByValue); if (is_js) { // In js case, it doesn't know the className, so the result looks slightly different Assert.True( JObject.DeepEquals(res.Value["result"], null_value_json), $"[StringField#returnByValue = {returnByValue}] Json didn't match. Actual: {res.Value["result"]} vs {null_value_json}"); } else { await CheckValue(res.Value["result"], TString(null), "StringField"); } } }); /* * 1. runs `Runtime.callFunctionOn` on the objectId, * if @roundtrip == false, then * -> calls @test_fn for that result (new objectId) * else * -> runs it again on the *result's* objectId. * -> calls @test_fn on the *new* result objectId * * Returns: result of `Runtime.callFunctionOn` */ async Task RunCallFunctionOn(string eval_fn, string fn_decl, string local_name, string bp_loc, int line, int col, int res_array_len = -1, Func<Result, Task> test_fn = null, bool returnByValue = false, JArray fn_args = null, bool roundtrip = false) { await SetBreakpoint(bp_loc, line, col); // callFunctionOn var eval_expr = $"window.setTimeout(function() {{ {eval_fn} }}, 1);"; var result = await cli.SendCommand("Runtime.evaluate", JObject.FromObject(new { expression = eval_expr }), token); var pause_location = await insp.WaitFor(Inspector.PAUSE); // Um for js we get "scriptId": "6" // CheckLocation (bp_loc, line, col, scripts, pause_location ["callFrames"][0]["location"]); // Check the object at the bp var frame_locals = await GetProperties(pause_location["callFrames"][0]["scopeChain"][0]["object"]["objectId"].Value<string>()); var obj = GetAndAssertObjectWithName(frame_locals, local_name); var obj_id = obj["value"]["objectId"].Value<string>(); var cfo_args = JObject.FromObject(new { functionDeclaration = fn_decl, objectId = obj_id }); if (fn_args != null) cfo_args["arguments"] = fn_args; if (returnByValue) cfo_args["returnByValue"] = returnByValue; // callFunctionOn result = await cli.SendCommand("Runtime.callFunctionOn", cfo_args, token); await CheckCFOResult(result); // If it wasn't `returnByValue`, then try to run a new function // on that *returned* object // This second function, just returns the object as-is, so the same // test_fn is re-usable. if (!returnByValue && roundtrip) { cfo_args = JObject.FromObject(new { functionDeclaration = "function () { return this; }", objectId = result.Value["result"]["objectId"]?.Value<string>() }); if (fn_args != null) cfo_args["arguments"] = fn_args; result = await cli.SendCommand("Runtime.callFunctionOn", cfo_args, token); await CheckCFOResult(result); } if (test_fn != null) await test_fn(result); return; async Task CheckCFOResult(Result result) { if (returnByValue) return; if (res_array_len < 0) await CheckValue(result.Value["result"], TObject("Object"), $"cfo-res"); else await CheckValue(result.Value["result"], TArray("Array", $"Array({res_array_len})"), $"cfo-res"); } } } }
// 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.Linq; using System.Threading.Tasks; using Microsoft.WebAssembly.Diagnostics; using Newtonsoft.Json.Linq; using Xunit; namespace DebuggerTests { public class CallFunctionOnTests : DebuggerTestBase { // This tests `callFunctionOn` with a function that the vscode-js-debug extension uses // Using this here as a non-trivial test case [Theory] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, 10, false)] [InlineData("big_array_js_test (0);", "/other.js", 10, 1, 0, true)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, 10, false)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 0);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, 0, true)] public async Task CheckVSCodeTestFunction1(string eval_fn, string bp_loc, int line, int col, int len, bool roundtrip) { string vscode_fn0 = "function(){const e={__proto__:this.__proto__},t=Object.getOwnPropertyNames(this);for(let r=0;r<t.length;++r){const n=t[r],i=n>>>0;if(String(i>>>0)===n&&i>>>0!=4294967295)continue;const a=Object.getOwnPropertyDescriptor(this,n);a&&Object.defineProperty(e,n,a)}return e}"; await RunCallFunctionOn(eval_fn, vscode_fn0, "big", bp_loc, line, col, res_array_len: len, roundtrip: roundtrip, test_fn: async (result) => { var is_js = bp_loc.EndsWith(".js", StringComparison.Ordinal); var obj_accessors = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = true, ownProperties = false }), token); if (is_js) await CheckProps(obj_accessors.Value["result"], new { __proto__ = TIgnore() }, "obj_accessors"); else AssertEqual(0, obj_accessors.Value["result"]?.Count(), "obj_accessors-count"); // Check for a __proto__ object // isOwn = true, accessorPropertiesOnly = false var obj_own = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = false, ownProperties = true }), token); await CheckProps(obj_own.Value["result"], new { length = TNumber(len), // __proto__ = TArray (type, 0) // Is this one really required? }, $"obj_own"); }); } void CheckJFunction(JToken actual, string className, string label) { AssertEqual("function", actual["type"]?.Value<string>(), $"{label}-type"); AssertEqual(className, actual["className"]?.Value<string>(), $"{label}-className"); } // This tests `callFunctionOn` with a function that the vscode-js-debug extension uses // Using this here as a non-trivial test case [Theory] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, 10)] [InlineData("big_array_js_test (0);", "/other.js", 10, 1, 0)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, 10)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 0);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, 0)] public async Task CheckVSCodeTestFunction2(string eval_fn, string bp_loc, int line, int col, int len) { var fetch_start_idx = 2; var num_elems_fetch = 3; string vscode_fn1 = "function(e,t){const r={},n=-1===e?0:e,i=-1===t?this.length:e+t;for(let e=n;e<i&&e<this.length;++e){const t=Object.getOwnPropertyDescriptor(this,e);t&&Object.defineProperty(r,e,t)}return r}"; await RunCallFunctionOn(eval_fn, vscode_fn1, "big", bp_loc, line, col, fn_args: JArray.FromObject(new[] { new { @value = fetch_start_idx }, new { @value = num_elems_fetch } }), test_fn: async (result) => { var is_js = bp_loc.EndsWith(".js", StringComparison.Ordinal); // isOwn = false, accessorPropertiesOnly = true var obj_accessors = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = true, ownProperties = false }), token); if (is_js) await CheckProps(obj_accessors.Value["result"], new { __proto__ = TIgnore() }, "obj_accessors"); else AssertEqual(0, obj_accessors.Value["result"]?.Count(), "obj_accessors-count"); // isOwn = true, accessorPropertiesOnly = false var obj_own = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = false, ownProperties = true }), token); var obj_own_val = obj_own.Value["result"]; var num_elems_recd = len == 0 ? 0 : num_elems_fetch; AssertEqual(num_elems_recd, obj_own_val.Count(), $"obj_own-count"); for (int i = fetch_start_idx; i < fetch_start_idx + num_elems_recd; i++) CheckNumber(obj_own_val, i.ToString(), 1000 + i); }); } [Theory] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, false)] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, true)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, false)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, true)] public async Task RunOnArrayReturnEmptyArray(string eval_fn, string bp_loc, int line, int col, bool roundtrip) { var ret_len = 0; await RunCallFunctionOn(eval_fn, "function () { return []; }", "big", bp_loc, line, col, res_array_len: ret_len, roundtrip: roundtrip, test_fn: async (result) => { var is_js = bp_loc.EndsWith(".js", StringComparison.Ordinal); // getProperties (isOwn = false, accessorPropertiesOnly = true) var obj_accessors = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = true, ownProperties = false }), token); if (is_js) await CheckProps(obj_accessors.Value["result"], new { __proto__ = TIgnore() }, "obj_accessors"); else AssertEqual(0, obj_accessors.Value["result"]?.Count(), "obj_accessors-count"); // getProperties (isOwn = true, accessorPropertiesOnly = false) var obj_own = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = false, ownProperties = true }), token); await CheckProps(obj_own.Value["result"], new { length = TNumber(ret_len), }, $"obj_own"); }); } [Theory] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, false)] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, true)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, false)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, true)] public async Task RunOnArrayReturnArray(string eval_fn, string bp_loc, int line, int col, bool roundtrip) { var ret_len = 5; await RunCallFunctionOn(eval_fn, "function (m) { return Object.values (this).filter ((k, i) => i%m == 0); }", "big", bp_loc, line, col, fn_args: JArray.FromObject(new[] { new { value = 2 } }), res_array_len: ret_len, roundtrip: roundtrip, test_fn: async (result) => { var is_js = bp_loc.EndsWith(".js"); // getProperties (own=false) var obj_accessors = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = true, ownProperties = false }), token); if (is_js) await CheckProps(obj_accessors.Value["result"], new { __proto__ = TIgnore() }, "obj_accessors"); else AssertEqual(0, obj_accessors.Value["result"]?.Count(), "obj_accessors-count"); // getProperties (own=true) // isOwn = true, accessorPropertiesOnly = false var obj_own = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = false, ownProperties = true }), token); // AssertEqual (2, obj_own.Value ["result"].Count (), $"{label}-obj_own.count"); var obj_own_val = obj_own.Value["result"]; await CheckProps(obj_own_val, new { length = TNumber(ret_len), }, $"obj_own", num_fields: (ret_len + 1)); for (int i = 0; i < ret_len; i++) CheckNumber(obj_own_val, i.ToString(), i * 2 + 1000); }); } [Theory] [InlineData(false)] [InlineData(true)] public async Task RunOnVTArray(bool roundtrip) => await RunCallFunctionOn( "invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "function (m) { return Object.values (this).filter ((k, i) => i%m == 0); }", "ss_arr", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, fn_args: JArray.FromObject(new[] { new { value = 2 } }), res_array_len: 5, roundtrip: roundtrip, test_fn: async (result) => { var ret_len = 5; // getProperties (own=false) var obj_accessors = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = true, ownProperties = false }), token); AssertEqual(0, obj_accessors.Value["result"]?.Count(), "obj_accessors-count"); // getProperties (own=true) // isOwn = true, accessorPropertiesOnly = false var obj_own = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = false, ownProperties = true }), token); var obj_own_val = obj_own.Value["result"]; await CheckProps(obj_own_val, new { length = TNumber(ret_len), // __proto__ returned by JS }, "obj_own", num_fields: ret_len + 1); for (int i = 0; i < ret_len; i++) { var act_i = await CheckValueType(obj_own_val, i.ToString(), "Math.SimpleStruct"); // Valuetypes can get sent as part of the container's getProperties, so ensure that we can access it var act_i_props = await GetProperties(act_i["value"]["objectId"]?.Value<string>()); await CheckProps(act_i_props, new { dt = TDateTime(new DateTime(2020 + (i * 2), 1, 2, 3, 4, 5)), gs = TValueType("Math.GenericStruct<System.DateTime>") }, "obj_own ss_arr[{i}]"); var gs_props = await GetObjectOnLocals(act_i_props, "gs"); await CheckProps(gs_props, new { List = TObject("System.Collections.Generic.List<System.DateTime>", is_null: true), StringField = TString($"ss_arr # {i * 2} # gs # StringField") }, "obj_own ss_arr[{i}].gs"); } }); [Theory] [InlineData(false)] [InlineData(true)] public async Task RunOnCFOValueTypeResult(bool roundtrip) => await RunCallFunctionOn( eval_fn: "invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", fn_decl: "function () { return this; }", local_name: "simple_struct", bp_loc: "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, roundtrip: roundtrip, test_fn: async (result) => { // getProperties (own=false) var obj_accessors = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = true, ownProperties = false }), token); AssertEqual(0, obj_accessors.Value["result"].Count(), "obj_accessors-count"); // getProperties (own=true) // isOwn = true, accessorPropertiesOnly = false var obj_own = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = false, ownProperties = true }), token); var obj_own_val = obj_own.Value["result"]; var dt = new DateTime(2020, 1, 2, 3, 4, 5); await CheckProps(obj_own_val, new { dt = TDateTime(dt), gs = TValueType("Math.GenericStruct<System.DateTime>") }, $"obj_own-props"); var gs_props = await GetObjectOnLocals(obj_own_val, "gs"); await CheckProps(gs_props, new { List = TObject("System.Collections.Generic.List<System.DateTime>", is_null: true), StringField = TString($"simple_struct # gs # StringField") }, "simple_struct.gs-props"); }); [Theory] [InlineData(false)] [InlineData(true)] public async Task RunOnJSObject(bool roundtrip) => await RunCallFunctionOn( "object_js_test ();", "function () { return this; }", "obj", "/other.js", 19, 1, fn_args: JArray.FromObject(new[] { new { value = 2 } }), roundtrip: roundtrip, test_fn: async (result) => { // getProperties (own=false) var obj_accessors = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = true, ownProperties = false }), token); await CheckProps(obj_accessors.Value["result"], new { __proto__ = TIgnore() }, "obj_accessors"); // getProperties (own=true) // isOwn = true, accessorPropertiesOnly = false var obj_own = await cli.SendCommand("Runtime.getProperties", JObject.FromObject(new { objectId = result.Value["result"]["objectId"].Value<string>(), accessorPropertiesOnly = false, ownProperties = true }), token); var obj_own_val = obj_own.Value["result"]; await CheckProps(obj_own_val, new { a_obj = TObject("Object"), b_arr = TArray("Array", "Array(2)") }, "obj_own"); }); [Theory] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, false)] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, true)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, false)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, true)] public async Task RunOnArrayReturnObjectArrayByValue(string eval_fn, string bp_loc, int line, int col, bool roundtrip) { var ret_len = 5; await RunCallFunctionOn(eval_fn, "function () { return Object.values (this).filter ((k, i) => i%2 == 0); }", "big", bp_loc, line, col, returnByValue: true, roundtrip: roundtrip, test_fn: async (result) => { // Check cfo result AssertEqual(JTokenType.Object, result.Value["result"].Type, "cfo-result-jsontype"); AssertEqual("object", result.Value["result"]["type"]?.Value<string>(), "cfo-res-type"); AssertEqual(JTokenType.Array, result.Value["result"]["value"].Type, "cfo-res-value-jsontype"); var actual = result.Value["result"]?["value"].Values<JToken>().ToArray(); AssertEqual(ret_len, actual.Length, "cfo-res-value-length"); for (int i = 0; i < ret_len; i++) { var exp_num = i * 2 + 1000; if (bp_loc.EndsWith(".js", StringComparison.Ordinal)) AssertEqual(exp_num, actual[i].Value<int>(), $"[{i}]"); else { AssertEqual("number", actual[i]?["type"]?.Value<string>(), $"[{i}]-type"); AssertEqual(exp_num.ToString(), actual[i]?["description"]?.Value<string>(), $"[{i}]-description"); AssertEqual(exp_num, actual[i]?["value"]?.Value<int>(), $"[{i}]-value"); } } await Task.CompletedTask; }); } [Theory] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, false)] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, true)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, false)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, true)] public async Task RunOnArrayReturnArrayByValue(string eval_fn, string bp_loc, int line, int col, bool roundtrip) => await RunCallFunctionOn(eval_fn, "function () { return Object.getOwnPropertyNames (this); }", "big", bp_loc, line, col, returnByValue: true, roundtrip: roundtrip, test_fn: async (result) => { // Check cfo result AssertEqual("object", result.Value["result"]["type"]?.Value<string>(), "cfo-res-type"); var exp = new JArray(); for (int i = 0; i < 10; i++) exp.Add(i.ToString()); exp.Add("length"); var actual = result.Value["result"]?["value"]; if (!JObject.DeepEquals(exp, actual)) { Assert.True(false, $"Results don't match.\nExpected: {exp}\nActual: {actual}"); } await Task.CompletedTask; }); [Theory] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, false)] [InlineData("big_array_js_test (10);", "/other.js", 10, 1, true)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, false)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, true)] public async Task RunOnArrayReturnPrimitive(string eval_fn, string bp_loc, int line, int col, bool return_by_val) { await SetBreakpoint(bp_loc, line, col); // callFunctionOn var eval_expr = $"window.setTimeout(function() {{ {eval_fn} }}, 1);"; var result = await cli.SendCommand("Runtime.evaluate", JObject.FromObject(new { expression = eval_expr }), token); var pause_location = await insp.WaitFor(Inspector.PAUSE); // Um for js we get "scriptId": "6" // CheckLocation (bp_loc, line, col, scripts, pause_location ["callFrames"][0]["location"]); // Check the object at the bp var frame_locals = await GetProperties(pause_location["callFrames"][0]["scopeChain"][0]["object"]["objectId"].Value<string>()); var obj = GetAndAssertObjectWithName(frame_locals, "big"); var obj_id = obj["value"]["objectId"].Value<string>(); var cfo_args = JObject.FromObject(new { functionDeclaration = "function () { return 5; }", objectId = obj_id }); // value of @returnByValue doesn't matter, as the returned value // is a primitive if (return_by_val) cfo_args["returnByValue"] = return_by_val; // callFunctionOn result = await cli.SendCommand("Runtime.callFunctionOn", cfo_args, token); await CheckValue(result.Value["result"], TNumber(5), "cfo-res"); cfo_args = JObject.FromObject(new { functionDeclaration = "function () { return 'test value'; }", objectId = obj_id }); // value of @returnByValue doesn't matter, as the returned value // is a primitive if (return_by_val) cfo_args["returnByValue"] = return_by_val; // callFunctionOn result = await cli.SendCommand("Runtime.callFunctionOn", cfo_args, token); await CheckValue(result.Value["result"], JObject.FromObject(new { type = "string", value = "test value" }), "cfo-res"); cfo_args = JObject.FromObject(new { functionDeclaration = "function () { return null; }", objectId = obj_id }); // value of @returnByValue doesn't matter, as the returned value // is a primitive if (return_by_val) cfo_args["returnByValue"] = return_by_val; // callFunctionOn result = await cli.SendCommand("Runtime.callFunctionOn", cfo_args, token); await CheckValue(result.Value["result"], JObject.Parse("{ type: 'object', subtype: 'null', value: null }"), "cfo-res"); } public static TheoryData<string, string, int, int, bool?> SilentErrorsTestData(bool? silent) => new TheoryData<string, string, int, int, bool?> { { "invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 23, 12, silent }, { "big_array_js_test (10);", "/other.js", 10, 1, silent } }; [Theory] [MemberData(nameof(SilentErrorsTestData), null)] [MemberData(nameof(SilentErrorsTestData), false)] [MemberData(nameof(SilentErrorsTestData), true)] public async Task CFOWithSilentReturnsErrors(string eval_fn, string bp_loc, int line, int col, bool? silent) { await SetBreakpoint(bp_loc, line, col); // callFunctionOn var eval_expr = "window.setTimeout(function() { " + eval_fn + " }, 1);"; var result = await cli.SendCommand("Runtime.evaluate", JObject.FromObject(new { expression = eval_expr }), token); var pause_location = await insp.WaitFor(Inspector.PAUSE); var frame_locals = await GetProperties(pause_location["callFrames"][0]["scopeChain"][0]["object"]["objectId"].Value<string>()); var obj = GetAndAssertObjectWithName(frame_locals, "big"); var big_obj_id = obj["value"]["objectId"].Value<string>(); var error_msg = "#This is an error message#"; // Check the object at the bp var cfo_args = JObject.FromObject(new { functionDeclaration = $"function () {{ throw Error ('{error_msg}'); }}", objectId = big_obj_id }); if (silent.HasValue) cfo_args["silent"] = silent; // callFunctionOn, Silent does not change the result, except that the error // doesn't get reported, and the execution is NOT paused even with setPauseOnException=true result = await cli.SendCommand("Runtime.callFunctionOn", cfo_args, token); Assert.False(result.IsOk, "result.IsOk"); var hasErrorMessage = result.Error["exceptionDetails"]?["exception"]?["description"]?.Value<string>()?.Contains(error_msg); Assert.True((hasErrorMessage ?? false), "Exception message not found"); } public static TheoryData<string, string, int, int, string, Func<string[], object>, string, bool> GettersTestData(string local_name, bool use_cfo) => new TheoryData<string, string, int, int, string, Func<string[], object>, string, bool> { // Chrome sends this one { "invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:PropertyGettersTest');", "PropertyGettersTest", 30, 12, "function invokeGetter(arrayStr){ let result=this; const properties=JSON.parse(arrayStr); for(let i=0,n=properties.length;i<n;++i){ result=result[properties[i]]; } return result; }", (arg_strs) => JArray.FromObject(arg_strs).ToString(), local_name, use_cfo }, { "invoke_static_method_async ('[debugger-test] DebuggerTests.CallFunctionOnTest:PropertyGettersTestAsync');", "MoveNext", 38, 12, "function invokeGetter(arrayStr){ let result=this; const properties=JSON.parse(arrayStr); for(let i=0,n=properties.length;i<n;++i){ result=result[properties[i]]; } return result; }", (arg_strs) => JArray.FromObject(arg_strs).ToString(), local_name, use_cfo }, // VSCode sends this one { "invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:PropertyGettersTest');", "PropertyGettersTest", 30, 12, "function(e){return this[e]}", (args_str) => args_str?.Length > 0 ? args_str[0] : String.Empty, local_name, use_cfo }, { "invoke_static_method_async ('[debugger-test] DebuggerTests.CallFunctionOnTest:PropertyGettersTestAsync');", "MoveNext", 38, 12, "function(e){return this[e]}", (args_str) => args_str?.Length > 0 ? args_str[0] : String.Empty, local_name, use_cfo } }; [Theory] [MemberData(nameof(GettersTestData), "ptd", false)] [MemberData(nameof(GettersTestData), "ptd", true)] [MemberData(nameof(GettersTestData), "swp", false)] [MemberData(nameof(GettersTestData), "swp", true)] public async Task PropertyGettersTest(string eval_fn, string method_name, int line, int col, string cfo_fn, Func<string[], object> get_args_fn, string local_name, bool use_cfo) => await CheckInspectLocalsAtBreakpointSite( "dotnet://debugger-test.dll/debugger-cfo-test.cs", line, col, method_name, $"window.setTimeout(function() {{ {eval_fn} }}, 1);", use_cfo: use_cfo, wait_for_event_fn: async (pause_location) => { var frame_locals = await GetProperties(pause_location["callFrames"][0]["callFrameId"].Value<string>()); await CheckProps(frame_locals, new { ptd = TObject("DebuggerTests.ClassWithProperties"), swp = TObject("DebuggerTests.StructWithProperties") }, "locals#0"); var obj = GetAndAssertObjectWithName(frame_locals, local_name); var dt = new DateTime(4, 5, 6, 7, 8, 9); var obj_props = await GetProperties(obj?["value"]?["objectId"]?.Value<string>()); await CheckProps(obj_props, new { V = TNumber(0xDEADBEEF), Int = TGetter("Int"), String = TGetter("String"), DT = TGetter("DT"), IntArray = TGetter("IntArray"), DTArray = TGetter("DTArray"), StringField = TString(null), // Auto properties show w/o getters, because they have // a backing field DTAutoProperty = TDateTime(dt) }, local_name); // Invoke getters, and check values dt = new DateTime(3, 4, 5, 6, 7, 8); var res = await InvokeGetter(obj, get_args_fn(new[] { "Int" }), cfo_fn); await CheckValue(res.Value["result"], JObject.FromObject(new { type = "number", value = (0xDEADBEEF + (uint)dt.Month) }), $"{local_name}.Int"); res = await InvokeGetter(obj, get_args_fn(new[] { "String" }), cfo_fn); await CheckValue(res.Value["result"], JObject.FromObject(new { type = "string", value = $"String property, V: 0xDEADBEEF" }), $"{local_name}.String"); res = await InvokeGetter(obj, get_args_fn(new[] { "DT" }), cfo_fn); await CheckValue(res.Value["result"], TDateTime(dt), $"{local_name}.DT"); // Check arrays through getters res = await InvokeGetter(obj, get_args_fn(new[] { "IntArray" }), cfo_fn); await CheckValue(res.Value["result"], TArray("int[]", "int[2]"), $"{local_name}.IntArray"); { var arr_elems = await GetProperties(res.Value["result"]?["objectId"]?.Value<string>()); var exp_elems = new[] { TNumber(10), TNumber(20) }; await CheckProps(arr_elems, exp_elems, $"{local_name}.IntArray"); } res = await InvokeGetter(obj, get_args_fn(new[] { "DTArray" }), cfo_fn); await CheckValue(res.Value["result"], TArray("System.DateTime[]", "System.DateTime[2]"), $"{local_name}.DTArray"); { var dt0 = new DateTime(6, 7, 8, 9, 10, 11); var dt1 = new DateTime(1, 2, 3, 4, 5, 6); var arr_elems = await GetProperties(res.Value["result"]?["objectId"]?.Value<string>()); var exp_elems = new[] { TDateTime(dt0), TDateTime(dt1) }; await CheckProps(arr_elems, exp_elems, $"{local_name}.DTArray"); res = await InvokeGetter(arr_elems[0], "Date"); await CheckDateTimeValue(res.Value["result"], dt0.Date); } }); [Fact] public async Task InvokeInheritedAndPrivateGetters() => await CheckInspectLocalsAtBreakpointSite( $"DebuggerTests.GetPropertiesTests.DerivedClass", "InstanceMethod", 1, "InstanceMethod", $"window.setTimeout(function() {{ invoke_static_method_async ('[debugger-test] DebuggerTests.GetPropertiesTests.DerivedClass:run'); }})", wait_for_event_fn: async (pause_location) => { var frame_id = pause_location["callFrames"][0]["callFrameId"].Value<string>(); var frame_locals = await GetProperties(frame_id); var this_obj = GetAndAssertObjectWithName(frame_locals, "this"); var args = new[] { // private ("_DTProp", TDateTime(new DateTime(2200, 5, 6, 7, 8, 9))), // overridden ("DateTimeForOverride", TDateTime(new DateTime(2190, 9, 7, 5, 3, 2))), ("FirstName", TString("DerivedClass#FirstName")), ("StringPropertyForOverrideWithAutoProperty", TString("DerivedClass#StringPropertyForOverrideWithAutoProperty")), // inherited ("_base_dateTime", TDateTime(new DateTime(2134, 5, 7, 1, 9, 2))) }; foreach (var (name, expected) in args) { var res = await InvokeGetter(this_obj, name); await CheckValue(res.Value["result"], expected, name); } }); [Theory] [InlineData("invoke_static_method_async ('[debugger-test] DebuggerTests.CallFunctionOnTest:PropertyGettersTestAsync');", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 38, 12, true)] [InlineData("invoke_static_method_async ('[debugger-test] DebuggerTests.CallFunctionOnTest:PropertyGettersTestAsync');", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 38, 12, false)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:PropertyGettersTest');", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 30, 12, true)] [InlineData("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:PropertyGettersTest');", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 30, 12, false)] [InlineData("invoke_getters_js_test ();", "/other.js", 32, 1, false)] [InlineData("invoke_getters_js_test ();", "/other.js", 32, 1, true)] public async Task CheckAccessorsOnObjectsWithCFO(string eval_fn, string bp_loc, int line, int col, bool roundtrip) { await RunCallFunctionOn( eval_fn, "function() { return this; }", "ptd", bp_loc, line, col, roundtrip: roundtrip, test_fn: async (result) => { var is_js = bp_loc.EndsWith(".js"); // Check with `accessorPropertiesOnly=true` var id = result.Value?["result"]?["objectId"]?.Value<string>(); var get_prop_req = JObject.FromObject(new { objectId = id, accessorPropertiesOnly = true }); var res = await GetPropertiesAndCheckAccessors(get_prop_req, 5); Assert.False(res.Value["result"].Any(jt => jt["name"]?.Value<string>() == "StringField"), "StringField shouldn't be returned for `accessorPropertiesOnly`"); // Check with `accessorPropertiesOnly` unset, == false get_prop_req = JObject.FromObject(new { objectId = id, }); res = await GetPropertiesAndCheckAccessors(get_prop_req, 7); Assert.True(res.Value["result"].Any(jt => jt["name"]?.Value<string>() == "StringField"), "StringField should be returned for `accessorPropertiesOnly=false`"); }); async Task<Result> GetPropertiesAndCheckAccessors(JObject get_prop_req, int num_fields) { var res = await cli.SendCommand("Runtime.getProperties", get_prop_req, token); if (!res.IsOk) Assert.True(false, $"Runtime.getProperties failed for {get_prop_req.ToString()}, with Result: {res}"); var accessors = new string[] { "Int", "String", "DT", "IntArray", "DTArray" }; foreach (var name in accessors) { var prop = GetAndAssertObjectWithName(res.Value["result"], name); Assert.True(prop["value"] == null, $"{name} shouldn't have a `value`"); await CheckValue(prop, TGetter(name), $"{name}"); } return res; } } public static TheoryData<string, string, int, int, bool> NegativeTestsData(bool use_cfo = false) => new TheoryData<string, string, int, int, bool> { { "invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:MethodForNegativeTests', null);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 45, 12, use_cfo }, { "negative_cfo_test ();", "/other.js", 64, 1, use_cfo } }; [Theory] [MemberData(nameof(NegativeTestsData), false)] public async Task RunOnInvalidCfoId(string eval_fn, string bp_loc, int line, int col, bool use_cfo) => await RunCallFunctionOn( eval_fn, "function() { return this; }", "ptd", bp_loc, line, col, test_fn: async (cfo_result) => { var ptd_id = cfo_result.Value?["result"]?["objectId"]?.Value<string>(); var cfo_args = JObject.FromObject(new { functionDeclaration = "function () { return 0; }", objectId = ptd_id + "_invalid" }); var res = await cli.SendCommand("Runtime.callFunctionOn", cfo_args, token); Assert.False(res.IsOk); }); [Theory] [MemberData(nameof(NegativeTestsData), false)] public async Task RunOnInvalidThirdSegmentOfObjectId(string eval_fn, string bp_loc, int line, int col, bool use_cfo) { UseCallFunctionOnBeforeGetProperties = use_cfo; await SetBreakpoint(bp_loc, line, col); // callFunctionOn var eval_expr = $"window.setTimeout(function() {{ {eval_fn} }}, 1);"; var result = await cli.SendCommand("Runtime.evaluate", JObject.FromObject(new { expression = eval_expr }), token); var pause_location = await insp.WaitFor(Inspector.PAUSE); var frame_locals = await GetProperties(pause_location["callFrames"][0]["scopeChain"][0]["object"]["objectId"].Value<string>()); var ptd = GetAndAssertObjectWithName(frame_locals, "ptd"); var ptd_id = ptd["value"]["objectId"].Value<string>(); var cfo_args = JObject.FromObject(new { functionDeclaration = "function () { return 0; }", objectId = ptd_id + "_invalid" }); var res = await cli.SendCommand("Runtime.callFunctionOn", cfo_args, token); Assert.False(res.IsOk); } [Theory] [MemberData(nameof(NegativeTestsData), false)] [MemberData(nameof(NegativeTestsData), true)] public async Task InvalidPropertyGetters(string eval_fn, string bp_loc, int line, int col, bool use_cfo) { await SetBreakpoint(bp_loc, line, col); UseCallFunctionOnBeforeGetProperties = use_cfo; // callFunctionOn var eval_expr = $"window.setTimeout(function() {{ {eval_fn} }}, 1);"; await SendCommand("Runtime.evaluate", JObject.FromObject(new { expression = eval_expr })); var pause_location = await insp.WaitFor(Inspector.PAUSE); var frame_locals = await GetProperties(pause_location["callFrames"][0]["scopeChain"][0]["object"]["objectId"].Value<string>()); var ptd = GetAndAssertObjectWithName(frame_locals, "ptd"); var ptd_id = ptd["value"]["objectId"].Value<string>(); var invalid_args = new object[] { "NonExistant", String.Empty, null, 12310 }; foreach (var invalid_arg in invalid_args) { var getter_res = await InvokeGetter(JObject.FromObject(new { value = new { objectId = ptd_id } }), invalid_arg); AssertEqual("undefined", getter_res.Value["result"]?["type"]?.ToString(), $"Expected to get undefined result for non-existant accessor - {invalid_arg}"); } } [Theory] [MemberData(nameof(NegativeTestsData), false)] public async Task ReturnNullFromCFO(string eval_fn, string bp_loc, int line, int col, bool use_cfo) => await RunCallFunctionOn( eval_fn, "function() { return this; }", "ptd", bp_loc, line, col, test_fn: async (result) => { var is_js = bp_loc.EndsWith(".js"); var ptd = JObject.FromObject(new { value = new { objectId = result.Value?["result"]?["objectId"]?.Value<string>() } }); var null_value_json = JObject.Parse("{ 'type': 'object', 'subtype': 'null', 'value': null }"); foreach (var returnByValue in new bool?[] { null, false, true }) { var res = await InvokeGetter(ptd, "StringField", returnByValue: returnByValue); if (is_js) { // In js case, it doesn't know the className, so the result looks slightly different Assert.True( JObject.DeepEquals(res.Value["result"], null_value_json), $"[StringField#returnByValue = {returnByValue}] Json didn't match. Actual: {res.Value["result"]} vs {null_value_json}"); } else { await CheckValue(res.Value["result"], TString(null), "StringField"); } } }); /* * 1. runs `Runtime.callFunctionOn` on the objectId, * if @roundtrip == false, then * -> calls @test_fn for that result (new objectId) * else * -> runs it again on the *result's* objectId. * -> calls @test_fn on the *new* result objectId * * Returns: result of `Runtime.callFunctionOn` */ async Task RunCallFunctionOn(string eval_fn, string fn_decl, string local_name, string bp_loc, int line, int col, int res_array_len = -1, Func<Result, Task> test_fn = null, bool returnByValue = false, JArray fn_args = null, bool roundtrip = false) { await SetBreakpoint(bp_loc, line, col); // callFunctionOn var eval_expr = $"window.setTimeout(function() {{ {eval_fn} }}, 1);"; var result = await cli.SendCommand("Runtime.evaluate", JObject.FromObject(new { expression = eval_expr }), token); var pause_location = await insp.WaitFor(Inspector.PAUSE); // Um for js we get "scriptId": "6" // CheckLocation (bp_loc, line, col, scripts, pause_location ["callFrames"][0]["location"]); // Check the object at the bp var frame_locals = await GetProperties(pause_location["callFrames"][0]["scopeChain"][0]["object"]["objectId"].Value<string>()); var obj = GetAndAssertObjectWithName(frame_locals, local_name); var obj_id = obj["value"]["objectId"].Value<string>(); var cfo_args = JObject.FromObject(new { functionDeclaration = fn_decl, objectId = obj_id }); if (fn_args != null) cfo_args["arguments"] = fn_args; if (returnByValue) cfo_args["returnByValue"] = returnByValue; // callFunctionOn result = await cli.SendCommand("Runtime.callFunctionOn", cfo_args, token); await CheckCFOResult(result); // If it wasn't `returnByValue`, then try to run a new function // on that *returned* object // This second function, just returns the object as-is, so the same // test_fn is re-usable. if (!returnByValue && roundtrip) { cfo_args = JObject.FromObject(new { functionDeclaration = "function () { return this; }", objectId = result.Value["result"]["objectId"]?.Value<string>() }); if (fn_args != null) cfo_args["arguments"] = fn_args; result = await cli.SendCommand("Runtime.callFunctionOn", cfo_args, token); await CheckCFOResult(result); } if (test_fn != null) await test_fn(result); return; async Task CheckCFOResult(Result result) { if (returnByValue) return; if (res_array_len < 0) await CheckValue(result.Value["result"], TObject("Object"), $"cfo-res"); else await CheckValue(result.Value["result"], TArray("Array", $"Array({res_array_len})"), $"cfo-res"); } } } }
-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/ShiftLeftLogicalWideningUpper.Vector128.SByte.1.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 ShiftLeftLogicalWideningUpper_Vector128_SByte_1() { var test = new ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_SByte_1(); 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 ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_SByte_1 { private struct DataTable { private byte[] inArray; private byte[] outArray; private GCHandle inHandle; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray, Int16[] outArray, int alignment) { int sizeOfinArray = inArray.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<SByte, byte>(ref inArray[0]), (uint)sizeOfinArray); } public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle.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<SByte> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_SByte_1 testClass) { var result = AdvSimd.ShiftLeftLogicalWideningUpper(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_SByte_1 testClass) { fixed (Vector128<SByte>* pFld = &_fld) { var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((SByte*)(pFld)), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly byte Imm = 1; private static SByte[] _data = new SByte[Op1ElementCount]; private static Vector128<SByte> _clsVar; private Vector128<SByte> _fld; private DataTable _dataTable; static ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_SByte_1() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_SByte_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data, new Int16[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.ShiftLeftLogicalWideningUpper( Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((SByte*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogicalWideningUpper), new Type[] { typeof(Vector128<SByte>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogicalWideningUpper), new Type[] { typeof(Vector128<SByte>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((SByte*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftLeftLogicalWideningUpper( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar = &_clsVar) { var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((SByte*)(pClsVar)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr); var result = AdvSimd.ShiftLeftLogicalWideningUpper(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = AdvSimd.LoadVector128((SByte*)(_dataTable.inArrayPtr)); var result = AdvSimd.ShiftLeftLogicalWideningUpper(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_SByte_1(); var result = AdvSimd.ShiftLeftLogicalWideningUpper(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_SByte_1(); fixed (Vector128<SByte>* pFld = &test._fld) { var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((SByte*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftLeftLogicalWideningUpper(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld = &_fld) { var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((SByte*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLeftLogicalWideningUpper(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((SByte*)(&test._fld)), 1 ); 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 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<SByte> firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(SByte[] firstOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftLeftLogicalWideningUpper(firstOp, Imm, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftLeftLogicalWideningUpper)}<Int16>(Vector128<SByte>, 1): {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.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftLeftLogicalWideningUpper_Vector128_SByte_1() { var test = new ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_SByte_1(); 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 ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_SByte_1 { private struct DataTable { private byte[] inArray; private byte[] outArray; private GCHandle inHandle; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray, Int16[] outArray, int alignment) { int sizeOfinArray = inArray.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<SByte, byte>(ref inArray[0]), (uint)sizeOfinArray); } public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle.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<SByte> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_SByte_1 testClass) { var result = AdvSimd.ShiftLeftLogicalWideningUpper(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_SByte_1 testClass) { fixed (Vector128<SByte>* pFld = &_fld) { var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((SByte*)(pFld)), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly byte Imm = 1; private static SByte[] _data = new SByte[Op1ElementCount]; private static Vector128<SByte> _clsVar; private Vector128<SByte> _fld; private DataTable _dataTable; static ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_SByte_1() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_SByte_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data, new Int16[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.ShiftLeftLogicalWideningUpper( Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((SByte*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogicalWideningUpper), new Type[] { typeof(Vector128<SByte>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogicalWideningUpper), new Type[] { typeof(Vector128<SByte>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((SByte*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftLeftLogicalWideningUpper( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar = &_clsVar) { var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((SByte*)(pClsVar)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr); var result = AdvSimd.ShiftLeftLogicalWideningUpper(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = AdvSimd.LoadVector128((SByte*)(_dataTable.inArrayPtr)); var result = AdvSimd.ShiftLeftLogicalWideningUpper(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_SByte_1(); var result = AdvSimd.ShiftLeftLogicalWideningUpper(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmUnaryOpTest__ShiftLeftLogicalWideningUpper_Vector128_SByte_1(); fixed (Vector128<SByte>* pFld = &test._fld) { var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((SByte*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftLeftLogicalWideningUpper(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld = &_fld) { var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((SByte*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLeftLogicalWideningUpper(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLeftLogicalWideningUpper( AdvSimd.LoadVector128((SByte*)(&test._fld)), 1 ); 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 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<SByte> firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(SByte[] firstOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftLeftLogicalWideningUpper(firstOp, Imm, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftLeftLogicalWideningUpper)}<Int16>(Vector128<SByte>, 1): {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/coreclr/tools/aot/DependencyGraphViewer/NodeForm.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.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DependencyLogViewer { public partial class NodeForm : Form { Graph _graph; Node _node; public NodeForm(Graph g, Node n) { _graph = g; _node = n; InitializeComponent(); this.Text = "Graph Pid:" + _graph.PID + " Id:" + _graph.ID + " Node:" + _node.ToString(); this.nodeTitle.Text = _node.ToString(); lock (GraphCollection.Singleton) { this.dependentsListBox.DataSource = _node.Dependents.ToArray(); this.dependeesListBox.DataSource = _node.Dependencies.ToArray(); } } private static void ExploreSelectedItem(Graph graph, ListBox listbox) { if (listbox.SelectedItem == null) return; KeyValuePair<Node, string> pair = (KeyValuePair<Node, string>)listbox.SelectedItem; NodeForm nodeForm = new NodeForm(graph, pair.Key); nodeForm.Show(); } private void exploreDependee_Click(object sender, EventArgs e) { ExploreSelectedItem(_graph, dependeesListBox); } private void exploreDependent_Click(object sender, EventArgs e) { ExploreSelectedItem(_graph, dependentsListBox); } } }
// 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.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DependencyLogViewer { public partial class NodeForm : Form { Graph _graph; Node _node; public NodeForm(Graph g, Node n) { _graph = g; _node = n; InitializeComponent(); this.Text = "Graph Pid:" + _graph.PID + " Id:" + _graph.ID + " Node:" + _node.ToString(); this.nodeTitle.Text = _node.ToString(); lock (GraphCollection.Singleton) { this.dependentsListBox.DataSource = _node.Dependents.ToArray(); this.dependeesListBox.DataSource = _node.Dependencies.ToArray(); } } private static void ExploreSelectedItem(Graph graph, ListBox listbox) { if (listbox.SelectedItem == null) return; KeyValuePair<Node, string> pair = (KeyValuePair<Node, string>)listbox.SelectedItem; NodeForm nodeForm = new NodeForm(graph, pair.Key); nodeForm.Show(); } private void exploreDependee_Click(object sender, EventArgs e) { ExploreSelectedItem(_graph, dependeesListBox); } private void exploreDependent_Click(object sender, EventArgs e) { ExploreSelectedItem(_graph, dependentsListBox); } } }
-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.Asn1/tests/Writer/WriteEnumerated.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.Formats.Asn1.Tests.Reader; using System.Security.Cryptography.X509Certificates; using Test.Cryptography; using Xunit; namespace System.Formats.Asn1.Tests.Writer { public class WriteEnumerated : Asn1WriterTests { [Theory] [InlineData(AsnEncodingRules.BER, ReadEnumerated.SByteBacked.Zero, false, "0A0100")] [InlineData(AsnEncodingRules.CER, ReadEnumerated.SByteBacked.Pillow, true, "9E01EF")] [InlineData(AsnEncodingRules.DER, ReadEnumerated.SByteBacked.Fluff, false, "0A0153")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.SByteBacked.Fluff, true, "9E0153")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.SByteBacked)(-127), true, "9E0181")] public void VerifyWriteEnumerated_SByte( AsnEncodingRules ruleSet, ReadEnumerated.SByteBacked value, bool customTag, string expectedHex) { AsnWriter writer = new AsnWriter(ruleSet); if (customTag) { writer.WriteEnumeratedValue(value, new Asn1Tag(TagClass.ContextSpecific, 30)); } else { writer.WriteEnumeratedValue(value); } Verify(writer, expectedHex); } [Theory] [InlineData(AsnEncodingRules.BER, ReadEnumerated.ByteBacked.Zero, false, "0A0100")] [InlineData(AsnEncodingRules.CER, ReadEnumerated.ByteBacked.NotFluffy, true, "9A010B")] [InlineData(AsnEncodingRules.DER, ReadEnumerated.ByteBacked.Fluff, false, "0A010C")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.ByteBacked.Fluff, true, "9A010C")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.ByteBacked)253, false, "0A0200FD")] public void VerifyWriteEnumerated_Byte( AsnEncodingRules ruleSet, ReadEnumerated.ByteBacked value, bool customTag, string expectedHex) { AsnWriter writer = new AsnWriter(ruleSet); if (customTag) { writer.WriteEnumeratedValue(value, new Asn1Tag(TagClass.ContextSpecific, 26)); } else { writer.WriteEnumeratedValue(value); } Verify(writer, expectedHex); } [Theory] [InlineData(AsnEncodingRules.BER, ReadEnumerated.ShortBacked.Zero, true, "DF81540100")] [InlineData(AsnEncodingRules.CER, ReadEnumerated.ShortBacked.Pillow, true, "DF815402FC00")] [InlineData(AsnEncodingRules.DER, ReadEnumerated.ShortBacked.Fluff, false, "0A020209")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.ShortBacked.Fluff, true, "DF8154020209")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.ShortBacked)25321, false, "0A0262E9")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.ShortBacked)(-12345), false, "0A02CFC7")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.ShortBacked)(-1), true, "DF815401FF")] public void VerifyWriteEnumerated_Short( AsnEncodingRules ruleSet, ReadEnumerated.ShortBacked value, bool customTag, string expectedHex) { AsnWriter writer = new AsnWriter(ruleSet); if (customTag) { writer.WriteEnumeratedValue(value, new Asn1Tag(TagClass.Private, 212)); } else { writer.WriteEnumeratedValue(value); } Verify(writer, expectedHex); } [Theory] [InlineData(AsnEncodingRules.BER, ReadEnumerated.UShortBacked.Zero, false, "0A0100")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.UShortBacked.Zero, true, "4D0100")] [InlineData(AsnEncodingRules.DER, ReadEnumerated.UShortBacked.Fluff, false, "0A03008000")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.UShortBacked.Fluff, true, "4D03008000")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.UShortBacked)11, false, "0A010B")] [InlineData(AsnEncodingRules.DER, (ReadEnumerated.UShortBacked)short.MaxValue, false, "0A027FFF")] [InlineData(AsnEncodingRules.BER, (ReadEnumerated.UShortBacked)ushort.MaxValue, true, "4D0300FFFF")] public void VerifyWriteEnumerated_UShort( AsnEncodingRules ruleSet, ReadEnumerated.UShortBacked value, bool customTag, string expectedHex) { AsnWriter writer = new AsnWriter(ruleSet); if (customTag) { writer.WriteEnumeratedValue(value, new Asn1Tag(TagClass.Application, 13)); } else { writer.WriteEnumeratedValue(value); } Verify(writer, expectedHex); } [Theory] [InlineData(AsnEncodingRules.BER, ReadEnumerated.IntBacked.Zero, true, "5F81FF7F0100")] [InlineData(AsnEncodingRules.CER, ReadEnumerated.IntBacked.Pillow, true, "5F81FF7F03FEFFFF")] [InlineData(AsnEncodingRules.DER, ReadEnumerated.IntBacked.Fluff, false, "0A03010001")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.IntBacked.Fluff, true, "5F81FF7F03010001")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.IntBacked)25321, false, "0A0262E9")] [InlineData(AsnEncodingRules.DER, (ReadEnumerated.IntBacked)(-12345), false, "0A02CFC7")] [InlineData(AsnEncodingRules.BER, (ReadEnumerated.IntBacked)(-1), true, "5F81FF7F01FF")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.IntBacked)int.MinValue, true, "5F81FF7F0480000000")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.IntBacked)int.MaxValue, false, "0A047FFFFFFF")] public void VerifyWriteEnumerated_Int( AsnEncodingRules ruleSet, ReadEnumerated.IntBacked value, bool customTag, string expectedHex) { AsnWriter writer = new AsnWriter(ruleSet); if (customTag) { writer.WriteEnumeratedValue(value, new Asn1Tag(TagClass.Application, short.MaxValue)); } else { writer.WriteEnumeratedValue(value); } Verify(writer, expectedHex); } [Theory] [InlineData(AsnEncodingRules.BER, ReadEnumerated.UIntBacked.Zero, false, "0A0100")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.UIntBacked.Zero, true, "9F610100")] [InlineData(AsnEncodingRules.DER, ReadEnumerated.UIntBacked.Fluff, false, "0A050080000005")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.UIntBacked.Fluff, true, "9F61050080000005")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.UIntBacked)11, false, "0A010B")] [InlineData(AsnEncodingRules.DER, (ReadEnumerated.UIntBacked)short.MaxValue, false, "0A027FFF")] [InlineData(AsnEncodingRules.BER, (ReadEnumerated.UIntBacked)ushort.MaxValue, true, "9F610300FFFF")] public void VerifyWriteEnumerated_UInt( AsnEncodingRules ruleSet, ReadEnumerated.UIntBacked value, bool customTag, string expectedHex) { AsnWriter writer = new AsnWriter(ruleSet); if (customTag) { writer.WriteEnumeratedValue(value, new Asn1Tag(TagClass.ContextSpecific, 97)); } else { writer.WriteEnumeratedValue(value); } Verify(writer, expectedHex); } [Theory] [InlineData(AsnEncodingRules.BER, ReadEnumerated.LongBacked.Zero, true, "800100")] [InlineData(AsnEncodingRules.CER, ReadEnumerated.LongBacked.Pillow, true, "8005FF00000000")] [InlineData(AsnEncodingRules.DER, ReadEnumerated.LongBacked.Fluff, false, "0A050200000441")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.LongBacked.Fluff, true, "80050200000441")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.LongBacked)25321, false, "0A0262E9")] [InlineData(AsnEncodingRules.DER, (ReadEnumerated.LongBacked)(-12345), false, "0A02CFC7")] [InlineData(AsnEncodingRules.BER, (ReadEnumerated.LongBacked)(-1), true, "8001FF")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.LongBacked)int.MinValue, true, "800480000000")] [InlineData(AsnEncodingRules.DER, (ReadEnumerated.LongBacked)int.MaxValue, false, "0A047FFFFFFF")] [InlineData(AsnEncodingRules.BER, (ReadEnumerated.LongBacked)long.MinValue, false, "0A088000000000000000")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.LongBacked)long.MaxValue, true, "80087FFFFFFFFFFFFFFF")] public void VerifyWriteEnumerated_Long( AsnEncodingRules ruleSet, ReadEnumerated.LongBacked value, bool customTag, string expectedHex) { AsnWriter writer = new AsnWriter(ruleSet); if (customTag) { writer.WriteEnumeratedValue(value, new Asn1Tag(TagClass.ContextSpecific, 0)); } else { writer.WriteEnumeratedValue(value); } Verify(writer, expectedHex); } [Theory] [InlineData(AsnEncodingRules.BER, ReadEnumerated.ULongBacked.Zero, false, "0A0100")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.ULongBacked.Zero, true, "C10100")] [InlineData(AsnEncodingRules.DER, ReadEnumerated.ULongBacked.Fluff, false, "0A0900FACEF00DCAFEBEEF")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.ULongBacked.Fluff, true, "C10900FACEF00DCAFEBEEF")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.ULongBacked)11, false, "0A010B")] [InlineData(AsnEncodingRules.DER, (ReadEnumerated.ULongBacked)short.MaxValue, false, "0A027FFF")] [InlineData(AsnEncodingRules.BER, (ReadEnumerated.ULongBacked)ushort.MaxValue, true, "C10300FFFF")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.ULongBacked)long.MaxValue, true, "C1087FFFFFFFFFFFFFFF")] [InlineData(AsnEncodingRules.DER, (ReadEnumerated.ULongBacked)ulong.MaxValue, false, "0A0900FFFFFFFFFFFFFFFF")] public void VerifyWriteEnumerated_ULong( AsnEncodingRules ruleSet, ReadEnumerated.ULongBacked value, bool customTag, string expectedHex) { AsnWriter writer = new AsnWriter(ruleSet); if (customTag) { writer.WriteEnumeratedValue(value, new Asn1Tag(TagClass.Private, 1)); } else { writer.WriteEnumeratedValue(value); } Verify(writer, expectedHex); } [Theory] [InlineData(AsnEncodingRules.BER)] [InlineData(AsnEncodingRules.CER)] [InlineData(AsnEncodingRules.DER)] public void VerifyFlagsBased(AsnEncodingRules ruleSet) { AsnWriter writer = new AsnWriter(ruleSet); AssertExtensions.Throws<ArgumentException>( "tEnum", () => writer.WriteEnumeratedValue(OpenFlags.IncludeArchived)); AssertExtensions.Throws<ArgumentException>( "tEnum", () => writer.WriteEnumeratedValue( OpenFlags.IncludeArchived, new Asn1Tag(TagClass.ContextSpecific, 13))); AssertExtensions.Throws<ArgumentException>( "tEnum", () => writer.WriteEnumeratedValue((Enum)OpenFlags.IncludeArchived)); AssertExtensions.Throws<ArgumentException>( "tEnum", () => writer.WriteEnumeratedValue( (Enum)OpenFlags.IncludeArchived, new Asn1Tag(TagClass.ContextSpecific, 13))); } [Theory] [InlineData(AsnEncodingRules.BER)] [InlineData(AsnEncodingRules.CER)] [InlineData(AsnEncodingRules.DER)] public void VerifyNull(AsnEncodingRules ruleSet) { AsnWriter writer = new AsnWriter(ruleSet); AssertExtensions.Throws<ArgumentException>( "tag", () => writer.WriteEnumeratedValue(ReadEnumerated.IntBacked.Pillow, Asn1Tag.Null)); AssertExtensions.Throws<ArgumentException>( "tag", () => writer.WriteEnumeratedValue((Enum)ReadEnumerated.IntBacked.Pillow, Asn1Tag.Null)); } [Theory] [InlineData(AsnEncodingRules.BER)] [InlineData(AsnEncodingRules.CER)] [InlineData(AsnEncodingRules.DER)] public static void VerifyWriteEnumeratedValue_NonNull(AsnEncodingRules ruleSet) { AsnWriter writer = new AsnWriter(ruleSet); AssertExtensions.Throws<ArgumentNullException>( "value", () => writer.WriteEnumeratedValue(null)); AssertExtensions.Throws<ArgumentNullException>( "value", () => writer.WriteEnumeratedValue( null, new Asn1Tag(TagClass.ContextSpecific, 1))); } [Theory] [InlineData(AsnEncodingRules.BER)] [InlineData(AsnEncodingRules.CER)] [InlineData(AsnEncodingRules.DER)] public static void VerifyWriteEnumeratedValue_Object(AsnEncodingRules ruleSet) { AsnWriter objWriter = new AsnWriter(ruleSet); AsnWriter genWriter = new AsnWriter(ruleSet); genWriter.WriteEnumeratedValue(ReadEnumerated.UIntBacked.Fluff); objWriter.WriteEnumeratedValue((Enum)ReadEnumerated.UIntBacked.Fluff); genWriter.WriteEnumeratedValue(ReadEnumerated.SByteBacked.Fluff); objWriter.WriteEnumeratedValue((Enum)ReadEnumerated.SByteBacked.Fluff); genWriter.WriteEnumeratedValue(ReadEnumerated.ULongBacked.Fluff); objWriter.WriteEnumeratedValue((Enum)ReadEnumerated.ULongBacked.Fluff); Verify(objWriter, genWriter.Encode().ByteArrayToHex()); } [Theory] [InlineData(AsnEncodingRules.BER)] [InlineData(AsnEncodingRules.CER)] [InlineData(AsnEncodingRules.DER)] public static void VerifyWriteEnumeratedValue_Object_WithTag(AsnEncodingRules ruleSet) { AsnWriter objWriter = new AsnWriter(ruleSet); AsnWriter genWriter = new AsnWriter(ruleSet); Asn1Tag tag = new Asn1Tag(TagClass.ContextSpecific, 52); genWriter.WriteEnumeratedValue(ReadEnumerated.UIntBacked.Fluff, tag); objWriter.WriteEnumeratedValue((Enum)ReadEnumerated.UIntBacked.Fluff, tag); tag = new Asn1Tag(TagClass.Private, 4); genWriter.WriteEnumeratedValue(ReadEnumerated.SByteBacked.Fluff, tag); objWriter.WriteEnumeratedValue((Enum)ReadEnumerated.SByteBacked.Fluff, tag); tag = new Asn1Tag(TagClass.Application, 75); genWriter.WriteEnumeratedValue(ReadEnumerated.ULongBacked.Fluff, tag); objWriter.WriteEnumeratedValue((Enum)ReadEnumerated.ULongBacked.Fluff, tag); Verify(objWriter, genWriter.Encode().ByteArrayToHex()); } [Theory] [InlineData(AsnEncodingRules.BER)] [InlineData(AsnEncodingRules.CER)] [InlineData(AsnEncodingRules.DER)] public void VerifyWriteEnumeratedValue_ConstructedIgnored(AsnEncodingRules ruleSet) { AsnWriter writer = new AsnWriter(ruleSet); writer.WriteEnumeratedValue( ReadEnumerated.ULongBacked.Fluff, new Asn1Tag(UniversalTagNumber.Enumerated, isConstructed: true)); writer.WriteEnumeratedValue( (Enum)ReadEnumerated.SByteBacked.Fluff, new Asn1Tag(TagClass.ContextSpecific, 0, isConstructed: true)); Verify(writer, "0A0900FACEF00DCAFEBEEF" + "800153"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Formats.Asn1.Tests.Reader; using System.Security.Cryptography.X509Certificates; using Test.Cryptography; using Xunit; namespace System.Formats.Asn1.Tests.Writer { public class WriteEnumerated : Asn1WriterTests { [Theory] [InlineData(AsnEncodingRules.BER, ReadEnumerated.SByteBacked.Zero, false, "0A0100")] [InlineData(AsnEncodingRules.CER, ReadEnumerated.SByteBacked.Pillow, true, "9E01EF")] [InlineData(AsnEncodingRules.DER, ReadEnumerated.SByteBacked.Fluff, false, "0A0153")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.SByteBacked.Fluff, true, "9E0153")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.SByteBacked)(-127), true, "9E0181")] public void VerifyWriteEnumerated_SByte( AsnEncodingRules ruleSet, ReadEnumerated.SByteBacked value, bool customTag, string expectedHex) { AsnWriter writer = new AsnWriter(ruleSet); if (customTag) { writer.WriteEnumeratedValue(value, new Asn1Tag(TagClass.ContextSpecific, 30)); } else { writer.WriteEnumeratedValue(value); } Verify(writer, expectedHex); } [Theory] [InlineData(AsnEncodingRules.BER, ReadEnumerated.ByteBacked.Zero, false, "0A0100")] [InlineData(AsnEncodingRules.CER, ReadEnumerated.ByteBacked.NotFluffy, true, "9A010B")] [InlineData(AsnEncodingRules.DER, ReadEnumerated.ByteBacked.Fluff, false, "0A010C")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.ByteBacked.Fluff, true, "9A010C")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.ByteBacked)253, false, "0A0200FD")] public void VerifyWriteEnumerated_Byte( AsnEncodingRules ruleSet, ReadEnumerated.ByteBacked value, bool customTag, string expectedHex) { AsnWriter writer = new AsnWriter(ruleSet); if (customTag) { writer.WriteEnumeratedValue(value, new Asn1Tag(TagClass.ContextSpecific, 26)); } else { writer.WriteEnumeratedValue(value); } Verify(writer, expectedHex); } [Theory] [InlineData(AsnEncodingRules.BER, ReadEnumerated.ShortBacked.Zero, true, "DF81540100")] [InlineData(AsnEncodingRules.CER, ReadEnumerated.ShortBacked.Pillow, true, "DF815402FC00")] [InlineData(AsnEncodingRules.DER, ReadEnumerated.ShortBacked.Fluff, false, "0A020209")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.ShortBacked.Fluff, true, "DF8154020209")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.ShortBacked)25321, false, "0A0262E9")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.ShortBacked)(-12345), false, "0A02CFC7")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.ShortBacked)(-1), true, "DF815401FF")] public void VerifyWriteEnumerated_Short( AsnEncodingRules ruleSet, ReadEnumerated.ShortBacked value, bool customTag, string expectedHex) { AsnWriter writer = new AsnWriter(ruleSet); if (customTag) { writer.WriteEnumeratedValue(value, new Asn1Tag(TagClass.Private, 212)); } else { writer.WriteEnumeratedValue(value); } Verify(writer, expectedHex); } [Theory] [InlineData(AsnEncodingRules.BER, ReadEnumerated.UShortBacked.Zero, false, "0A0100")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.UShortBacked.Zero, true, "4D0100")] [InlineData(AsnEncodingRules.DER, ReadEnumerated.UShortBacked.Fluff, false, "0A03008000")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.UShortBacked.Fluff, true, "4D03008000")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.UShortBacked)11, false, "0A010B")] [InlineData(AsnEncodingRules.DER, (ReadEnumerated.UShortBacked)short.MaxValue, false, "0A027FFF")] [InlineData(AsnEncodingRules.BER, (ReadEnumerated.UShortBacked)ushort.MaxValue, true, "4D0300FFFF")] public void VerifyWriteEnumerated_UShort( AsnEncodingRules ruleSet, ReadEnumerated.UShortBacked value, bool customTag, string expectedHex) { AsnWriter writer = new AsnWriter(ruleSet); if (customTag) { writer.WriteEnumeratedValue(value, new Asn1Tag(TagClass.Application, 13)); } else { writer.WriteEnumeratedValue(value); } Verify(writer, expectedHex); } [Theory] [InlineData(AsnEncodingRules.BER, ReadEnumerated.IntBacked.Zero, true, "5F81FF7F0100")] [InlineData(AsnEncodingRules.CER, ReadEnumerated.IntBacked.Pillow, true, "5F81FF7F03FEFFFF")] [InlineData(AsnEncodingRules.DER, ReadEnumerated.IntBacked.Fluff, false, "0A03010001")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.IntBacked.Fluff, true, "5F81FF7F03010001")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.IntBacked)25321, false, "0A0262E9")] [InlineData(AsnEncodingRules.DER, (ReadEnumerated.IntBacked)(-12345), false, "0A02CFC7")] [InlineData(AsnEncodingRules.BER, (ReadEnumerated.IntBacked)(-1), true, "5F81FF7F01FF")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.IntBacked)int.MinValue, true, "5F81FF7F0480000000")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.IntBacked)int.MaxValue, false, "0A047FFFFFFF")] public void VerifyWriteEnumerated_Int( AsnEncodingRules ruleSet, ReadEnumerated.IntBacked value, bool customTag, string expectedHex) { AsnWriter writer = new AsnWriter(ruleSet); if (customTag) { writer.WriteEnumeratedValue(value, new Asn1Tag(TagClass.Application, short.MaxValue)); } else { writer.WriteEnumeratedValue(value); } Verify(writer, expectedHex); } [Theory] [InlineData(AsnEncodingRules.BER, ReadEnumerated.UIntBacked.Zero, false, "0A0100")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.UIntBacked.Zero, true, "9F610100")] [InlineData(AsnEncodingRules.DER, ReadEnumerated.UIntBacked.Fluff, false, "0A050080000005")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.UIntBacked.Fluff, true, "9F61050080000005")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.UIntBacked)11, false, "0A010B")] [InlineData(AsnEncodingRules.DER, (ReadEnumerated.UIntBacked)short.MaxValue, false, "0A027FFF")] [InlineData(AsnEncodingRules.BER, (ReadEnumerated.UIntBacked)ushort.MaxValue, true, "9F610300FFFF")] public void VerifyWriteEnumerated_UInt( AsnEncodingRules ruleSet, ReadEnumerated.UIntBacked value, bool customTag, string expectedHex) { AsnWriter writer = new AsnWriter(ruleSet); if (customTag) { writer.WriteEnumeratedValue(value, new Asn1Tag(TagClass.ContextSpecific, 97)); } else { writer.WriteEnumeratedValue(value); } Verify(writer, expectedHex); } [Theory] [InlineData(AsnEncodingRules.BER, ReadEnumerated.LongBacked.Zero, true, "800100")] [InlineData(AsnEncodingRules.CER, ReadEnumerated.LongBacked.Pillow, true, "8005FF00000000")] [InlineData(AsnEncodingRules.DER, ReadEnumerated.LongBacked.Fluff, false, "0A050200000441")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.LongBacked.Fluff, true, "80050200000441")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.LongBacked)25321, false, "0A0262E9")] [InlineData(AsnEncodingRules.DER, (ReadEnumerated.LongBacked)(-12345), false, "0A02CFC7")] [InlineData(AsnEncodingRules.BER, (ReadEnumerated.LongBacked)(-1), true, "8001FF")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.LongBacked)int.MinValue, true, "800480000000")] [InlineData(AsnEncodingRules.DER, (ReadEnumerated.LongBacked)int.MaxValue, false, "0A047FFFFFFF")] [InlineData(AsnEncodingRules.BER, (ReadEnumerated.LongBacked)long.MinValue, false, "0A088000000000000000")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.LongBacked)long.MaxValue, true, "80087FFFFFFFFFFFFFFF")] public void VerifyWriteEnumerated_Long( AsnEncodingRules ruleSet, ReadEnumerated.LongBacked value, bool customTag, string expectedHex) { AsnWriter writer = new AsnWriter(ruleSet); if (customTag) { writer.WriteEnumeratedValue(value, new Asn1Tag(TagClass.ContextSpecific, 0)); } else { writer.WriteEnumeratedValue(value); } Verify(writer, expectedHex); } [Theory] [InlineData(AsnEncodingRules.BER, ReadEnumerated.ULongBacked.Zero, false, "0A0100")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.ULongBacked.Zero, true, "C10100")] [InlineData(AsnEncodingRules.DER, ReadEnumerated.ULongBacked.Fluff, false, "0A0900FACEF00DCAFEBEEF")] [InlineData(AsnEncodingRules.BER, ReadEnumerated.ULongBacked.Fluff, true, "C10900FACEF00DCAFEBEEF")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.ULongBacked)11, false, "0A010B")] [InlineData(AsnEncodingRules.DER, (ReadEnumerated.ULongBacked)short.MaxValue, false, "0A027FFF")] [InlineData(AsnEncodingRules.BER, (ReadEnumerated.ULongBacked)ushort.MaxValue, true, "C10300FFFF")] [InlineData(AsnEncodingRules.CER, (ReadEnumerated.ULongBacked)long.MaxValue, true, "C1087FFFFFFFFFFFFFFF")] [InlineData(AsnEncodingRules.DER, (ReadEnumerated.ULongBacked)ulong.MaxValue, false, "0A0900FFFFFFFFFFFFFFFF")] public void VerifyWriteEnumerated_ULong( AsnEncodingRules ruleSet, ReadEnumerated.ULongBacked value, bool customTag, string expectedHex) { AsnWriter writer = new AsnWriter(ruleSet); if (customTag) { writer.WriteEnumeratedValue(value, new Asn1Tag(TagClass.Private, 1)); } else { writer.WriteEnumeratedValue(value); } Verify(writer, expectedHex); } [Theory] [InlineData(AsnEncodingRules.BER)] [InlineData(AsnEncodingRules.CER)] [InlineData(AsnEncodingRules.DER)] public void VerifyFlagsBased(AsnEncodingRules ruleSet) { AsnWriter writer = new AsnWriter(ruleSet); AssertExtensions.Throws<ArgumentException>( "tEnum", () => writer.WriteEnumeratedValue(OpenFlags.IncludeArchived)); AssertExtensions.Throws<ArgumentException>( "tEnum", () => writer.WriteEnumeratedValue( OpenFlags.IncludeArchived, new Asn1Tag(TagClass.ContextSpecific, 13))); AssertExtensions.Throws<ArgumentException>( "tEnum", () => writer.WriteEnumeratedValue((Enum)OpenFlags.IncludeArchived)); AssertExtensions.Throws<ArgumentException>( "tEnum", () => writer.WriteEnumeratedValue( (Enum)OpenFlags.IncludeArchived, new Asn1Tag(TagClass.ContextSpecific, 13))); } [Theory] [InlineData(AsnEncodingRules.BER)] [InlineData(AsnEncodingRules.CER)] [InlineData(AsnEncodingRules.DER)] public void VerifyNull(AsnEncodingRules ruleSet) { AsnWriter writer = new AsnWriter(ruleSet); AssertExtensions.Throws<ArgumentException>( "tag", () => writer.WriteEnumeratedValue(ReadEnumerated.IntBacked.Pillow, Asn1Tag.Null)); AssertExtensions.Throws<ArgumentException>( "tag", () => writer.WriteEnumeratedValue((Enum)ReadEnumerated.IntBacked.Pillow, Asn1Tag.Null)); } [Theory] [InlineData(AsnEncodingRules.BER)] [InlineData(AsnEncodingRules.CER)] [InlineData(AsnEncodingRules.DER)] public static void VerifyWriteEnumeratedValue_NonNull(AsnEncodingRules ruleSet) { AsnWriter writer = new AsnWriter(ruleSet); AssertExtensions.Throws<ArgumentNullException>( "value", () => writer.WriteEnumeratedValue(null)); AssertExtensions.Throws<ArgumentNullException>( "value", () => writer.WriteEnumeratedValue( null, new Asn1Tag(TagClass.ContextSpecific, 1))); } [Theory] [InlineData(AsnEncodingRules.BER)] [InlineData(AsnEncodingRules.CER)] [InlineData(AsnEncodingRules.DER)] public static void VerifyWriteEnumeratedValue_Object(AsnEncodingRules ruleSet) { AsnWriter objWriter = new AsnWriter(ruleSet); AsnWriter genWriter = new AsnWriter(ruleSet); genWriter.WriteEnumeratedValue(ReadEnumerated.UIntBacked.Fluff); objWriter.WriteEnumeratedValue((Enum)ReadEnumerated.UIntBacked.Fluff); genWriter.WriteEnumeratedValue(ReadEnumerated.SByteBacked.Fluff); objWriter.WriteEnumeratedValue((Enum)ReadEnumerated.SByteBacked.Fluff); genWriter.WriteEnumeratedValue(ReadEnumerated.ULongBacked.Fluff); objWriter.WriteEnumeratedValue((Enum)ReadEnumerated.ULongBacked.Fluff); Verify(objWriter, genWriter.Encode().ByteArrayToHex()); } [Theory] [InlineData(AsnEncodingRules.BER)] [InlineData(AsnEncodingRules.CER)] [InlineData(AsnEncodingRules.DER)] public static void VerifyWriteEnumeratedValue_Object_WithTag(AsnEncodingRules ruleSet) { AsnWriter objWriter = new AsnWriter(ruleSet); AsnWriter genWriter = new AsnWriter(ruleSet); Asn1Tag tag = new Asn1Tag(TagClass.ContextSpecific, 52); genWriter.WriteEnumeratedValue(ReadEnumerated.UIntBacked.Fluff, tag); objWriter.WriteEnumeratedValue((Enum)ReadEnumerated.UIntBacked.Fluff, tag); tag = new Asn1Tag(TagClass.Private, 4); genWriter.WriteEnumeratedValue(ReadEnumerated.SByteBacked.Fluff, tag); objWriter.WriteEnumeratedValue((Enum)ReadEnumerated.SByteBacked.Fluff, tag); tag = new Asn1Tag(TagClass.Application, 75); genWriter.WriteEnumeratedValue(ReadEnumerated.ULongBacked.Fluff, tag); objWriter.WriteEnumeratedValue((Enum)ReadEnumerated.ULongBacked.Fluff, tag); Verify(objWriter, genWriter.Encode().ByteArrayToHex()); } [Theory] [InlineData(AsnEncodingRules.BER)] [InlineData(AsnEncodingRules.CER)] [InlineData(AsnEncodingRules.DER)] public void VerifyWriteEnumeratedValue_ConstructedIgnored(AsnEncodingRules ruleSet) { AsnWriter writer = new AsnWriter(ruleSet); writer.WriteEnumeratedValue( ReadEnumerated.ULongBacked.Fluff, new Asn1Tag(UniversalTagNumber.Enumerated, isConstructed: true)); writer.WriteEnumeratedValue( (Enum)ReadEnumerated.SByteBacked.Fluff, new Asn1Tag(TagClass.ContextSpecific, 0, isConstructed: true)); Verify(writer, "0A0900FACEF00DCAFEBEEF" + "800153"); } } }
-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/DefaultECDsaProvider.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.Runtime.InteropServices; namespace System.Security.Cryptography.EcDsa.Tests { public partial class ECDsaProvider : IECDsaProvider { public bool IsCurveValid(Oid oid) { if (PlatformDetection.IsOSXLike) { return false; } if (!string.IsNullOrEmpty(oid.Value)) { // Value is passed before FriendlyName return IsValueOrFriendlyNameValid(oid.Value); } return IsValueOrFriendlyNameValid(oid.FriendlyName); } public bool ExplicitCurvesSupported { get { if (PlatformDetection.IsOSXLike) { return false; } return true; } } private static bool IsValueOrFriendlyNameValid(string friendlyNameOrValue) { if (string.IsNullOrEmpty(friendlyNameOrValue)) { return false; } IntPtr key = Interop.Crypto.EcKeyCreateByOid(friendlyNameOrValue); if (key != IntPtr.Zero) { Interop.Crypto.EcKeyDestroy(key); return true; } return false; } } } internal static partial class Interop { internal static partial class Crypto { [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyCreateByOid")] internal static extern System.IntPtr EcKeyCreateByOid(string oid); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyDestroy")] internal static extern void EcKeyDestroy(System.IntPtr r); } }
// 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 System.Security.Cryptography.EcDsa.Tests { public partial class ECDsaProvider : IECDsaProvider { public bool IsCurveValid(Oid oid) { if (PlatformDetection.IsOSXLike) { return false; } if (!string.IsNullOrEmpty(oid.Value)) { // Value is passed before FriendlyName return IsValueOrFriendlyNameValid(oid.Value); } return IsValueOrFriendlyNameValid(oid.FriendlyName); } public bool ExplicitCurvesSupported { get { if (PlatformDetection.IsOSXLike) { return false; } return true; } } private static bool IsValueOrFriendlyNameValid(string friendlyNameOrValue) { if (string.IsNullOrEmpty(friendlyNameOrValue)) { return false; } IntPtr key = Interop.Crypto.EcKeyCreateByOid(friendlyNameOrValue); if (key != IntPtr.Zero) { Interop.Crypto.EcKeyDestroy(key); return true; } return false; } } } internal static partial class Interop { internal static partial class Crypto { [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyCreateByOid")] internal static extern System.IntPtr EcKeyCreateByOid(string oid); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyDestroy")] internal static extern void EcKeyDestroy(System.IntPtr r); } }
-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.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.CrossProcess.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.Globalization; using System.Security.Principal; using System.Threading.Tasks; using Microsoft.DotNet.RemoteExecutor; using Microsoft.Win32.SafeHandles; using Xunit; namespace System.IO.Pipes.Tests { public sealed class NamedPipeTest_CrossProcess { [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void InheritHandles_AvailableInChildProcess() { string pipeName = PipeStreamConformanceTests.GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.None, TokenImpersonationLevel.None, HandleInheritability.Inheritable)) { Task.WaitAll(server.WaitForConnectionAsync(), client.ConnectAsync()); using (RemoteExecutor.Invoke(new Action<string>(ChildFunc), client.SafePipeHandle.DangerousGetHandle().ToString())) { client.Dispose(); for (int i = 0; i < 5; i++) { Assert.Equal(i, server.ReadByte()); } } } void ChildFunc(string handle) { using (var childClient = new NamedPipeClientStream(PipeDirection.Out, isAsync: false, isConnected: true, new SafePipeHandle((IntPtr)long.Parse(handle, CultureInfo.InvariantCulture), ownsHandle: true))) { for (int i = 0; i < 5; i++) { childClient.WriteByte((byte)i); } } } } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void PingPong_Sync() { // Create names for two pipes string outName = PipeStreamConformanceTests.GetUniquePipeName(); string inName = PipeStreamConformanceTests.GetUniquePipeName(); // Create the two named pipes, one for each direction, then create // another process with which to communicate using (var outbound = new NamedPipeServerStream(outName, PipeDirection.Out)) using (var inbound = new NamedPipeClientStream(".", inName, PipeDirection.In)) using (RemoteExecutor.Invoke(new Action<string, string>(PingPong_OtherProcess), outName, inName)) { // Wait for both pipes to be connected Task.WaitAll(outbound.WaitForConnectionAsync(), inbound.ConnectAsync()); // Repeatedly write then read a byte to and from the other process for (byte i = 0; i < 10; i++) { outbound.WriteByte(i); int received = inbound.ReadByte(); Assert.Equal(i, received); } } } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public async Task PingPong_Async() { // Create names for two pipes string outName = PipeStreamConformanceTests.GetUniquePipeName(); string inName = PipeStreamConformanceTests.GetUniquePipeName(); // Create the two named pipes, one for each direction, then create // another process with which to communicate using (var outbound = new NamedPipeServerStream(outName, PipeDirection.Out)) using (var inbound = new NamedPipeClientStream(".", inName, PipeDirection.In)) using (RemoteExecutor.Invoke(new Action<string, string>(PingPong_OtherProcess), outName, inName)) { // Wait for both pipes to be connected await Task.WhenAll(outbound.WaitForConnectionAsync(), inbound.ConnectAsync()); // Repeatedly write then read a byte to and from the other process var data = new byte[1]; for (byte i = 0; i < 10; i++) { data[0] = i; await outbound.WriteAsync(data, 0, data.Length); data[0] = 0; int received = await inbound.ReadAsync(data, 0, data.Length); Assert.Equal(1, received); Assert.Equal(i, data[0]); } } } private static void PingPong_OtherProcess(string inName, string outName) { // Create pipes with the supplied names using (var inbound = new NamedPipeClientStream(".", inName, PipeDirection.In)) using (var outbound = new NamedPipeServerStream(outName, PipeDirection.Out)) { // Wait for the connections to be established Task.WaitAll(inbound.ConnectAsync(), outbound.WaitForConnectionAsync()); // Repeatedly read then write bytes from and to the other process for (int i = 0; i < 10; i++) { int b = inbound.ReadByte(); outbound.WriteByte((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.Diagnostics; using System.Globalization; using System.Security.Principal; using System.Threading.Tasks; using Microsoft.DotNet.RemoteExecutor; using Microsoft.Win32.SafeHandles; using Xunit; namespace System.IO.Pipes.Tests { public sealed class NamedPipeTest_CrossProcess { [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void InheritHandles_AvailableInChildProcess() { string pipeName = PipeStreamConformanceTests.GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.None, TokenImpersonationLevel.None, HandleInheritability.Inheritable)) { Task.WaitAll(server.WaitForConnectionAsync(), client.ConnectAsync()); using (RemoteExecutor.Invoke(new Action<string>(ChildFunc), client.SafePipeHandle.DangerousGetHandle().ToString())) { client.Dispose(); for (int i = 0; i < 5; i++) { Assert.Equal(i, server.ReadByte()); } } } void ChildFunc(string handle) { using (var childClient = new NamedPipeClientStream(PipeDirection.Out, isAsync: false, isConnected: true, new SafePipeHandle((IntPtr)long.Parse(handle, CultureInfo.InvariantCulture), ownsHandle: true))) { for (int i = 0; i < 5; i++) { childClient.WriteByte((byte)i); } } } } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void PingPong_Sync() { // Create names for two pipes string outName = PipeStreamConformanceTests.GetUniquePipeName(); string inName = PipeStreamConformanceTests.GetUniquePipeName(); // Create the two named pipes, one for each direction, then create // another process with which to communicate using (var outbound = new NamedPipeServerStream(outName, PipeDirection.Out)) using (var inbound = new NamedPipeClientStream(".", inName, PipeDirection.In)) using (RemoteExecutor.Invoke(new Action<string, string>(PingPong_OtherProcess), outName, inName)) { // Wait for both pipes to be connected Task.WaitAll(outbound.WaitForConnectionAsync(), inbound.ConnectAsync()); // Repeatedly write then read a byte to and from the other process for (byte i = 0; i < 10; i++) { outbound.WriteByte(i); int received = inbound.ReadByte(); Assert.Equal(i, received); } } } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public async Task PingPong_Async() { // Create names for two pipes string outName = PipeStreamConformanceTests.GetUniquePipeName(); string inName = PipeStreamConformanceTests.GetUniquePipeName(); // Create the two named pipes, one for each direction, then create // another process with which to communicate using (var outbound = new NamedPipeServerStream(outName, PipeDirection.Out)) using (var inbound = new NamedPipeClientStream(".", inName, PipeDirection.In)) using (RemoteExecutor.Invoke(new Action<string, string>(PingPong_OtherProcess), outName, inName)) { // Wait for both pipes to be connected await Task.WhenAll(outbound.WaitForConnectionAsync(), inbound.ConnectAsync()); // Repeatedly write then read a byte to and from the other process var data = new byte[1]; for (byte i = 0; i < 10; i++) { data[0] = i; await outbound.WriteAsync(data, 0, data.Length); data[0] = 0; int received = await inbound.ReadAsync(data, 0, data.Length); Assert.Equal(1, received); Assert.Equal(i, data[0]); } } } private static void PingPong_OtherProcess(string inName, string outName) { // Create pipes with the supplied names using (var inbound = new NamedPipeClientStream(".", inName, PipeDirection.In)) using (var outbound = new NamedPipeServerStream(outName, PipeDirection.Out)) { // Wait for the connections to be established Task.WaitAll(inbound.ConnectAsync(), outbound.WaitForConnectionAsync()); // Repeatedly read then write bytes from and to the other process for (int i = 0; i < 10; i++) { int b = inbound.ReadByte(); outbound.WriteByte((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/tests/Loader/classloader/explicitlayout/NestedStructs/case01.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.InteropServices; [StructLayout(LayoutKind.Explicit, Size = 24)] public struct ComplexStruct { [FieldOffset(0)] public object? Object; [FieldOffset(0)] public InnerStruct Inner; [FieldOffset(8)] public double Double; [FieldOffset(8)] public ulong High; [FieldOffset(16)] public ulong Low; } [StructLayout(LayoutKind.Explicit, Size = 16)] public struct InnerStruct { [FieldOffset(0)] public object? Object; [FieldOffset(8)] public int High; [FieldOffset(12)] public int Low; } public class Test_NestedStructsWithExplicitLayout_Case01 { private ComplexStruct currentCount = default; private void IncrementCount() { var x = new ComplexStruct(); x.Inner.High = currentCount.Inner.High + 1; currentCount = x; } public static int Main () { try { var instance = new Test_NestedStructsWithExplicitLayout_Case01(); instance.IncrementCount(); var result = 99 + instance.currentCount.Inner.High; if (result == 100) { Console.WriteLine("PASS: union of Explict + Explicit works correctly"); } return result; } catch (TypeLoadException e) { Console.WriteLine("FAIL: type was not loaded"); return 101; } catch (Exception e) { 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; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit, Size = 24)] public struct ComplexStruct { [FieldOffset(0)] public object? Object; [FieldOffset(0)] public InnerStruct Inner; [FieldOffset(8)] public double Double; [FieldOffset(8)] public ulong High; [FieldOffset(16)] public ulong Low; } [StructLayout(LayoutKind.Explicit, Size = 16)] public struct InnerStruct { [FieldOffset(0)] public object? Object; [FieldOffset(8)] public int High; [FieldOffset(12)] public int Low; } public class Test_NestedStructsWithExplicitLayout_Case01 { private ComplexStruct currentCount = default; private void IncrementCount() { var x = new ComplexStruct(); x.Inner.High = currentCount.Inner.High + 1; currentCount = x; } public static int Main () { try { var instance = new Test_NestedStructsWithExplicitLayout_Case01(); instance.IncrementCount(); var result = 99 + instance.currentCount.Inner.High; if (result == 100) { Console.WriteLine("PASS: union of Explict + Explicit works correctly"); } return result; } catch (TypeLoadException e) { Console.WriteLine("FAIL: type was not loaded"); return 101; } catch (Exception e) { 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/coreclr/tools/Common/Compiler/Logging/CompilerGeneratedState.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 Internal.TypeSystem; using Internal.TypeSystem.Ecma; namespace ILCompiler.Logging { // Currently this is implemented using heuristics public class CompilerGeneratedState { private static bool HasRoslynCompilerGeneratedName(DefType type) => type.Name.Contains('<') || (type.ContainingType != null && HasRoslynCompilerGeneratedName(type.ContainingType)); public static MethodDesc GetUserDefinedMethodForCompilerGeneratedMember(MethodDesc sourceMember) { var compilerGeneratedType = sourceMember.OwningType.GetTypeDefinition() as EcmaType; if (compilerGeneratedType == null) return null; // Only handle async or iterator state machine // So go to the declaring type and check if it's compiler generated (as a perf optimization) if (!HasRoslynCompilerGeneratedName(compilerGeneratedType) || compilerGeneratedType.ContainingType == null) return null; // Now go to its declaring type and search all methods to find the one which points to the type as its // state machine implementation. foreach (EcmaMethod method in compilerGeneratedType.ContainingType.GetMethods()) { var decodedAttribute = method.GetDecodedCustomAttribute("System.Runtime.CompilerServices", "AsyncIteratorStateMachineAttribute") ?? method.GetDecodedCustomAttribute("System.Runtime.CompilerServices", "AsyncStateMachineAttribute") ?? method.GetDecodedCustomAttribute("System.Runtime.CompilerServices", "IteratorStateMachineAttribute"); if (!decodedAttribute.HasValue) continue; if (decodedAttribute.Value.FixedArguments.Length != 1 || decodedAttribute.Value.FixedArguments[0].Value is not TypeDesc stateMachineType) continue; if (stateMachineType == compilerGeneratedType) return method; } 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.Collections.Generic; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; namespace ILCompiler.Logging { // Currently this is implemented using heuristics public class CompilerGeneratedState { private static bool HasRoslynCompilerGeneratedName(DefType type) => type.Name.Contains('<') || (type.ContainingType != null && HasRoslynCompilerGeneratedName(type.ContainingType)); public static MethodDesc GetUserDefinedMethodForCompilerGeneratedMember(MethodDesc sourceMember) { var compilerGeneratedType = sourceMember.OwningType.GetTypeDefinition() as EcmaType; if (compilerGeneratedType == null) return null; // Only handle async or iterator state machine // So go to the declaring type and check if it's compiler generated (as a perf optimization) if (!HasRoslynCompilerGeneratedName(compilerGeneratedType) || compilerGeneratedType.ContainingType == null) return null; // Now go to its declaring type and search all methods to find the one which points to the type as its // state machine implementation. foreach (EcmaMethod method in compilerGeneratedType.ContainingType.GetMethods()) { var decodedAttribute = method.GetDecodedCustomAttribute("System.Runtime.CompilerServices", "AsyncIteratorStateMachineAttribute") ?? method.GetDecodedCustomAttribute("System.Runtime.CompilerServices", "AsyncStateMachineAttribute") ?? method.GetDecodedCustomAttribute("System.Runtime.CompilerServices", "IteratorStateMachineAttribute"); if (!decodedAttribute.HasValue) continue; if (decodedAttribute.Value.FixedArguments.Length != 1 || decodedAttribute.Value.FixedArguments[0].Value is not TypeDesc stateMachineType) continue; if (stateMachineType == compilerGeneratedType) return method; } 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/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/AbsoluteDifferenceWideningLower.Vector64.SByte.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 AbsoluteDifferenceWideningLower_Vector64_SByte() { var test = new SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte(); 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__AbsoluteDifferenceWideningLower_Vector64_SByte { 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(SByte[] inArray1, SByte[] inArray2, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); 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<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, 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<SByte> _fld1; public Vector64<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte testClass) { var result = AdvSimd.AbsoluteDifferenceWideningLower(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte testClass) { fixed (Vector64<SByte>* pFld1 = &_fld1) fixed (Vector64<SByte>* pFld2 = &_fld2) { var result = AdvSimd.AbsoluteDifferenceWideningLower( AdvSimd.LoadVector64((SByte*)(pFld1)), AdvSimd.LoadVector64((SByte*)(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<Vector64<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector64<SByte> _clsVar1; private static Vector64<SByte> _clsVar2; private Vector64<SByte> _fld1; private Vector64<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); } public SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _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.AbsoluteDifferenceWideningLower( Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<SByte>>(_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.AbsoluteDifferenceWideningLower( AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((SByte*)(_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.AbsoluteDifferenceWideningLower), new Type[] { typeof(Vector64<SByte>), typeof(Vector64<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<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.AbsoluteDifferenceWideningLower), new Type[] { typeof(Vector64<SByte>), typeof(Vector64<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.AbsoluteDifferenceWideningLower( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<SByte>* pClsVar1 = &_clsVar1) fixed (Vector64<SByte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.AbsoluteDifferenceWideningLower( AdvSimd.LoadVector64((SByte*)(pClsVar1)), AdvSimd.LoadVector64((SByte*)(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<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr); var result = AdvSimd.AbsoluteDifferenceWideningLower(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((SByte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.AbsoluteDifferenceWideningLower(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte(); var result = AdvSimd.AbsoluteDifferenceWideningLower(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__AbsoluteDifferenceWideningLower_Vector64_SByte(); fixed (Vector64<SByte>* pFld1 = &test._fld1) fixed (Vector64<SByte>* pFld2 = &test._fld2) { var result = AdvSimd.AbsoluteDifferenceWideningLower( AdvSimd.LoadVector64((SByte*)(pFld1)), AdvSimd.LoadVector64((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.AbsoluteDifferenceWideningLower(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<SByte>* pFld1 = &_fld1) fixed (Vector64<SByte>* pFld2 = &_fld2) { var result = AdvSimd.AbsoluteDifferenceWideningLower( AdvSimd.LoadVector64((SByte*)(pFld1)), AdvSimd.LoadVector64((SByte*)(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.AbsoluteDifferenceWideningLower(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.AbsoluteDifferenceWideningLower( AdvSimd.LoadVector64((SByte*)(&test._fld1)), AdvSimd.LoadVector64((SByte*)(&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<SByte> op1, Vector64<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.AbsoluteDifferenceWidening(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AbsoluteDifferenceWideningLower)}<UInt16>(Vector64<SByte>, Vector64<SByte>): {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 AbsoluteDifferenceWideningLower_Vector64_SByte() { var test = new SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte(); 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__AbsoluteDifferenceWideningLower_Vector64_SByte { 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(SByte[] inArray1, SByte[] inArray2, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); 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<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, 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<SByte> _fld1; public Vector64<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte testClass) { var result = AdvSimd.AbsoluteDifferenceWideningLower(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte testClass) { fixed (Vector64<SByte>* pFld1 = &_fld1) fixed (Vector64<SByte>* pFld2 = &_fld2) { var result = AdvSimd.AbsoluteDifferenceWideningLower( AdvSimd.LoadVector64((SByte*)(pFld1)), AdvSimd.LoadVector64((SByte*)(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<Vector64<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector64<SByte> _clsVar1; private static Vector64<SByte> _clsVar2; private Vector64<SByte> _fld1; private Vector64<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); } public SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _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.AbsoluteDifferenceWideningLower( Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<SByte>>(_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.AbsoluteDifferenceWideningLower( AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((SByte*)(_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.AbsoluteDifferenceWideningLower), new Type[] { typeof(Vector64<SByte>), typeof(Vector64<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<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.AbsoluteDifferenceWideningLower), new Type[] { typeof(Vector64<SByte>), typeof(Vector64<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.AbsoluteDifferenceWideningLower( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<SByte>* pClsVar1 = &_clsVar1) fixed (Vector64<SByte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.AbsoluteDifferenceWideningLower( AdvSimd.LoadVector64((SByte*)(pClsVar1)), AdvSimd.LoadVector64((SByte*)(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<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr); var result = AdvSimd.AbsoluteDifferenceWideningLower(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((SByte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.AbsoluteDifferenceWideningLower(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AbsoluteDifferenceWideningLower_Vector64_SByte(); var result = AdvSimd.AbsoluteDifferenceWideningLower(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__AbsoluteDifferenceWideningLower_Vector64_SByte(); fixed (Vector64<SByte>* pFld1 = &test._fld1) fixed (Vector64<SByte>* pFld2 = &test._fld2) { var result = AdvSimd.AbsoluteDifferenceWideningLower( AdvSimd.LoadVector64((SByte*)(pFld1)), AdvSimd.LoadVector64((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.AbsoluteDifferenceWideningLower(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<SByte>* pFld1 = &_fld1) fixed (Vector64<SByte>* pFld2 = &_fld2) { var result = AdvSimd.AbsoluteDifferenceWideningLower( AdvSimd.LoadVector64((SByte*)(pFld1)), AdvSimd.LoadVector64((SByte*)(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.AbsoluteDifferenceWideningLower(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.AbsoluteDifferenceWideningLower( AdvSimd.LoadVector64((SByte*)(&test._fld1)), AdvSimd.LoadVector64((SByte*)(&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<SByte> op1, Vector64<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.AbsoluteDifferenceWidening(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AbsoluteDifferenceWideningLower)}<UInt16>(Vector64<SByte>, Vector64<SByte>): {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.Reflection.Emit/tests/MethodBuilder/MethodBuilderGetILGenerator.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; namespace System.Reflection.Emit.Tests { public class MethodBuilderGetILGenerator { [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))] [InlineData(20)] [InlineData(-10)] public void GetILGenerator_Int(int size) { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[0]); ILGenerator ilGenerator = method.GetILGenerator(size); int expectedReturn = 5; ilGenerator.Emit(OpCodes.Ldc_I4, expectedReturn); ilGenerator.Emit(OpCodes.Ret); Type createdType = type.CreateTypeInfo().AsType(); MethodInfo createdMethod = createdType.GetMethod("TestMethod"); Assert.Equal(expectedReturn, createdMethod.Invoke(null, null)); // Verify MetadataToken Assert.Equal(method.MetadataToken, createdMethod.MetadataToken); MethodInfo methodFromToken = (MethodInfo)type.Module.ResolveMethod(method.MetadataToken); Assert.Equal(createdMethod, methodFromToken); MemberInfo memberInfoFromToken = (MemberInfo)type.Module.ResolveMember(method.MetadataToken); Assert.Equal(methodFromToken, memberInfoFromToken); } [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/2389", TestRuntimes.Mono)] [InlineData(TypeAttributes.Public, MethodAttributes.Public | MethodAttributes.PinvokeImpl)] [InlineData(TypeAttributes.Abstract, MethodAttributes.PinvokeImpl)] [InlineData(TypeAttributes.Abstract, MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)] public void GetILGenerator_NoMethodBody_ThrowsInvalidOperationException(TypeAttributes typeAttributes, MethodAttributes methodAttributes) { TypeBuilder type = Helpers.DynamicType(typeAttributes); MethodBuilder method = type.DefineMethod("TestMethod", methodAttributes); Assert.Throws<InvalidOperationException>(() => method.GetILGenerator()); Assert.Throws<InvalidOperationException>(() => method.GetILGenerator(10)); } [Theory] [InlineData(MethodAttributes.Abstract)] [InlineData(MethodAttributes.Assembly)] [InlineData(MethodAttributes.CheckAccessOnOverride)] [InlineData(MethodAttributes.FamANDAssem)] [InlineData(MethodAttributes.Family)] [InlineData(MethodAttributes.FamORAssem)] [InlineData(MethodAttributes.Final)] [InlineData(MethodAttributes.HasSecurity)] [InlineData(MethodAttributes.HideBySig)] [InlineData(MethodAttributes.MemberAccessMask)] [InlineData(MethodAttributes.NewSlot)] [InlineData(MethodAttributes.Private)] [InlineData(MethodAttributes.Public)] [InlineData(MethodAttributes.RequireSecObject)] [InlineData(MethodAttributes.ReuseSlot)] [InlineData(MethodAttributes.RTSpecialName)] [InlineData(MethodAttributes.SpecialName)] [InlineData(MethodAttributes.Static)] [InlineData(MethodAttributes.UnmanagedExport)] [InlineData(MethodAttributes.Virtual)] [InlineData(MethodAttributes.Assembly | MethodAttributes.CheckAccessOnOverride | MethodAttributes.FamORAssem | MethodAttributes.Final | MethodAttributes.HasSecurity | MethodAttributes.HideBySig | MethodAttributes.MemberAccessMask | MethodAttributes.NewSlot | MethodAttributes.Private | MethodAttributes.PrivateScope | MethodAttributes.RequireSecObject | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName | MethodAttributes.Static | MethodAttributes.UnmanagedExport)] public void GetILGenerator_DifferentAttributes(MethodAttributes attributes) { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod(attributes.ToString(), attributes); Assert.NotNull(method.GetILGenerator()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Reflection.Emit.Tests { public class MethodBuilderGetILGenerator { [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))] [InlineData(20)] [InlineData(-10)] public void GetILGenerator_Int(int size) { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public); MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[0]); ILGenerator ilGenerator = method.GetILGenerator(size); int expectedReturn = 5; ilGenerator.Emit(OpCodes.Ldc_I4, expectedReturn); ilGenerator.Emit(OpCodes.Ret); Type createdType = type.CreateTypeInfo().AsType(); MethodInfo createdMethod = createdType.GetMethod("TestMethod"); Assert.Equal(expectedReturn, createdMethod.Invoke(null, null)); // Verify MetadataToken Assert.Equal(method.MetadataToken, createdMethod.MetadataToken); MethodInfo methodFromToken = (MethodInfo)type.Module.ResolveMethod(method.MetadataToken); Assert.Equal(createdMethod, methodFromToken); MemberInfo memberInfoFromToken = (MemberInfo)type.Module.ResolveMember(method.MetadataToken); Assert.Equal(methodFromToken, memberInfoFromToken); } [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/2389", TestRuntimes.Mono)] [InlineData(TypeAttributes.Public, MethodAttributes.Public | MethodAttributes.PinvokeImpl)] [InlineData(TypeAttributes.Abstract, MethodAttributes.PinvokeImpl)] [InlineData(TypeAttributes.Abstract, MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)] public void GetILGenerator_NoMethodBody_ThrowsInvalidOperationException(TypeAttributes typeAttributes, MethodAttributes methodAttributes) { TypeBuilder type = Helpers.DynamicType(typeAttributes); MethodBuilder method = type.DefineMethod("TestMethod", methodAttributes); Assert.Throws<InvalidOperationException>(() => method.GetILGenerator()); Assert.Throws<InvalidOperationException>(() => method.GetILGenerator(10)); } [Theory] [InlineData(MethodAttributes.Abstract)] [InlineData(MethodAttributes.Assembly)] [InlineData(MethodAttributes.CheckAccessOnOverride)] [InlineData(MethodAttributes.FamANDAssem)] [InlineData(MethodAttributes.Family)] [InlineData(MethodAttributes.FamORAssem)] [InlineData(MethodAttributes.Final)] [InlineData(MethodAttributes.HasSecurity)] [InlineData(MethodAttributes.HideBySig)] [InlineData(MethodAttributes.MemberAccessMask)] [InlineData(MethodAttributes.NewSlot)] [InlineData(MethodAttributes.Private)] [InlineData(MethodAttributes.Public)] [InlineData(MethodAttributes.RequireSecObject)] [InlineData(MethodAttributes.ReuseSlot)] [InlineData(MethodAttributes.RTSpecialName)] [InlineData(MethodAttributes.SpecialName)] [InlineData(MethodAttributes.Static)] [InlineData(MethodAttributes.UnmanagedExport)] [InlineData(MethodAttributes.Virtual)] [InlineData(MethodAttributes.Assembly | MethodAttributes.CheckAccessOnOverride | MethodAttributes.FamORAssem | MethodAttributes.Final | MethodAttributes.HasSecurity | MethodAttributes.HideBySig | MethodAttributes.MemberAccessMask | MethodAttributes.NewSlot | MethodAttributes.Private | MethodAttributes.PrivateScope | MethodAttributes.RequireSecObject | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName | MethodAttributes.Static | MethodAttributes.UnmanagedExport)] public void GetILGenerator_DifferentAttributes(MethodAttributes attributes) { TypeBuilder type = Helpers.DynamicType(TypeAttributes.Abstract); MethodBuilder method = type.DefineMethod(attributes.ToString(), attributes); Assert.NotNull(method.GetILGenerator()); } } }
-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.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/Import.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 Internal.Text; using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis.ReadyToRun { /// <summary> /// This class represents a single indirection cell in one of the import tables. /// </summary> public class Import : EmbeddedObjectNode, ISymbolDefinitionNode, ISortableSymbolNode { public readonly ImportSectionNode Table; internal readonly SignatureEmbeddedPointerIndirectionNode ImportSignature; internal readonly MethodDesc CallingMethod; public Import(ImportSectionNode tableNode, Signature importSignature, MethodDesc callingMethod = null) { Table = tableNode; CallingMethod = callingMethod; ImportSignature = new SignatureEmbeddedPointerIndirectionNode(this, importSignature); } protected override void OnMarked(NodeFactory factory) { Table.AddImport(factory, this); } protected override string GetName(NodeFactory factory) { Utf8StringBuilder sb = new Utf8StringBuilder(); AppendMangledName(factory.NameMangler, sb); return sb.ToString(); } public override int ClassCode => 667823013; public virtual bool EmitPrecode => Table.EmitPrecode; public override void EncodeData(ref ObjectDataBuilder dataBuilder, NodeFactory factory, bool relocsOnly) { // This needs to be an empty target pointer since it will be filled in with Module* // when loaded by CoreCLR dataBuilder.EmitZeroPointer(); } public virtual void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(Table.Name); sb.Append("->"); ImportSignature.AppendMangledName(nameMangler, sb); } public override bool StaticDependenciesAreComputed => true; public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory) { return new DependencyListEntry[] { new DependencyListEntry(ImportSignature, "Signature for ready-to-run fixup import") }; } public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { Import otherNode = (Import)other; int result = comparer.Compare(CallingMethod, otherNode.CallingMethod); if (result != 0) return result; result = comparer.Compare(ImportSignature.Target, otherNode.ImportSignature.Target); if (result != 0) return result; return Table.CompareToImpl(otherNode.Table, comparer); } public override bool RepresentsIndirectionCell => true; int ISymbolDefinitionNode.Offset => OffsetFromBeginningOfArray; int ISymbolNode.Offset => 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.Collections.Generic; using Internal.Text; using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis.ReadyToRun { /// <summary> /// This class represents a single indirection cell in one of the import tables. /// </summary> public class Import : EmbeddedObjectNode, ISymbolDefinitionNode, ISortableSymbolNode { public readonly ImportSectionNode Table; internal readonly SignatureEmbeddedPointerIndirectionNode ImportSignature; internal readonly MethodDesc CallingMethod; public Import(ImportSectionNode tableNode, Signature importSignature, MethodDesc callingMethod = null) { Table = tableNode; CallingMethod = callingMethod; ImportSignature = new SignatureEmbeddedPointerIndirectionNode(this, importSignature); } protected override void OnMarked(NodeFactory factory) { Table.AddImport(factory, this); } protected override string GetName(NodeFactory factory) { Utf8StringBuilder sb = new Utf8StringBuilder(); AppendMangledName(factory.NameMangler, sb); return sb.ToString(); } public override int ClassCode => 667823013; public virtual bool EmitPrecode => Table.EmitPrecode; public override void EncodeData(ref ObjectDataBuilder dataBuilder, NodeFactory factory, bool relocsOnly) { // This needs to be an empty target pointer since it will be filled in with Module* // when loaded by CoreCLR dataBuilder.EmitZeroPointer(); } public virtual void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(Table.Name); sb.Append("->"); ImportSignature.AppendMangledName(nameMangler, sb); } public override bool StaticDependenciesAreComputed => true; public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory) { return new DependencyListEntry[] { new DependencyListEntry(ImportSignature, "Signature for ready-to-run fixup import") }; } public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { Import otherNode = (Import)other; int result = comparer.Compare(CallingMethod, otherNode.CallingMethod); if (result != 0) return result; result = comparer.Compare(ImportSignature.Target, otherNode.ImportSignature.Target); if (result != 0) return result; return Table.CompareToImpl(otherNode.Table, comparer); } public override bool RepresentsIndirectionCell => true; int ISymbolDefinitionNode.Offset => OffsetFromBeginningOfArray; int ISymbolNode.Offset => 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/tests/JIT/HardwareIntrinsics/X86/Avx2/MaskLoad.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; using System.Runtime.Intrinsics.X86; using System.Reflection; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MaskLoadUInt32() { var test = new SimpleBinaryOpTest__MaskLoadUInt32(); 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 SimpleBinaryOpTest__MaskLoadUInt32 { private struct TestStruct { public Vector256<UInt32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } 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(SimpleBinaryOpTest__MaskLoadUInt32 testClass) { var result = Avx2.MaskLoad((UInt32*)testClass._dataTable.inArray1Ptr, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(testClass._dataTable.inArray1Ptr, _fld2, testClass._dataTable.outArrayPtr); } } 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 readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector256<UInt32> _clsVar2; private Vector256<UInt32> _fld2; private SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32> _dataTable; static SimpleBinaryOpTest__MaskLoadUInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } 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 SimpleBinaryOpTest__MaskLoadUInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } 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 SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32>(_data1, _data2, new UInt32[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.MaskLoad( (UInt32*)_dataTable.inArray1Ptr, Unsafe.Read<Vector256<UInt32>>(_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 = Avx2.MaskLoad( (UInt32*)_dataTable.inArray1Ptr, Avx.LoadVector256((UInt32*)(_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 = Avx2.MaskLoad( (UInt32*)_dataTable.inArray1Ptr, Avx.LoadAlignedVector256((UInt32*)(_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(Avx2).GetMethod(nameof(Avx2.MaskLoad), new Type[] { typeof(UInt32*), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(UInt32*)), Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.MaskLoad), new Type[] { typeof(UInt32*), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(UInt32*)), Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.MaskLoad), new Type[] { typeof(UInt32*), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(UInt32*)), Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.MaskLoad( (UInt32*)_dataTable.inArray1Ptr, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = (UInt32*)_dataTable.inArray1Ptr; var right = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr); var result = Avx2.MaskLoad(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = (UInt32*)_dataTable.inArray1Ptr; var right = Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.MaskLoad(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = (UInt32*)_dataTable.inArray1Ptr; var right = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.MaskLoad(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MaskLoadUInt32(); var result = Avx2.MaskLoad((UInt32*)_dataTable.inArray1Ptr, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.MaskLoad((UInt32*)_dataTable.inArray1Ptr, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.MaskLoad((UInt32*)_dataTable.inArray1Ptr, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, test._fld2, _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(void* left, Vector256<UInt32> right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (((right[0] & (1U << 31)) != 0) ? left[0] : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (((right[i] & (1U << 31)) != 0) ? left[i] : 0)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.MaskLoad)}<UInt32>(UInt32*, Vector256<UInt32>): {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; using System.Reflection; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MaskLoadUInt32() { var test = new SimpleBinaryOpTest__MaskLoadUInt32(); 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 SimpleBinaryOpTest__MaskLoadUInt32 { private struct TestStruct { public Vector256<UInt32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } 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(SimpleBinaryOpTest__MaskLoadUInt32 testClass) { var result = Avx2.MaskLoad((UInt32*)testClass._dataTable.inArray1Ptr, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(testClass._dataTable.inArray1Ptr, _fld2, testClass._dataTable.outArrayPtr); } } 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 readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector256<UInt32> _clsVar2; private Vector256<UInt32> _fld2; private SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32> _dataTable; static SimpleBinaryOpTest__MaskLoadUInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } 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 SimpleBinaryOpTest__MaskLoadUInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } 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 SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32>(_data1, _data2, new UInt32[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.MaskLoad( (UInt32*)_dataTable.inArray1Ptr, Unsafe.Read<Vector256<UInt32>>(_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 = Avx2.MaskLoad( (UInt32*)_dataTable.inArray1Ptr, Avx.LoadVector256((UInt32*)(_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 = Avx2.MaskLoad( (UInt32*)_dataTable.inArray1Ptr, Avx.LoadAlignedVector256((UInt32*)(_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(Avx2).GetMethod(nameof(Avx2.MaskLoad), new Type[] { typeof(UInt32*), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(UInt32*)), Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.MaskLoad), new Type[] { typeof(UInt32*), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(UInt32*)), Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.MaskLoad), new Type[] { typeof(UInt32*), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(UInt32*)), Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.MaskLoad( (UInt32*)_dataTable.inArray1Ptr, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = (UInt32*)_dataTable.inArray1Ptr; var right = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr); var result = Avx2.MaskLoad(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = (UInt32*)_dataTable.inArray1Ptr; var right = Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.MaskLoad(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = (UInt32*)_dataTable.inArray1Ptr; var right = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.MaskLoad(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MaskLoadUInt32(); var result = Avx2.MaskLoad((UInt32*)_dataTable.inArray1Ptr, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.MaskLoad((UInt32*)_dataTable.inArray1Ptr, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.MaskLoad((UInt32*)_dataTable.inArray1Ptr, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, test._fld2, _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(void* left, Vector256<UInt32> right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (((right[0] & (1U << 31)) != 0) ? left[0] : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (((right[i] & (1U << 31)) != 0) ? left[i] : 0)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.MaskLoad)}<UInt32>(UInt32*, Vector256<UInt32>): {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/Multiply.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 MultiplyDouble() { var test = new SimpleBinaryOpTest__MultiplyDouble(); 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__MultiplyDouble { 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__MultiplyDouble testClass) { var result = Sse2.Multiply(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MultiplyDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.Multiply( 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__MultiplyDouble() { 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__MultiplyDouble() { 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.Multiply( 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.Multiply( 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.Multiply( 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.Multiply), 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.Multiply), 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.Multiply), 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.Multiply( _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.Multiply( 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.Multiply(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.Multiply(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.Multiply(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MultiplyDouble(); var result = Sse2.Multiply(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__MultiplyDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse2.Multiply( 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.Multiply(_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.Multiply( 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.Multiply(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.Multiply( 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] * right[i]) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Multiply)}<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 MultiplyDouble() { var test = new SimpleBinaryOpTest__MultiplyDouble(); 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__MultiplyDouble { 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__MultiplyDouble testClass) { var result = Sse2.Multiply(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MultiplyDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.Multiply( 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__MultiplyDouble() { 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__MultiplyDouble() { 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.Multiply( 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.Multiply( 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.Multiply( 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.Multiply), 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.Multiply), 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.Multiply), 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.Multiply( _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.Multiply( 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.Multiply(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.Multiply(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.Multiply(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MultiplyDouble(); var result = Sse2.Multiply(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__MultiplyDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse2.Multiply( 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.Multiply(_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.Multiply( 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.Multiply(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.Multiply( 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] * right[i]) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Multiply)}<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/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/Negate.Vector128.SByte.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 Negate_Vector128_SByte() { var test = new SimpleUnaryOpTest__Negate_Vector128_SByte(); 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 SimpleUnaryOpTest__Negate_Vector128_SByte { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); if ((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<SByte, 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 Vector128<SByte> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__Negate_Vector128_SByte testClass) { var result = AdvSimd.Negate(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__Negate_Vector128_SByte testClass) { fixed (Vector128<SByte>* pFld1 = &_fld1) { var result = AdvSimd.Negate( AdvSimd.LoadVector128((SByte*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static Vector128<SByte> _clsVar1; private Vector128<SByte> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__Negate_Vector128_SByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public SimpleUnaryOpTest__Negate_Vector128_SByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, new SByte[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.Negate( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Negate( AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Negate), new Type[] { typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Negate), new Type[] { typeof(Vector128<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Negate( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar1 = &_clsVar1) { var result = AdvSimd.Negate( AdvSimd.LoadVector128((SByte*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr); var result = AdvSimd.Negate(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)); var result = AdvSimd.Negate(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__Negate_Vector128_SByte(); var result = AdvSimd.Negate(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__Negate_Vector128_SByte(); fixed (Vector128<SByte>* pFld1 = &test._fld1) { var result = AdvSimd.Negate( AdvSimd.LoadVector128((SByte*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Negate(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld1 = &_fld1) { var result = AdvSimd.Negate( AdvSimd.LoadVector128((SByte*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Negate(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Negate( AdvSimd.LoadVector128((SByte*)(&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); } 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<SByte> op1, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Negate(firstOp[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Negate)}<SByte>(Vector128<SByte>): {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.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 Negate_Vector128_SByte() { var test = new SimpleUnaryOpTest__Negate_Vector128_SByte(); 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 SimpleUnaryOpTest__Negate_Vector128_SByte { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); if ((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<SByte, 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 Vector128<SByte> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__Negate_Vector128_SByte testClass) { var result = AdvSimd.Negate(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__Negate_Vector128_SByte testClass) { fixed (Vector128<SByte>* pFld1 = &_fld1) { var result = AdvSimd.Negate( AdvSimd.LoadVector128((SByte*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static Vector128<SByte> _clsVar1; private Vector128<SByte> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__Negate_Vector128_SByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public SimpleUnaryOpTest__Negate_Vector128_SByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, new SByte[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.Negate( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Negate( AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Negate), new Type[] { typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Negate), new Type[] { typeof(Vector128<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Negate( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar1 = &_clsVar1) { var result = AdvSimd.Negate( AdvSimd.LoadVector128((SByte*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr); var result = AdvSimd.Negate(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)); var result = AdvSimd.Negate(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__Negate_Vector128_SByte(); var result = AdvSimd.Negate(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__Negate_Vector128_SByte(); fixed (Vector128<SByte>* pFld1 = &test._fld1) { var result = AdvSimd.Negate( AdvSimd.LoadVector128((SByte*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Negate(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld1 = &_fld1) { var result = AdvSimd.Negate( AdvSimd.LoadVector128((SByte*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Negate(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Negate( AdvSimd.LoadVector128((SByte*)(&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); } 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<SByte> op1, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Negate(firstOp[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Negate)}<SByte>(Vector128<SByte>): {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/Common/tests/TestUtilities/System/RetryHelper.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.Threading; using System.Threading.Tasks; namespace System { public static partial class RetryHelper { private static readonly Func<int, int> s_defaultBackoffFunc = i => Math.Min(i * 100, 60_000); private static readonly Predicate<Exception> s_defaultRetryWhenFunc = _ => true; /// <summary>Executes the <paramref name="test"/> action up to a maximum of <paramref name="maxAttempts"/> times.</summary> /// <param name="maxAttempts">The maximum number of times to invoke <paramref name="test"/>.</param> /// <param name="test">The test to invoke.</param> /// <param name="backoffFunc">After a failure, invoked to determine how many milliseconds to wait before the next attempt. It's passed the number of iterations attempted.</param> /// <param name="retryWhen">Invoked to select the exceptions to retry on. If not set, any exception will trigger a retry.</param> public static void Execute(Action test, int maxAttempts = 5, Func<int, int> backoffFunc = null, Predicate<Exception> retryWhen = null) { // Validate arguments if (maxAttempts < 1) { throw new ArgumentOutOfRangeException(nameof(maxAttempts)); } if (test == null) { throw new ArgumentNullException(nameof(test)); } retryWhen ??= s_defaultRetryWhenFunc; // Execute the test until it either passes or we run it maxAttempts times var exceptions = new List<Exception>(); for (int i = 1; i <= maxAttempts; i++) { try { test(); return; } catch (Exception e) when (retryWhen(e)) { exceptions.Add(e); if (i == maxAttempts) { throw new AggregateException(exceptions); } } Thread.Sleep((backoffFunc ?? s_defaultBackoffFunc)(i)); } } /// <summary>Executes the <paramref name="test"/> action up to a maximum of <paramref name="maxAttempts"/> times.</summary> /// <param name="maxAttempts">The maximum number of times to invoke <paramref name="test"/>.</param> /// <param name="test">The test to invoke.</param> /// <param name="backoffFunc">After a failure, invoked to determine how many milliseconds to wait before the next attempt. It's passed the number of iterations attempted.</param> /// <param name="retryWhen">Invoked to select the exceptions to retry on. If not set, any exception will trigger a retry.</param> public static async Task ExecuteAsync(Func<Task> test, int maxAttempts = 5, Func<int, int> backoffFunc = null, Predicate<Exception> retryWhen = null) { // Validate arguments if (maxAttempts < 1) { throw new ArgumentOutOfRangeException(nameof(maxAttempts)); } if (test == null) { throw new ArgumentNullException(nameof(test)); } retryWhen ??= s_defaultRetryWhenFunc; // Execute the test until it either passes or we run it maxAttempts times var exceptions = new List<Exception>(); for (int i = 1; i <= maxAttempts; i++) { try { await test().ConfigureAwait(false); return; } catch (Exception e) when (retryWhen(e)) { exceptions.Add(e); if (i == maxAttempts) { throw new AggregateException(exceptions); } } await Task.Delay((backoffFunc ?? s_defaultBackoffFunc)(i)).ConfigureAwait(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.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace System { public static partial class RetryHelper { private static readonly Func<int, int> s_defaultBackoffFunc = i => Math.Min(i * 100, 60_000); private static readonly Predicate<Exception> s_defaultRetryWhenFunc = _ => true; /// <summary>Executes the <paramref name="test"/> action up to a maximum of <paramref name="maxAttempts"/> times.</summary> /// <param name="maxAttempts">The maximum number of times to invoke <paramref name="test"/>.</param> /// <param name="test">The test to invoke.</param> /// <param name="backoffFunc">After a failure, invoked to determine how many milliseconds to wait before the next attempt. It's passed the number of iterations attempted.</param> /// <param name="retryWhen">Invoked to select the exceptions to retry on. If not set, any exception will trigger a retry.</param> public static void Execute(Action test, int maxAttempts = 5, Func<int, int> backoffFunc = null, Predicate<Exception> retryWhen = null) { // Validate arguments if (maxAttempts < 1) { throw new ArgumentOutOfRangeException(nameof(maxAttempts)); } if (test == null) { throw new ArgumentNullException(nameof(test)); } retryWhen ??= s_defaultRetryWhenFunc; // Execute the test until it either passes or we run it maxAttempts times var exceptions = new List<Exception>(); for (int i = 1; i <= maxAttempts; i++) { try { test(); return; } catch (Exception e) when (retryWhen(e)) { exceptions.Add(e); if (i == maxAttempts) { throw new AggregateException(exceptions); } } Thread.Sleep((backoffFunc ?? s_defaultBackoffFunc)(i)); } } /// <summary>Executes the <paramref name="test"/> action up to a maximum of <paramref name="maxAttempts"/> times.</summary> /// <param name="maxAttempts">The maximum number of times to invoke <paramref name="test"/>.</param> /// <param name="test">The test to invoke.</param> /// <param name="backoffFunc">After a failure, invoked to determine how many milliseconds to wait before the next attempt. It's passed the number of iterations attempted.</param> /// <param name="retryWhen">Invoked to select the exceptions to retry on. If not set, any exception will trigger a retry.</param> public static async Task ExecuteAsync(Func<Task> test, int maxAttempts = 5, Func<int, int> backoffFunc = null, Predicate<Exception> retryWhen = null) { // Validate arguments if (maxAttempts < 1) { throw new ArgumentOutOfRangeException(nameof(maxAttempts)); } if (test == null) { throw new ArgumentNullException(nameof(test)); } retryWhen ??= s_defaultRetryWhenFunc; // Execute the test until it either passes or we run it maxAttempts times var exceptions = new List<Exception>(); for (int i = 1; i <= maxAttempts; i++) { try { await test().ConfigureAwait(false); return; } catch (Exception e) when (retryWhen(e)) { exceptions.Add(e); if (i == maxAttempts) { throw new AggregateException(exceptions); } } await Task.Delay((backoffFunc ?? s_defaultBackoffFunc)(i)).ConfigureAwait(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.NetworkInformation/src/System/Net/NetworkInformation/SystemIPv4InterfaceProperties.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; namespace System.Net.NetworkInformation { internal sealed class SystemIPv4InterfaceProperties : IPv4InterfaceProperties { // These are only valid for ipv4 interfaces. private readonly bool _haveWins; private readonly bool _dhcpEnabled; private readonly bool _routingEnabled; private readonly uint _index; private readonly uint _mtu; private bool _autoConfigEnabled; private bool _autoConfigActive; internal SystemIPv4InterfaceProperties(Interop.IpHlpApi.FIXED_INFO fixedInfo, Interop.IpHlpApi.IpAdapterAddresses ipAdapterAddresses) { _index = ipAdapterAddresses.index; _routingEnabled = fixedInfo.enableRouting; _dhcpEnabled = ((ipAdapterAddresses.flags & Interop.IpHlpApi.AdapterFlags.DhcpEnabled) != 0); _haveWins = (ipAdapterAddresses.firstWinsServerAddress != IntPtr.Zero); _mtu = ipAdapterAddresses.mtu; GetPerAdapterInfo(ipAdapterAddresses.index); } /// Only valid for Ipv4 Uses WINS for name resolution. public override bool UsesWins { get { return _haveWins; } } public override bool IsDhcpEnabled { get { return _dhcpEnabled; } } public override bool IsForwardingEnabled { get { return _routingEnabled; } } /// Auto configuration of an ipv4 address for a client on a network where a DHCP server isn't available. public override bool IsAutomaticPrivateAddressingEnabled { get { return _autoConfigEnabled; } } public override bool IsAutomaticPrivateAddressingActive { get { return _autoConfigActive; } } // Specifies the Maximum transmission unit in bytes. Uses GetIFEntry. // We cache this to be consistent across all platforms. public override int Mtu { get { return unchecked((int)_mtu); } } public override int Index { get { return (int)_index; } } private unsafe void GetPerAdapterInfo(uint index) { if (index != 0) { uint size = 0; uint result = Interop.IpHlpApi.GetPerAdapterInfo(index, IntPtr.Zero, &size); while (result == Interop.IpHlpApi.ERROR_BUFFER_OVERFLOW) { // Now we allocate the buffer and read the network parameters. IntPtr buffer = Marshal.AllocHGlobal((int)size); try { result = Interop.IpHlpApi.GetPerAdapterInfo(index, buffer, &size); if (result == Interop.IpHlpApi.ERROR_SUCCESS) { Interop.IpHlpApi.IpPerAdapterInfo ipPerAdapterInfo = Marshal.PtrToStructure<Interop.IpHlpApi.IpPerAdapterInfo>(buffer); _autoConfigEnabled = ipPerAdapterInfo.autoconfigEnabled; _autoConfigActive = ipPerAdapterInfo.autoconfigActive; } } finally { Marshal.FreeHGlobal(buffer); } } if (result != Interop.IpHlpApi.ERROR_SUCCESS) { throw new NetworkInformationException((int)result); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; namespace System.Net.NetworkInformation { internal sealed class SystemIPv4InterfaceProperties : IPv4InterfaceProperties { // These are only valid for ipv4 interfaces. private readonly bool _haveWins; private readonly bool _dhcpEnabled; private readonly bool _routingEnabled; private readonly uint _index; private readonly uint _mtu; private bool _autoConfigEnabled; private bool _autoConfigActive; internal SystemIPv4InterfaceProperties(Interop.IpHlpApi.FIXED_INFO fixedInfo, Interop.IpHlpApi.IpAdapterAddresses ipAdapterAddresses) { _index = ipAdapterAddresses.index; _routingEnabled = fixedInfo.enableRouting; _dhcpEnabled = ((ipAdapterAddresses.flags & Interop.IpHlpApi.AdapterFlags.DhcpEnabled) != 0); _haveWins = (ipAdapterAddresses.firstWinsServerAddress != IntPtr.Zero); _mtu = ipAdapterAddresses.mtu; GetPerAdapterInfo(ipAdapterAddresses.index); } /// Only valid for Ipv4 Uses WINS for name resolution. public override bool UsesWins { get { return _haveWins; } } public override bool IsDhcpEnabled { get { return _dhcpEnabled; } } public override bool IsForwardingEnabled { get { return _routingEnabled; } } /// Auto configuration of an ipv4 address for a client on a network where a DHCP server isn't available. public override bool IsAutomaticPrivateAddressingEnabled { get { return _autoConfigEnabled; } } public override bool IsAutomaticPrivateAddressingActive { get { return _autoConfigActive; } } // Specifies the Maximum transmission unit in bytes. Uses GetIFEntry. // We cache this to be consistent across all platforms. public override int Mtu { get { return unchecked((int)_mtu); } } public override int Index { get { return (int)_index; } } private unsafe void GetPerAdapterInfo(uint index) { if (index != 0) { uint size = 0; uint result = Interop.IpHlpApi.GetPerAdapterInfo(index, IntPtr.Zero, &size); while (result == Interop.IpHlpApi.ERROR_BUFFER_OVERFLOW) { // Now we allocate the buffer and read the network parameters. IntPtr buffer = Marshal.AllocHGlobal((int)size); try { result = Interop.IpHlpApi.GetPerAdapterInfo(index, buffer, &size); if (result == Interop.IpHlpApi.ERROR_SUCCESS) { Interop.IpHlpApi.IpPerAdapterInfo ipPerAdapterInfo = Marshal.PtrToStructure<Interop.IpHlpApi.IpPerAdapterInfo>(buffer); _autoConfigEnabled = ipPerAdapterInfo.autoconfigEnabled; _autoConfigActive = ipPerAdapterInfo.autoconfigActive; } } finally { Marshal.FreeHGlobal(buffer); } } if (result != Interop.IpHlpApi.ERROR_SUCCESS) { throw new NetworkInformationException((int)result); } } } } }
-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/tests/bug-561239.cs
using System; using System.IO; using System.Threading; public class PulseTest { private bool startedUp = false; private int threadNum = 0; private object theLock = new object (); public static void Main (string[] args) { int lastThreadNum = 0; for (int i = 0; i < 100; ++i) { /* * Start a thread going. */ PulseTest pulseTest = new PulseTest (); pulseTest.threadNum = ++ lastThreadNum; Thread sysThread = new Thread (pulseTest.ThreadMain); /* * Block thread from doing anything. */ Monitor.Enter (pulseTest.theLock); /* * Now start it. */ sysThread.Start (); /* * Wait for pulsetest thread to call Monitor.Wait(). */ while (!pulseTest.startedUp) { pulseTest.Message ("Main", "waiting"); Monitor.Wait (pulseTest.theLock); pulseTest.Message ("Main", "woken"); } Monitor.Exit (pulseTest.theLock); /* * Whilst it is sitting in Monitor.Wait, kill it off. * * Without the patch, the wait event sits in mon->wait_list, * even as the mon struct gets recycled onto monitor_freelist. * * With the patch, the event is unlinked when the mon struct * gets recycled. */ pulseTest.Message ("Main", "disposing"); sysThread.Abort (); sysThread.Join (); pulseTest.Message ("Main", "disposed"); } } private void ThreadMain () { Monitor.Enter (theLock); startedUp = true; Monitor.Pulse (theLock); while (true) { Message ("ThreadMain", "waiting"); /* * This puts an event onto mon->wait_list. * Then Main() does a sysThread.Abort() and * the event is left on mon->wait_list. */ Monitor.Wait (theLock); Message ("ThreadMain", "woken"); } } private void Message (string func, string msg) { Console.WriteLine ("{0}[{1}]*: {2}", func, threadNum, msg); } }
using System; using System.IO; using System.Threading; public class PulseTest { private bool startedUp = false; private int threadNum = 0; private object theLock = new object (); public static void Main (string[] args) { int lastThreadNum = 0; for (int i = 0; i < 100; ++i) { /* * Start a thread going. */ PulseTest pulseTest = new PulseTest (); pulseTest.threadNum = ++ lastThreadNum; Thread sysThread = new Thread (pulseTest.ThreadMain); /* * Block thread from doing anything. */ Monitor.Enter (pulseTest.theLock); /* * Now start it. */ sysThread.Start (); /* * Wait for pulsetest thread to call Monitor.Wait(). */ while (!pulseTest.startedUp) { pulseTest.Message ("Main", "waiting"); Monitor.Wait (pulseTest.theLock); pulseTest.Message ("Main", "woken"); } Monitor.Exit (pulseTest.theLock); /* * Whilst it is sitting in Monitor.Wait, kill it off. * * Without the patch, the wait event sits in mon->wait_list, * even as the mon struct gets recycled onto monitor_freelist. * * With the patch, the event is unlinked when the mon struct * gets recycled. */ pulseTest.Message ("Main", "disposing"); sysThread.Abort (); sysThread.Join (); pulseTest.Message ("Main", "disposed"); } } private void ThreadMain () { Monitor.Enter (theLock); startedUp = true; Monitor.Pulse (theLock); while (true) { Message ("ThreadMain", "waiting"); /* * This puts an event onto mon->wait_list. * Then Main() does a sysThread.Abort() and * the event is left on mon->wait_list. */ Monitor.Wait (theLock); Message ("ThreadMain", "woken"); } } private void Message (string func, string msg) { Console.WriteLine ("{0}[{1}]*: {2}", func, threadNum, msg); } }
-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.IO.Compression.ZipFile/tests/ZipFileExtensions.ZipArchive.Extract.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; namespace System.IO.Compression.Tests { public class ZipFile_ZipArchive_Extract : ZipFileTestBase { [Fact] public void ExtractToDirectoryExtension() { using (ZipArchive archive = ZipFile.Open(zfile("normal.zip"), ZipArchiveMode.Read)) { string tempFolder = GetTestFilePath(); Assert.Throws<ArgumentNullException>(() => ((ZipArchive)null).ExtractToDirectory(tempFolder)); Assert.Throws<ArgumentNullException>(() => archive.ExtractToDirectory(null)); archive.ExtractToDirectory(tempFolder); DirsEqual(tempFolder, zfolder("normal")); } } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/60582", TestPlatforms.iOS | TestPlatforms.tvOS)] public void ExtractToDirectoryExtension_Unicode() { using (ZipArchive archive = ZipFile.OpenRead(zfile("unicode.zip"))) { string tempFolder = GetTestFilePath(); archive.ExtractToDirectory(tempFolder); DirFileNamesEqual(tempFolder, zfolder("unicode")); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.IO.Compression.Tests { public class ZipFile_ZipArchive_Extract : ZipFileTestBase { [Fact] public void ExtractToDirectoryExtension() { using (ZipArchive archive = ZipFile.Open(zfile("normal.zip"), ZipArchiveMode.Read)) { string tempFolder = GetTestFilePath(); Assert.Throws<ArgumentNullException>(() => ((ZipArchive)null).ExtractToDirectory(tempFolder)); Assert.Throws<ArgumentNullException>(() => archive.ExtractToDirectory(null)); archive.ExtractToDirectory(tempFolder); DirsEqual(tempFolder, zfolder("normal")); } } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/60582", TestPlatforms.iOS | TestPlatforms.tvOS)] public void ExtractToDirectoryExtension_Unicode() { using (ZipArchive archive = ZipFile.OpenRead(zfile("unicode.zip"))) { string tempFolder = GetTestFilePath(); archive.ExtractToDirectory(tempFolder); DirFileNamesEqual(tempFolder, zfolder("unicode")); } } } }
-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.CoreLib/src/System/Reflection/Emit/PropertyBuilder.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.Emit { public sealed class PropertyBuilder : PropertyInfo { internal PropertyBuilder() { // Prevent generating a default constructor } public override PropertyAttributes Attributes { get { return default; } } public override bool CanRead { get { return default; } } public override bool CanWrite { get { return default; } } public override Type DeclaringType { get { return default; } } public override Module Module { get { return default; } } public override string Name { get { return default; } } public override Type PropertyType { get { return default; } } public override Type ReflectedType { get { return default; } } public void AddOtherMethod(MethodBuilder mdBuilder) { } public override MethodInfo[] GetAccessors(bool nonPublic) { return default; } public override object[] GetCustomAttributes(bool inherit) { return default; } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return default; } public override MethodInfo GetGetMethod(bool nonPublic) { return default; } public override ParameterInfo[] GetIndexParameters() { return default; } public override MethodInfo GetSetMethod(bool nonPublic) { return default; } public override object? GetValue(object? obj, object?[]? index) { return default; } public override object? GetValue(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? index, Globalization.CultureInfo? culture) { return default; } public override bool IsDefined(Type attributeType, bool inherit) { return default; } public void SetConstant(object defaultValue) { } public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { } public void SetGetMethod(MethodBuilder mdBuilder) { } public void SetSetMethod(MethodBuilder mdBuilder) { } public override void SetValue(object? obj, object? value, object?[]? index) { } public override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, object?[]? index, Globalization.CultureInfo? culture) { } } }
// 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.Emit { public sealed class PropertyBuilder : PropertyInfo { internal PropertyBuilder() { // Prevent generating a default constructor } public override PropertyAttributes Attributes { get { return default; } } public override bool CanRead { get { return default; } } public override bool CanWrite { get { return default; } } public override Type DeclaringType { get { return default; } } public override Module Module { get { return default; } } public override string Name { get { return default; } } public override Type PropertyType { get { return default; } } public override Type ReflectedType { get { return default; } } public void AddOtherMethod(MethodBuilder mdBuilder) { } public override MethodInfo[] GetAccessors(bool nonPublic) { return default; } public override object[] GetCustomAttributes(bool inherit) { return default; } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return default; } public override MethodInfo GetGetMethod(bool nonPublic) { return default; } public override ParameterInfo[] GetIndexParameters() { return default; } public override MethodInfo GetSetMethod(bool nonPublic) { return default; } public override object? GetValue(object? obj, object?[]? index) { return default; } public override object? GetValue(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? index, Globalization.CultureInfo? culture) { return default; } public override bool IsDefined(Type attributeType, bool inherit) { return default; } public void SetConstant(object defaultValue) { } public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { } public void SetGetMethod(MethodBuilder mdBuilder) { } public void SetSetMethod(MethodBuilder mdBuilder) { } public override void SetValue(object? obj, object? value, object?[]? index) { } public override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, object?[]? index, Globalization.CultureInfo? culture) { } } }
-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/ReciprocalSquareRootEstimate.Vector128.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.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 ReciprocalSquareRootEstimate_Vector128_Single() { var test = new SimpleUnaryOpTest__ReciprocalSquareRootEstimate_Vector128_Single(); 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 SimpleUnaryOpTest__ReciprocalSquareRootEstimate_Vector128_Single { 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 != 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 Vector128<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = BitConverter.Int32BitsToSingle(0x3e4ed9ed); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__ReciprocalSquareRootEstimate_Vector128_Single testClass) { var result = AdvSimd.ReciprocalSquareRootEstimate(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__ReciprocalSquareRootEstimate_Vector128_Single testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) { var result = AdvSimd.ReciprocalSquareRootEstimate( AdvSimd.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar1; private Vector128<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__ReciprocalSquareRootEstimate_Vector128_Single() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = BitConverter.Int32BitsToSingle(0x3e4ed9ed); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleUnaryOpTest__ReciprocalSquareRootEstimate_Vector128_Single() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = BitConverter.Int32BitsToSingle(0x3e4ed9ed); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = BitConverter.Int32BitsToSingle(0x3e4ed9ed); } _dataTable = new DataTable(_data1, new Single[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.ReciprocalSquareRootEstimate( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ReciprocalSquareRootEstimate( AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ReciprocalSquareRootEstimate), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ReciprocalSquareRootEstimate), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ReciprocalSquareRootEstimate( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) { var result = AdvSimd.ReciprocalSquareRootEstimate( AdvSimd.LoadVector128((Single*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var result = AdvSimd.ReciprocalSquareRootEstimate(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var result = AdvSimd.ReciprocalSquareRootEstimate(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__ReciprocalSquareRootEstimate_Vector128_Single(); var result = AdvSimd.ReciprocalSquareRootEstimate(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__ReciprocalSquareRootEstimate_Vector128_Single(); fixed (Vector128<Single>* pFld1 = &test._fld1) { var result = AdvSimd.ReciprocalSquareRootEstimate( AdvSimd.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ReciprocalSquareRootEstimate(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) { var result = AdvSimd.ReciprocalSquareRootEstimate( AdvSimd.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ReciprocalSquareRootEstimate(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ReciprocalSquareRootEstimate( AdvSimd.LoadVector128((Single*)(&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); } 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<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<Vector128<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<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != 0x400e8000) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ReciprocalSquareRootEstimate)}<Single>(Vector128<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.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 ReciprocalSquareRootEstimate_Vector128_Single() { var test = new SimpleUnaryOpTest__ReciprocalSquareRootEstimate_Vector128_Single(); 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 SimpleUnaryOpTest__ReciprocalSquareRootEstimate_Vector128_Single { 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 != 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 Vector128<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = BitConverter.Int32BitsToSingle(0x3e4ed9ed); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__ReciprocalSquareRootEstimate_Vector128_Single testClass) { var result = AdvSimd.ReciprocalSquareRootEstimate(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__ReciprocalSquareRootEstimate_Vector128_Single testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) { var result = AdvSimd.ReciprocalSquareRootEstimate( AdvSimd.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar1; private Vector128<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__ReciprocalSquareRootEstimate_Vector128_Single() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = BitConverter.Int32BitsToSingle(0x3e4ed9ed); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleUnaryOpTest__ReciprocalSquareRootEstimate_Vector128_Single() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = BitConverter.Int32BitsToSingle(0x3e4ed9ed); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = BitConverter.Int32BitsToSingle(0x3e4ed9ed); } _dataTable = new DataTable(_data1, new Single[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.ReciprocalSquareRootEstimate( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ReciprocalSquareRootEstimate( AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ReciprocalSquareRootEstimate), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ReciprocalSquareRootEstimate), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ReciprocalSquareRootEstimate( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) { var result = AdvSimd.ReciprocalSquareRootEstimate( AdvSimd.LoadVector128((Single*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var result = AdvSimd.ReciprocalSquareRootEstimate(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var result = AdvSimd.ReciprocalSquareRootEstimate(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__ReciprocalSquareRootEstimate_Vector128_Single(); var result = AdvSimd.ReciprocalSquareRootEstimate(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__ReciprocalSquareRootEstimate_Vector128_Single(); fixed (Vector128<Single>* pFld1 = &test._fld1) { var result = AdvSimd.ReciprocalSquareRootEstimate( AdvSimd.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ReciprocalSquareRootEstimate(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) { var result = AdvSimd.ReciprocalSquareRootEstimate( AdvSimd.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ReciprocalSquareRootEstimate(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ReciprocalSquareRootEstimate( AdvSimd.LoadVector128((Single*)(&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); } 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<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<Vector128<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<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != 0x400e8000) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ReciprocalSquareRootEstimate)}<Single>(Vector128<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,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/jit64/valuetypes/nullable/box-unbox/generics/box-unbox-generics028.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="box-unbox-generics028.cs" /> <Compile Include="..\structdef.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="box-unbox-generics028.cs" /> <Compile Include="..\structdef.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/mono/mono/sgen/sgen-workers.h
/** * \file * Worker threads for parallel and concurrent GC. * * Copyright 2011 Xamarin Inc (http://www.xamarin.com) * Copyright (C) 2012 Xamarin Inc * * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #ifndef __MONO_SGEN_WORKER_H__ #define __MONO_SGEN_WORKER_H__ #include "mono/sgen/sgen-thread-pool.h" typedef struct _WorkerData WorkerData; typedef struct _WorkerContext WorkerContext; typedef gint32 State; typedef void (*SgenWorkersFinishCallback) (void); typedef void (*SgenWorkerCallback) (WorkerData *data); struct _WorkerData { gint32 state; SgenGrayQueue private_gray_queue; /* only read/written by worker thread */ /* * Workers allocate major objects only from here. It has same structure as the * global one. This is normally accessed from the worker_block_free_list_key. * We hold it here so we can clear free lists from all threads before sweep * starts. */ gpointer free_block_lists; WorkerContext *context; /* Work time distribution. Measured in ticks. */ gint64 major_scan_time, los_scan_time, total_time; /* * When changing the state of the worker from not working to work enqueued * we set the timestamp so we can compute for how long the worker did actual * work during the phase */ gint64 last_start; }; struct _WorkerContext { int workers_num; int active_workers_num; volatile gboolean started; volatile gboolean forced_stop; WorkerData *workers_data; /* * When using multiple workers, we need to have the last worker * enqueue the preclean jobs (if there are any). This lock ensures * that when the last worker takes it, all the other workers have * gracefully finished, so it can restart them. */ mono_mutex_t finished_lock; volatile gboolean workers_finished; int worker_awakenings; SgenSectionGrayQueue workers_distribute_gray_queue; SgenObjectOperations * volatile idle_func_object_ops; SgenObjectOperations *idle_func_object_ops_par, *idle_func_object_ops_nopar; /* * finished_callback is called only when the workers finish work normally (when they * are not forced to finish). The callback is used to enqueue preclean jobs. */ volatile SgenWorkersFinishCallback finish_callback; int generation; int thread_pool_context; }; void sgen_workers_create_context (int generation, int num_workers); void sgen_workers_stop_all_workers (int generation); void sgen_workers_set_num_active_workers (int generation, int num_workers); #ifndef DISABLE_SGEN_MAJOR_MARKSWEEP_CONC void sgen_workers_start_all_workers (int generation, SgenObjectOperations *object_ops_nopar, SgenObjectOperations *object_ops_par, SgenWorkersFinishCallback finish_job); #else #define sgen_workers_start_all_workers(generation, object_ops_nopar, object_ops_par, finish_job) (void)object_ops_par; // avoid compiler warning: variable 'object_ops_par' set but not used #endif void sgen_workers_enqueue_job (int generation, SgenThreadPoolJob *job, gboolean enqueue); /* * LOCKING: Assumes the GC lock is held. */ void sgen_workers_enqueue_deferred_job (int generation, SgenThreadPoolJob *job, gboolean enqueue); /* * LOCKING: Assumes the GC lock is held. */ void sgen_workers_flush_deferred_jobs (int generation, gboolean signal); void sgen_workers_join (int generation); gboolean sgen_workers_have_idle_work (int generation); gboolean sgen_workers_all_done (void); void sgen_workers_assert_gray_queue_is_empty (int generation); void sgen_workers_take_from_queue (int generation, SgenGrayQueue *queue); SgenObjectOperations* sgen_workers_get_idle_func_object_ops (WorkerData *worker); int sgen_workers_get_job_split_count (int generation); int sgen_workers_get_active_worker_count (int generation); #ifndef DISABLE_SGEN_MAJOR_MARKSWEEP_CONC void sgen_workers_foreach (int generation, SgenWorkerCallback callback); #else #define sgen_workers_foreach(...) #endif gboolean sgen_workers_is_worker_thread (MonoNativeThreadId id); #endif
/** * \file * Worker threads for parallel and concurrent GC. * * Copyright 2011 Xamarin Inc (http://www.xamarin.com) * Copyright (C) 2012 Xamarin Inc * * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #ifndef __MONO_SGEN_WORKER_H__ #define __MONO_SGEN_WORKER_H__ #include "mono/sgen/sgen-thread-pool.h" typedef struct _WorkerData WorkerData; typedef struct _WorkerContext WorkerContext; typedef gint32 State; typedef void (*SgenWorkersFinishCallback) (void); typedef void (*SgenWorkerCallback) (WorkerData *data); struct _WorkerData { gint32 state; SgenGrayQueue private_gray_queue; /* only read/written by worker thread */ /* * Workers allocate major objects only from here. It has same structure as the * global one. This is normally accessed from the worker_block_free_list_key. * We hold it here so we can clear free lists from all threads before sweep * starts. */ gpointer free_block_lists; WorkerContext *context; /* Work time distribution. Measured in ticks. */ gint64 major_scan_time, los_scan_time, total_time; /* * When changing the state of the worker from not working to work enqueued * we set the timestamp so we can compute for how long the worker did actual * work during the phase */ gint64 last_start; }; struct _WorkerContext { int workers_num; int active_workers_num; volatile gboolean started; volatile gboolean forced_stop; WorkerData *workers_data; /* * When using multiple workers, we need to have the last worker * enqueue the preclean jobs (if there are any). This lock ensures * that when the last worker takes it, all the other workers have * gracefully finished, so it can restart them. */ mono_mutex_t finished_lock; volatile gboolean workers_finished; int worker_awakenings; SgenSectionGrayQueue workers_distribute_gray_queue; SgenObjectOperations * volatile idle_func_object_ops; SgenObjectOperations *idle_func_object_ops_par, *idle_func_object_ops_nopar; /* * finished_callback is called only when the workers finish work normally (when they * are not forced to finish). The callback is used to enqueue preclean jobs. */ volatile SgenWorkersFinishCallback finish_callback; int generation; int thread_pool_context; }; void sgen_workers_create_context (int generation, int num_workers); void sgen_workers_stop_all_workers (int generation); void sgen_workers_set_num_active_workers (int generation, int num_workers); #ifndef DISABLE_SGEN_MAJOR_MARKSWEEP_CONC void sgen_workers_start_all_workers (int generation, SgenObjectOperations *object_ops_nopar, SgenObjectOperations *object_ops_par, SgenWorkersFinishCallback finish_job); #else #define sgen_workers_start_all_workers(generation, object_ops_nopar, object_ops_par, finish_job) (void)object_ops_par; // avoid compiler warning: variable 'object_ops_par' set but not used #endif void sgen_workers_enqueue_job (int generation, SgenThreadPoolJob *job, gboolean enqueue); /* * LOCKING: Assumes the GC lock is held. */ void sgen_workers_enqueue_deferred_job (int generation, SgenThreadPoolJob *job, gboolean enqueue); /* * LOCKING: Assumes the GC lock is held. */ void sgen_workers_flush_deferred_jobs (int generation, gboolean signal); void sgen_workers_join (int generation); gboolean sgen_workers_have_idle_work (int generation); gboolean sgen_workers_all_done (void); void sgen_workers_assert_gray_queue_is_empty (int generation); void sgen_workers_take_from_queue (int generation, SgenGrayQueue *queue); SgenObjectOperations* sgen_workers_get_idle_func_object_ops (WorkerData *worker); int sgen_workers_get_job_split_count (int generation); int sgen_workers_get_active_worker_count (int generation); #ifndef DISABLE_SGEN_MAJOR_MARKSWEEP_CONC void sgen_workers_foreach (int generation, SgenWorkerCallback callback); #else #define sgen_workers_foreach(...) #endif gboolean sgen_workers_is_worker_thread (MonoNativeThreadId id); #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/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/CompareEqual.Vector128.Int16.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_Vector128_Int16() { var test = new SimpleBinaryOpTest__CompareEqual_Vector128_Int16(); 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_Vector128_Int16 { 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(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); 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<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, 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<Int16> _fld1; public Vector128<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareEqual_Vector128_Int16 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_Vector128_Int16 testClass) { fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(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<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private Vector128<Int16> _fld1; private Vector128<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareEqual_Vector128_Int16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public SimpleBinaryOpTest__CompareEqual_Vector128_Int16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[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<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_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.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int16*)(_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(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(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(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(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 (Vector128<Int16>* pClsVar1 = &_clsVar1) fixed (Vector128<Int16>* pClsVar2 = &_clsVar2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector128((Int16*)(pClsVar1)), AdvSimd.LoadVector128((Int16*)(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<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int16>>(_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.LoadVector128((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int16*)(_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_Vector128_Int16(); 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_Vector128_Int16(); fixed (Vector128<Int16>* pFld1 = &test._fld1) fixed (Vector128<Int16>* pFld2 = &test._fld2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(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 (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(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.LoadVector128((Int16*)(&test._fld1)), AdvSimd.LoadVector128((Int16*)(&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<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] 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)}<Int16>(Vector128<Int16>, Vector128<Int16>): {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_Vector128_Int16() { var test = new SimpleBinaryOpTest__CompareEqual_Vector128_Int16(); 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_Vector128_Int16 { 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(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); 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<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, 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<Int16> _fld1; public Vector128<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareEqual_Vector128_Int16 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_Vector128_Int16 testClass) { fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(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<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private Vector128<Int16> _fld1; private Vector128<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareEqual_Vector128_Int16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public SimpleBinaryOpTest__CompareEqual_Vector128_Int16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[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<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_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.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int16*)(_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(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(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(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(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 (Vector128<Int16>* pClsVar1 = &_clsVar1) fixed (Vector128<Int16>* pClsVar2 = &_clsVar2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector128((Int16*)(pClsVar1)), AdvSimd.LoadVector128((Int16*)(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<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int16>>(_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.LoadVector128((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int16*)(_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_Vector128_Int16(); 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_Vector128_Int16(); fixed (Vector128<Int16>* pFld1 = &test._fld1) fixed (Vector128<Int16>* pFld2 = &test._fld2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(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 (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(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.LoadVector128((Int16*)(&test._fld1)), AdvSimd.LoadVector128((Int16*)(&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<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] 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)}<Int16>(Vector128<Int16>, Vector128<Int16>): {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