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
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderNLS.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.Text; using System; using System.Globalization; using System.Runtime.Serialization; namespace System.Text { // A Decoder is used to decode a sequence of blocks of bytes into a // sequence of blocks of characters. Following instantiation of a decoder, // sequential blocks of bytes are converted into blocks of characters through // calls to the GetChars method. The decoder maintains state between the // conversions, allowing it to correctly decode byte sequences that span // adjacent blocks. // // Instances of specific implementations of the Decoder abstract base // class are typically obtained through calls to the GetDecoder method // of Encoding objects. // internal class DecoderNLS : Decoder, ISerializable { // Remember our encoding protected EncodingNLS m_encoding; protected bool m_mustFlush; internal bool m_throwOnOverflow; internal int m_bytesUsed; internal DecoderFallback m_fallback; internal DecoderFallbackBuffer? m_fallbackBuffer; internal DecoderNLS(EncodingNLS encoding) { m_encoding = encoding; m_fallback = m_encoding.DecoderFallback; Reset(); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } internal new DecoderFallback Fallback { get { return m_fallback; } } internal bool InternalHasFallbackBuffer { get { return m_fallbackBuffer is not null; } } public new DecoderFallbackBuffer FallbackBuffer { get { m_fallbackBuffer ??= m_fallback is not null ? m_fallback.CreateFallbackBuffer() : DecoderFallback.ReplacementFallback.CreateFallbackBuffer(); return m_fallbackBuffer; } } public override void Reset() { m_fallbackBuffer?.Reset(); } public override unsafe int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, false); } public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush) { if (bytes is null) throw new ArgumentNullException(nameof(bytes)); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // Avoid null fixed problem if (bytes.Length == 0) bytes = new byte[1]; // Just call pointer version fixed (byte* pBytes = &bytes[0]) return GetCharCount(pBytes + index, count, flush); } public override unsafe int GetCharCount(byte* bytes, int count, bool flush) { if (bytes is null) throw new ArgumentNullException(nameof(bytes)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); // Remember the flush m_mustFlush = flush; m_throwOnOverflow = true; // By default just call the encoding version, no flush by default return m_encoding.GetCharCount(bytes, count, this); } public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false); } public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { if (bytes is null) throw new ArgumentNullException(nameof(bytes)); if (chars is null) throw new ArgumentNullException(nameof(chars)); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); // Avoid empty input fixed problem if (bytes.Length == 0) bytes = new byte[1]; int charCount = chars.Length - charIndex; if (chars.Length == 0) chars = new char[1]; // Just call pointer version fixed (byte* pBytes = &bytes[0]) fixed (char* pChars = &chars[0]) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush); } public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { if (bytes is null) throw new ArgumentNullException(nameof(bytes)); if (chars is null) throw new ArgumentNullException(nameof(chars)); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); // Remember our flush m_mustFlush = flush; m_throwOnOverflow = true; // By default just call the encoding's version return m_encoding.GetChars(bytes, byteCount, chars, charCount, this); } // This method is used when the output buffer might not be big enough. // Just call the pointer version. (This gets chars) public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { if (bytes is null) throw new ArgumentNullException(nameof(bytes)); if (chars is null) throw new ArgumentNullException(nameof(chars)); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); // Avoid empty input problem if (bytes.Length == 0) bytes = new byte[1]; if (chars.Length == 0) chars = new char[1]; // Just call the pointer version (public overrides can't do this) fixed (byte* pBytes = &bytes[0]) { fixed (char* pChars = &chars[0]) { Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed); } } } // This is the version that used pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting chars public override unsafe void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { if (bytes is null) throw new ArgumentNullException(nameof(bytes)); if (chars is null) throw new ArgumentNullException(nameof(chars)); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); // We don't want to throw m_mustFlush = flush; m_throwOnOverflow = false; m_bytesUsed = 0; // Do conversion charsUsed = m_encoding.GetChars(bytes, byteCount, chars, charCount, this); bytesUsed = m_bytesUsed; // It's completed if they've used what they wanted AND if they didn't want flush or if we are flushed completed = (bytesUsed == byteCount) && (!flush || !HasState) && (m_fallbackBuffer is null || m_fallbackBuffer.Remaining == 0); // Our data thingies are now full, we can return } public bool MustFlush { get { return m_mustFlush; } } // Anything left in our decoder? internal virtual bool HasState { get { return false; } } // Allow encoding to clear our must flush instead of throwing (in ThrowCharsOverflow) internal void ClearMustFlush() { m_mustFlush = 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.Text; using System; using System.Globalization; using System.Runtime.Serialization; namespace System.Text { // A Decoder is used to decode a sequence of blocks of bytes into a // sequence of blocks of characters. Following instantiation of a decoder, // sequential blocks of bytes are converted into blocks of characters through // calls to the GetChars method. The decoder maintains state between the // conversions, allowing it to correctly decode byte sequences that span // adjacent blocks. // // Instances of specific implementations of the Decoder abstract base // class are typically obtained through calls to the GetDecoder method // of Encoding objects. // internal class DecoderNLS : Decoder, ISerializable { // Remember our encoding protected EncodingNLS m_encoding; protected bool m_mustFlush; internal bool m_throwOnOverflow; internal int m_bytesUsed; internal DecoderFallback m_fallback; internal DecoderFallbackBuffer? m_fallbackBuffer; internal DecoderNLS(EncodingNLS encoding) { m_encoding = encoding; m_fallback = m_encoding.DecoderFallback; Reset(); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } internal new DecoderFallback Fallback { get { return m_fallback; } } internal bool InternalHasFallbackBuffer { get { return m_fallbackBuffer is not null; } } public new DecoderFallbackBuffer FallbackBuffer { get { m_fallbackBuffer ??= m_fallback is not null ? m_fallback.CreateFallbackBuffer() : DecoderFallback.ReplacementFallback.CreateFallbackBuffer(); return m_fallbackBuffer; } } public override void Reset() { m_fallbackBuffer?.Reset(); } public override unsafe int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, false); } public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush) { if (bytes is null) throw new ArgumentNullException(nameof(bytes)); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // Avoid null fixed problem if (bytes.Length == 0) bytes = new byte[1]; // Just call pointer version fixed (byte* pBytes = &bytes[0]) return GetCharCount(pBytes + index, count, flush); } public override unsafe int GetCharCount(byte* bytes, int count, bool flush) { if (bytes is null) throw new ArgumentNullException(nameof(bytes)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); // Remember the flush m_mustFlush = flush; m_throwOnOverflow = true; // By default just call the encoding version, no flush by default return m_encoding.GetCharCount(bytes, count, this); } public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false); } public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { if (bytes is null) throw new ArgumentNullException(nameof(bytes)); if (chars is null) throw new ArgumentNullException(nameof(chars)); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); // Avoid empty input fixed problem if (bytes.Length == 0) bytes = new byte[1]; int charCount = chars.Length - charIndex; if (chars.Length == 0) chars = new char[1]; // Just call pointer version fixed (byte* pBytes = &bytes[0]) fixed (char* pChars = &chars[0]) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush); } public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { if (bytes is null) throw new ArgumentNullException(nameof(bytes)); if (chars is null) throw new ArgumentNullException(nameof(chars)); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); // Remember our flush m_mustFlush = flush; m_throwOnOverflow = true; // By default just call the encoding's version return m_encoding.GetChars(bytes, byteCount, chars, charCount, this); } // This method is used when the output buffer might not be big enough. // Just call the pointer version. (This gets chars) public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { if (bytes is null) throw new ArgumentNullException(nameof(bytes)); if (chars is null) throw new ArgumentNullException(nameof(chars)); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); // Avoid empty input problem if (bytes.Length == 0) bytes = new byte[1]; if (chars.Length == 0) chars = new char[1]; // Just call the pointer version (public overrides can't do this) fixed (byte* pBytes = &bytes[0]) { fixed (char* pChars = &chars[0]) { Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed); } } } // This is the version that used pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting chars public override unsafe void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { if (bytes is null) throw new ArgumentNullException(nameof(bytes)); if (chars is null) throw new ArgumentNullException(nameof(chars)); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); // We don't want to throw m_mustFlush = flush; m_throwOnOverflow = false; m_bytesUsed = 0; // Do conversion charsUsed = m_encoding.GetChars(bytes, byteCount, chars, charCount, this); bytesUsed = m_bytesUsed; // It's completed if they've used what they wanted AND if they didn't want flush or if we are flushed completed = (bytesUsed == byteCount) && (!flush || !HasState) && (m_fallbackBuffer is null || m_fallbackBuffer.Remaining == 0); // Our data thingies are now full, we can return } public bool MustFlush { get { return m_mustFlush; } } // Anything left in our decoder? internal virtual bool HasState { get { return false; } } // Allow encoding to clear our must flush instead of throwing (in ThrowCharsOverflow) internal void ClearMustFlush() { m_mustFlush = false; } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.ComponentModel.TypeConverter/tests/Drawing/PointConverterTests.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.Drawing; using System.Globalization; using System.Linq; using Xunit; namespace System.ComponentModel.TypeConverterTests { public class PointConverterTests : StringTypeConverterTestBase<Point> { protected override TypeConverter Converter { get; } = new PointConverter(); protected override bool StandardValuesSupported { get; } = false; protected override bool StandardValuesExclusive { get; } = false; protected override Point Default => new Point(1, 1); protected override bool CreateInstanceSupported { get; } = true; protected override bool IsGetPropertiesSupported { get; } = true; protected override IEnumerable<Tuple<Point, Dictionary<string, object>>> CreateInstancePairs { get { yield return Tuple.Create(new Point(10, 20), new Dictionary<string, object> { ["X"] = 10, ["Y"] = 20, }); yield return Tuple.Create(new Point(-2, 3), new Dictionary<string, object> { ["X"] = -2, ["Y"] = 3, }); } } [Theory] [InlineData(typeof(string))] public void CanConvertFromTrue(Type type) { CanConvertFrom(type); } [Theory] [InlineData(typeof(Rectangle))] [InlineData(typeof(RectangleF))] [InlineData(typeof(Point))] [InlineData(typeof(PointF))] [InlineData(typeof(Color))] [InlineData(typeof(Size))] [InlineData(typeof(SizeF))] [InlineData(typeof(object))] [InlineData(typeof(int))] public void CanConvertFromFalse(Type type) { CannotConvertFrom(type); } [Theory] [InlineData(typeof(string))] public void CanConvertToTrue(Type type) { CanConvertTo(type); } [Theory] [InlineData(typeof(Rectangle))] [InlineData(typeof(RectangleF))] [InlineData(typeof(Point))] [InlineData(typeof(PointF))] [InlineData(typeof(Color))] [InlineData(typeof(Size))] [InlineData(typeof(SizeF))] [InlineData(typeof(object))] [InlineData(typeof(int))] public void CanConvertToFalse(Type type) { CannotConvertTo(type); } public static IEnumerable<object[]> PointData => new[] { new object[] {0, 0}, new object[] {1, 1}, new object[] {-1, 1}, new object[] {1, -1}, new object[] {-1, -1}, new object[] {int.MaxValue, int.MaxValue}, new object[] {int.MinValue, int.MaxValue}, new object[] {int.MaxValue, int.MinValue}, new object[] {int.MinValue, int.MinValue}, }; [Theory] [MemberData(nameof(PointData))] public void ConvertFrom(int x, int y) { TestConvertFromString(new Point(x, y), $"{x}, {y}"); } [Theory] [InlineData("1")] [InlineData("1, 1, 1")] public void ConvertFrom_ArgumentException(string value) { ConvertFromThrowsArgumentExceptionForString(value); } [Fact] public void ConvertFrom_Invalid() { ConvertFromThrowsFormatInnerExceptionForString("*1, 1"); } public static IEnumerable<object[]> ConvertFrom_NotSupportedData => new[] { new object[] {new Point(1, 1)}, new object[] {new PointF(1, 1)}, new object[] {new Size(1, 1)}, new object[] {new SizeF(1, 1)}, new object[] {0x10}, }; [Theory] [MemberData(nameof(ConvertFrom_NotSupportedData))] public void ConvertFrom_NotSupported(object value) { ConvertFromThrowsNotSupportedFor(value); } [Theory] [MemberData(nameof(PointData))] public void ConvertTo(int x, int y) { TestConvertToString(new Point(x, y), $"{x}, {y}"); } [Theory] [InlineData(typeof(Size))] [InlineData(typeof(SizeF))] [InlineData(typeof(Point))] [InlineData(typeof(PointF))] [InlineData(typeof(int))] public void ConvertTo_NotSupportedException(Type type) { ConvertToThrowsNotSupportedForType(type); } [Fact] public void ConvertTo_NullCulture() { string listSep = CultureInfo.CurrentCulture.TextInfo.ListSeparator; Assert.Equal($"1{listSep} 1", Converter.ConvertTo(null, null, new Point(1, 1), typeof(string))); } [Fact] public void CreateInstance_CaseSensitive() { AssertExtensions.Throws<ArgumentException>(null, () => { Converter.CreateInstance(null, new Dictionary<string, object> { ["x"] = 1, ["y"] = -1, }); }); } [Fact] public void GetProperties() { var pt = new Point(1, 1); var props = Converter.GetProperties(new Point(1, 1)); Assert.Equal(2, props.Count); Assert.Equal(1, props["X"].GetValue(pt)); Assert.Equal(1, props["Y"].GetValue(pt)); props = Converter.GetProperties(null, new Point(1, 1)); Assert.Equal(2, props.Count); Assert.Equal(1, props["X"].GetValue(pt)); Assert.Equal(1, props["Y"].GetValue(pt)); props = Converter.GetProperties(null, new Point(1, 1), null); Assert.Equal(3, props.Count); Assert.Equal(1, props["X"].GetValue(pt)); Assert.Equal(1, props["Y"].GetValue(pt)); Assert.Equal((object)false, props["IsEmpty"].GetValue(pt)); props = Converter.GetProperties(null, new Point(1, 1), new Attribute[0]); Assert.Equal(3, props.Count); Assert.Equal(1, props["X"].GetValue(pt)); Assert.Equal(1, props["Y"].GetValue(pt)); Assert.Equal((object)false, props["IsEmpty"].GetValue(pt)); // Pick an attribute that cannot be applied to properties to make sure everything gets filtered props = Converter.GetProperties(null, new Point(1, 1), new Attribute[] { new System.Reflection.AssemblyCopyrightAttribute("")}); Assert.Equal(0, props.Count); } [Theory] [MemberData(nameof(PointData))] public void ConvertFromInvariantString(int x, int y) { var point = (Point)Converter.ConvertFromInvariantString($"{x}, {y}"); Assert.Equal(x, point.X); Assert.Equal(y, point.Y); } [Fact] public void ConvertFromInvariantString_ArgumentException() { ConvertFromInvariantStringThrowsArgumentException("1"); } [Fact] public void ConvertFromInvariantString_FormatException() { ConvertFromInvariantStringThrowsFormatInnerException("hello"); } [Theory] [MemberData(nameof(PointData))] public void ConvertFromString(int x, int y) { var point = (Point)Converter.ConvertFromString(string.Format("{0}{2} {1}", x, y, CultureInfo.CurrentCulture.TextInfo.ListSeparator)); Assert.Equal(x, point.X); Assert.Equal(y, point.Y); } [Fact] public void ConvertFromString_ArgumentException() { ConvertFromStringThrowsArgumentException("1"); } [Fact] public void ConvertFromString_FormatException() { ConvertFromStringThrowsFormatInnerException("hello"); } [Theory] [MemberData(nameof(PointData))] public void ConvertToInvariantString(int x, int y) { var str = Converter.ConvertToInvariantString(new Point(x, y)); Assert.Equal($"{x}, {y}", str); } [Theory] [MemberData(nameof(PointData))] public void ConvertToString(int x, int y) { var str = Converter.ConvertToString(new Point(x, y)); Assert.Equal(string.Format("{0}{2} {1}", x, y, CultureInfo.CurrentCulture.TextInfo.ListSeparator), str); } } }
// 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.Drawing; using System.Globalization; using System.Linq; using Xunit; namespace System.ComponentModel.TypeConverterTests { public class PointConverterTests : StringTypeConverterTestBase<Point> { protected override TypeConverter Converter { get; } = new PointConverter(); protected override bool StandardValuesSupported { get; } = false; protected override bool StandardValuesExclusive { get; } = false; protected override Point Default => new Point(1, 1); protected override bool CreateInstanceSupported { get; } = true; protected override bool IsGetPropertiesSupported { get; } = true; protected override IEnumerable<Tuple<Point, Dictionary<string, object>>> CreateInstancePairs { get { yield return Tuple.Create(new Point(10, 20), new Dictionary<string, object> { ["X"] = 10, ["Y"] = 20, }); yield return Tuple.Create(new Point(-2, 3), new Dictionary<string, object> { ["X"] = -2, ["Y"] = 3, }); } } [Theory] [InlineData(typeof(string))] public void CanConvertFromTrue(Type type) { CanConvertFrom(type); } [Theory] [InlineData(typeof(Rectangle))] [InlineData(typeof(RectangleF))] [InlineData(typeof(Point))] [InlineData(typeof(PointF))] [InlineData(typeof(Color))] [InlineData(typeof(Size))] [InlineData(typeof(SizeF))] [InlineData(typeof(object))] [InlineData(typeof(int))] public void CanConvertFromFalse(Type type) { CannotConvertFrom(type); } [Theory] [InlineData(typeof(string))] public void CanConvertToTrue(Type type) { CanConvertTo(type); } [Theory] [InlineData(typeof(Rectangle))] [InlineData(typeof(RectangleF))] [InlineData(typeof(Point))] [InlineData(typeof(PointF))] [InlineData(typeof(Color))] [InlineData(typeof(Size))] [InlineData(typeof(SizeF))] [InlineData(typeof(object))] [InlineData(typeof(int))] public void CanConvertToFalse(Type type) { CannotConvertTo(type); } public static IEnumerable<object[]> PointData => new[] { new object[] {0, 0}, new object[] {1, 1}, new object[] {-1, 1}, new object[] {1, -1}, new object[] {-1, -1}, new object[] {int.MaxValue, int.MaxValue}, new object[] {int.MinValue, int.MaxValue}, new object[] {int.MaxValue, int.MinValue}, new object[] {int.MinValue, int.MinValue}, }; [Theory] [MemberData(nameof(PointData))] public void ConvertFrom(int x, int y) { TestConvertFromString(new Point(x, y), $"{x}, {y}"); } [Theory] [InlineData("1")] [InlineData("1, 1, 1")] public void ConvertFrom_ArgumentException(string value) { ConvertFromThrowsArgumentExceptionForString(value); } [Fact] public void ConvertFrom_Invalid() { ConvertFromThrowsFormatInnerExceptionForString("*1, 1"); } public static IEnumerable<object[]> ConvertFrom_NotSupportedData => new[] { new object[] {new Point(1, 1)}, new object[] {new PointF(1, 1)}, new object[] {new Size(1, 1)}, new object[] {new SizeF(1, 1)}, new object[] {0x10}, }; [Theory] [MemberData(nameof(ConvertFrom_NotSupportedData))] public void ConvertFrom_NotSupported(object value) { ConvertFromThrowsNotSupportedFor(value); } [Theory] [MemberData(nameof(PointData))] public void ConvertTo(int x, int y) { TestConvertToString(new Point(x, y), $"{x}, {y}"); } [Theory] [InlineData(typeof(Size))] [InlineData(typeof(SizeF))] [InlineData(typeof(Point))] [InlineData(typeof(PointF))] [InlineData(typeof(int))] public void ConvertTo_NotSupportedException(Type type) { ConvertToThrowsNotSupportedForType(type); } [Fact] public void ConvertTo_NullCulture() { string listSep = CultureInfo.CurrentCulture.TextInfo.ListSeparator; Assert.Equal($"1{listSep} 1", Converter.ConvertTo(null, null, new Point(1, 1), typeof(string))); } [Fact] public void CreateInstance_CaseSensitive() { AssertExtensions.Throws<ArgumentException>(null, () => { Converter.CreateInstance(null, new Dictionary<string, object> { ["x"] = 1, ["y"] = -1, }); }); } [Fact] public void GetProperties() { var pt = new Point(1, 1); var props = Converter.GetProperties(new Point(1, 1)); Assert.Equal(2, props.Count); Assert.Equal(1, props["X"].GetValue(pt)); Assert.Equal(1, props["Y"].GetValue(pt)); props = Converter.GetProperties(null, new Point(1, 1)); Assert.Equal(2, props.Count); Assert.Equal(1, props["X"].GetValue(pt)); Assert.Equal(1, props["Y"].GetValue(pt)); props = Converter.GetProperties(null, new Point(1, 1), null); Assert.Equal(3, props.Count); Assert.Equal(1, props["X"].GetValue(pt)); Assert.Equal(1, props["Y"].GetValue(pt)); Assert.Equal((object)false, props["IsEmpty"].GetValue(pt)); props = Converter.GetProperties(null, new Point(1, 1), new Attribute[0]); Assert.Equal(3, props.Count); Assert.Equal(1, props["X"].GetValue(pt)); Assert.Equal(1, props["Y"].GetValue(pt)); Assert.Equal((object)false, props["IsEmpty"].GetValue(pt)); // Pick an attribute that cannot be applied to properties to make sure everything gets filtered props = Converter.GetProperties(null, new Point(1, 1), new Attribute[] { new System.Reflection.AssemblyCopyrightAttribute("")}); Assert.Equal(0, props.Count); } [Theory] [MemberData(nameof(PointData))] public void ConvertFromInvariantString(int x, int y) { var point = (Point)Converter.ConvertFromInvariantString($"{x}, {y}"); Assert.Equal(x, point.X); Assert.Equal(y, point.Y); } [Fact] public void ConvertFromInvariantString_ArgumentException() { ConvertFromInvariantStringThrowsArgumentException("1"); } [Fact] public void ConvertFromInvariantString_FormatException() { ConvertFromInvariantStringThrowsFormatInnerException("hello"); } [Theory] [MemberData(nameof(PointData))] public void ConvertFromString(int x, int y) { var point = (Point)Converter.ConvertFromString(string.Format("{0}{2} {1}", x, y, CultureInfo.CurrentCulture.TextInfo.ListSeparator)); Assert.Equal(x, point.X); Assert.Equal(y, point.Y); } [Fact] public void ConvertFromString_ArgumentException() { ConvertFromStringThrowsArgumentException("1"); } [Fact] public void ConvertFromString_FormatException() { ConvertFromStringThrowsFormatInnerException("hello"); } [Theory] [MemberData(nameof(PointData))] public void ConvertToInvariantString(int x, int y) { var str = Converter.ConvertToInvariantString(new Point(x, y)); Assert.Equal($"{x}, {y}", str); } [Theory] [MemberData(nameof(PointData))] public void ConvertToString(int x, int y) { var str = Converter.ConvertToString(new Point(x, y)); Assert.Equal(string.Format("{0}{2} {1}", x, y, CultureInfo.CurrentCulture.TextInfo.ListSeparator), str); } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Drawing.Common/src/Interop/Windows/Interop.Kernel32.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; #if NET7_0_OR_GREATER using System.Runtime.InteropServices.Marshalling; #endif internal static partial class Interop { internal static partial class Kernel32 { [LibraryImport(Libraries.Kernel32, SetLastError = true)] public static partial int GetSystemDefaultLCID(); [LibraryImport(Libraries.Kernel32, EntryPoint = "GlobalAlloc", SetLastError = true)] internal static partial IntPtr IntGlobalAlloc(int uFlags, UIntPtr dwBytes); // size should be 32/64bits compatible internal static IntPtr GlobalAlloc(int uFlags, uint dwBytes) { return IntGlobalAlloc(uFlags, new UIntPtr(dwBytes)); } [LibraryImport(Libraries.Gdi32, SetLastError = true)] internal static partial IntPtr SelectObject( #if NET7_0_OR_GREATER [MarshalUsing(typeof(HandleRefMarshaller))] #endif HandleRef hdc, #if NET7_0_OR_GREATER [MarshalUsing(typeof(HandleRefMarshaller))] #endif HandleRef obj); } }
// 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; #if NET7_0_OR_GREATER using System.Runtime.InteropServices.Marshalling; #endif internal static partial class Interop { internal static partial class Kernel32 { [LibraryImport(Libraries.Kernel32, SetLastError = true)] public static partial int GetSystemDefaultLCID(); [LibraryImport(Libraries.Kernel32, EntryPoint = "GlobalAlloc", SetLastError = true)] internal static partial IntPtr IntGlobalAlloc(int uFlags, UIntPtr dwBytes); // size should be 32/64bits compatible internal static IntPtr GlobalAlloc(int uFlags, uint dwBytes) { return IntGlobalAlloc(uFlags, new UIntPtr(dwBytes)); } [LibraryImport(Libraries.Gdi32, SetLastError = true)] internal static partial IntPtr SelectObject( #if NET7_0_OR_GREATER [MarshalUsing(typeof(HandleRefMarshaller))] #endif HandleRef hdc, #if NET7_0_OR_GREATER [MarshalUsing(typeof(HandleRefMarshaller))] #endif HandleRef obj); } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/GroupCollectionTests.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 Xunit; namespace System.Text.RegularExpressions.Tests { public static partial class GroupCollectionTests { [Fact] public static void GetEnumerator() { Regex regex = new Regex(@"(?<A1>a*)(?<A2>b*)(?<A3>c*)"); Match match = regex.Match("aaabbccccccccccaaaabc"); GroupCollection groups = match.Groups; IEnumerator enumerator = groups.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { Assert.Equal(groups[counter], enumerator.Current); counter++; } Assert.False(enumerator.MoveNext()); Assert.Equal(groups.Count, counter); enumerator.Reset(); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Interface not implemented on .NET Framework")] public static void GetEnumerator_Generic() { Regex regex = new Regex(@"(?<A1>a*)(?<A2>b*)(?<A3>c*)"); Match match = regex.Match("aaabbccccccccccaaaabc"); GroupCollection groups = match.Groups; IEnumerator<KeyValuePair<string, Group>> enumerator = ((IEnumerable<KeyValuePair<string, Group>>)groups).GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { Assert.Equal(groups[counter], enumerator.Current.Value); counter++; } Assert.False(enumerator.MoveNext()); Assert.Equal(groups.Count, counter); enumerator.Reset(); } } [Fact] public static void GetEnumerator_Invalid() { Regex regex = new Regex(@"(?<A1>a*)(?<A2>b*)(?<A3>c*)"); Match match = regex.Match("aaabbccccccccccaaaabc"); IEnumerator enumerator = match.Groups.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); while (enumerator.MoveNext()) ; Assert.Throws<InvalidOperationException>(() => enumerator.Current); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Interface not implemented on .NET Framework")] public static void GetEnumerator_Generic_Invalid() { Regex regex = new Regex(@"(?<A1>a*)(?<A2>b*)(?<A3>c*)"); Match match = regex.Match("aaabbccccccccccaaaabc"); IEnumerator<KeyValuePair<string, Group>> enumerator = ((IEnumerable<KeyValuePair<string, Group>>)match.Groups).GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); while (enumerator.MoveNext()) ; Assert.Throws<InvalidOperationException>(() => enumerator.Current); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); } [Fact] public static void Item_Get() { GroupCollection collection = CreateCollection(); Assert.Equal("212-555-6666", collection[0].ToString()); Assert.Equal("212", collection[1].ToString()); Assert.Equal("555-6666", collection[2].ToString()); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Interface not implemented on .NET Framework")] public static void ContainsKey() { IReadOnlyDictionary<string, Group> collection = (IReadOnlyDictionary<string, Group>)CreateCollection(); Assert.True(collection.ContainsKey("0")); Assert.True(collection.ContainsKey("1")); Assert.True(collection.ContainsKey("2")); Assert.False(collection.ContainsKey("3")); } [Theory] [InlineData(-1)] [InlineData(4)] public static void Item_Invalid(int groupNumber) { Regex regex = new Regex(@"(?<A1>a*)(?<A2>b*)(?<A3>c*)"); GroupCollection groups = regex.Match("aaabbccccccccccaaaabc").Groups; Group group = groups[groupNumber]; Assert.Same(string.Empty, group.Value); Assert.Equal(0, group.Index); Assert.Equal(0, group.Length); Assert.Equal(0, group.Captures.Count); } [Fact] public static void ICollection_Properties() { Regex regex = new Regex(@"(?<A1>a*)(?<A2>b*)(?<A3>c*)"); GroupCollection groups = regex.Match("aaabbccccccccccaaaabc").Groups; ICollection collection = groups; Assert.False(collection.IsSynchronized); Assert.NotNull(collection.SyncRoot); Assert.Same(collection.SyncRoot, collection.SyncRoot); } [Theory] [InlineData(0)] [InlineData(5)] public static void ICollection_CopyTo(int index) { Regex regex = new Regex(@"(?<A1>a*)(?<A2>b*)(?<A3>c*)"); GroupCollection groups = regex.Match("aaabbccccccccccaaaabc").Groups; ICollection collection = groups; Group[] copy = new Group[collection.Count + index]; collection.CopyTo(copy, index); for (int i = 0; i < index; i++) { Assert.Null(copy[i]); } for (int i = index; i < copy.Length; i++) { Assert.Same(groups[i - index], copy[i]); } } [Fact] public static void ICollection_CopyTo_Invalid() { Regex regex = new Regex("e"); ICollection collection = regex.Match("aaabbccccccccccaaaabc").Groups; // Array is null AssertExtensions.Throws<ArgumentNullException>("array", () => collection.CopyTo(null, 0)); // Array is multidimensional AssertExtensions.Throws<ArgumentException>(null, () => collection.CopyTo(new object[10, 10], 0)); if (PlatformDetection.IsNonZeroLowerBoundArraySupported) { // Array has a non-zero lower bound Array o = Array.CreateInstance(typeof(object), new int[] { 10 }, new int[] { 10 }); Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(o, 0)); } // Index < 0 Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(new object[collection.Count], -1)); // Invalid index + length Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(new object[collection.Count], 1)); Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(new object[collection.Count + 1], 2)); } private static GroupCollection CreateCollection() { Regex regex = new Regex(@"(\d{3})-(\d{3}-\d{4})"); Match match = regex.Match("212-555-6666"); return match.Groups; } } }
// 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 Xunit; namespace System.Text.RegularExpressions.Tests { public static partial class GroupCollectionTests { [Fact] public static void GetEnumerator() { Regex regex = new Regex(@"(?<A1>a*)(?<A2>b*)(?<A3>c*)"); Match match = regex.Match("aaabbccccccccccaaaabc"); GroupCollection groups = match.Groups; IEnumerator enumerator = groups.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { Assert.Equal(groups[counter], enumerator.Current); counter++; } Assert.False(enumerator.MoveNext()); Assert.Equal(groups.Count, counter); enumerator.Reset(); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Interface not implemented on .NET Framework")] public static void GetEnumerator_Generic() { Regex regex = new Regex(@"(?<A1>a*)(?<A2>b*)(?<A3>c*)"); Match match = regex.Match("aaabbccccccccccaaaabc"); GroupCollection groups = match.Groups; IEnumerator<KeyValuePair<string, Group>> enumerator = ((IEnumerable<KeyValuePair<string, Group>>)groups).GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { Assert.Equal(groups[counter], enumerator.Current.Value); counter++; } Assert.False(enumerator.MoveNext()); Assert.Equal(groups.Count, counter); enumerator.Reset(); } } [Fact] public static void GetEnumerator_Invalid() { Regex regex = new Regex(@"(?<A1>a*)(?<A2>b*)(?<A3>c*)"); Match match = regex.Match("aaabbccccccccccaaaabc"); IEnumerator enumerator = match.Groups.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); while (enumerator.MoveNext()) ; Assert.Throws<InvalidOperationException>(() => enumerator.Current); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Interface not implemented on .NET Framework")] public static void GetEnumerator_Generic_Invalid() { Regex regex = new Regex(@"(?<A1>a*)(?<A2>b*)(?<A3>c*)"); Match match = regex.Match("aaabbccccccccccaaaabc"); IEnumerator<KeyValuePair<string, Group>> enumerator = ((IEnumerable<KeyValuePair<string, Group>>)match.Groups).GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); while (enumerator.MoveNext()) ; Assert.Throws<InvalidOperationException>(() => enumerator.Current); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); } [Fact] public static void Item_Get() { GroupCollection collection = CreateCollection(); Assert.Equal("212-555-6666", collection[0].ToString()); Assert.Equal("212", collection[1].ToString()); Assert.Equal("555-6666", collection[2].ToString()); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Interface not implemented on .NET Framework")] public static void ContainsKey() { IReadOnlyDictionary<string, Group> collection = (IReadOnlyDictionary<string, Group>)CreateCollection(); Assert.True(collection.ContainsKey("0")); Assert.True(collection.ContainsKey("1")); Assert.True(collection.ContainsKey("2")); Assert.False(collection.ContainsKey("3")); } [Theory] [InlineData(-1)] [InlineData(4)] public static void Item_Invalid(int groupNumber) { Regex regex = new Regex(@"(?<A1>a*)(?<A2>b*)(?<A3>c*)"); GroupCollection groups = regex.Match("aaabbccccccccccaaaabc").Groups; Group group = groups[groupNumber]; Assert.Same(string.Empty, group.Value); Assert.Equal(0, group.Index); Assert.Equal(0, group.Length); Assert.Equal(0, group.Captures.Count); } [Fact] public static void ICollection_Properties() { Regex regex = new Regex(@"(?<A1>a*)(?<A2>b*)(?<A3>c*)"); GroupCollection groups = regex.Match("aaabbccccccccccaaaabc").Groups; ICollection collection = groups; Assert.False(collection.IsSynchronized); Assert.NotNull(collection.SyncRoot); Assert.Same(collection.SyncRoot, collection.SyncRoot); } [Theory] [InlineData(0)] [InlineData(5)] public static void ICollection_CopyTo(int index) { Regex regex = new Regex(@"(?<A1>a*)(?<A2>b*)(?<A3>c*)"); GroupCollection groups = regex.Match("aaabbccccccccccaaaabc").Groups; ICollection collection = groups; Group[] copy = new Group[collection.Count + index]; collection.CopyTo(copy, index); for (int i = 0; i < index; i++) { Assert.Null(copy[i]); } for (int i = index; i < copy.Length; i++) { Assert.Same(groups[i - index], copy[i]); } } [Fact] public static void ICollection_CopyTo_Invalid() { Regex regex = new Regex("e"); ICollection collection = regex.Match("aaabbccccccccccaaaabc").Groups; // Array is null AssertExtensions.Throws<ArgumentNullException>("array", () => collection.CopyTo(null, 0)); // Array is multidimensional AssertExtensions.Throws<ArgumentException>(null, () => collection.CopyTo(new object[10, 10], 0)); if (PlatformDetection.IsNonZeroLowerBoundArraySupported) { // Array has a non-zero lower bound Array o = Array.CreateInstance(typeof(object), new int[] { 10 }, new int[] { 10 }); Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(o, 0)); } // Index < 0 Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(new object[collection.Count], -1)); // Invalid index + length Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(new object[collection.Count], 1)); Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(new object[collection.Count + 1], 2)); } private static GroupCollection CreateCollection() { Regex regex = new Regex(@"(\d{3})-(\d{3}-\d{4})"); Match match = regex.Match("212-555-6666"); return match.Groups; } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/Methodical/Boxing/morph/sin_morph_cs_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>None</DebugType> <Optimize>True</Optimize> <NoStandardLib>True</NoStandardLib> <Noconfig>True</Noconfig> </PropertyGroup> <ItemGroup> <Compile Include="sin.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>None</DebugType> <Optimize>True</Optimize> <NoStandardLib>True</NoStandardLib> <Noconfig>True</Noconfig> </PropertyGroup> <ItemGroup> <Compile Include="sin.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/Not.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 Not_Vector128_Single() { var test = new SimpleUnaryOpTest__Not_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__Not_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] = TestLibrary.Generator.GetSingle(); } 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__Not_Vector128_Single testClass) { var result = AdvSimd.Not(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__Not_Vector128_Single testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) { var result = AdvSimd.Not( 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__Not_Vector128_Single() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } 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__Not_Vector128_Single() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } 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] = TestLibrary.Generator.GetSingle(); } _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.Not( 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.Not( 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.Not), 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.Not), 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.Not( _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.Not( 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.Not(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.Not(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__Not_Vector128_Single(); var result = AdvSimd.Not(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__Not_Vector128_Single(); fixed (Vector128<Single>* pFld1 = &test._fld1) { var result = AdvSimd.Not( 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.Not(_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.Not( 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.Not(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.Not( 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(Helpers.Not(firstOp[i])) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Not)}<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 Not_Vector128_Single() { var test = new SimpleUnaryOpTest__Not_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__Not_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] = TestLibrary.Generator.GetSingle(); } 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__Not_Vector128_Single testClass) { var result = AdvSimd.Not(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__Not_Vector128_Single testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) { var result = AdvSimd.Not( 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__Not_Vector128_Single() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } 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__Not_Vector128_Single() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } 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] = TestLibrary.Generator.GetSingle(); } _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.Not( 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.Not( 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.Not), 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.Not), 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.Not( _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.Not( 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.Not(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.Not(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__Not_Vector128_Single(); var result = AdvSimd.Not(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__Not_Vector128_Single(); fixed (Vector128<Single>* pFld1 = &test._fld1) { var result = AdvSimd.Not( 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.Not(_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.Not( 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.Not(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.Not( 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(Helpers.Not(firstOp[i])) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Not)}<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
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Bytes.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Text; using System.Diagnostics; namespace System.Text.Json { public sealed partial class Utf8JsonWriter { /// <summary> /// Writes the raw bytes value as a Base64 encoded JSON string as an element of a JSON array. /// </summary> /// <param name="bytes">The binary data to write as Base64 encoded text.</param> /// <exception cref="ArgumentException"> /// Thrown when the specified value is too large. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown if this would result in invalid JSON being written (while validation is enabled). /// </exception> /// <remarks> /// The bytes are encoded before writing. /// </remarks> public void WriteBase64StringValue(ReadOnlySpan<byte> bytes) { JsonWriterHelper.ValidateBytes(bytes); WriteBase64ByOptions(bytes); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } private void WriteBase64ByOptions(ReadOnlySpan<byte> bytes) { if (!_options.SkipValidation) { ValidateWritingValue(); } if (_options.Indented) { WriteBase64Indented(bytes); } else { WriteBase64Minimized(bytes); } } // TODO: https://github.com/dotnet/runtime/issues/29293 private void WriteBase64Minimized(ReadOnlySpan<byte> bytes) { int encodingLength = Base64.GetMaxEncodedToUtf8Length(bytes.Length); Debug.Assert(encodingLength < int.MaxValue - 3); // 2 quotes to surround the base-64 encoded string value. // Optionally, 1 list separator int maxRequired = encodingLength + 3; if (_memory.Length - BytesPending < maxRequired) { Grow(maxRequired); } Span<byte> output = _memory.Span; if (_currentDepth < 0) { output[BytesPending++] = JsonConstants.ListSeparator; } output[BytesPending++] = JsonConstants.Quote; Base64EncodeAndWrite(bytes, output, encodingLength); output[BytesPending++] = JsonConstants.Quote; } // TODO: https://github.com/dotnet/runtime/issues/29293 private void WriteBase64Indented(ReadOnlySpan<byte> bytes) { int indent = Indentation; Debug.Assert(indent <= 2 * _options.MaxDepth); int encodingLength = Base64.GetMaxEncodedToUtf8Length(bytes.Length); Debug.Assert(encodingLength < int.MaxValue - indent - 3 - s_newLineLength); // indentation + 2 quotes to surround the base-64 encoded string value. // Optionally, 1 list separator, and 1-2 bytes for new line int maxRequired = indent + encodingLength + 3 + s_newLineLength; if (_memory.Length - BytesPending < maxRequired) { Grow(maxRequired); } Span<byte> output = _memory.Span; if (_currentDepth < 0) { output[BytesPending++] = JsonConstants.ListSeparator; } if (_tokenType != JsonTokenType.PropertyName) { if (_tokenType != JsonTokenType.None) { WriteNewLine(output); } JsonWriterHelper.WriteIndentation(output.Slice(BytesPending), indent); BytesPending += indent; } output[BytesPending++] = JsonConstants.Quote; Base64EncodeAndWrite(bytes, output, encodingLength); output[BytesPending++] = JsonConstants.Quote; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Text; using System.Diagnostics; namespace System.Text.Json { public sealed partial class Utf8JsonWriter { /// <summary> /// Writes the raw bytes value as a Base64 encoded JSON string as an element of a JSON array. /// </summary> /// <param name="bytes">The binary data to write as Base64 encoded text.</param> /// <exception cref="ArgumentException"> /// Thrown when the specified value is too large. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown if this would result in invalid JSON being written (while validation is enabled). /// </exception> /// <remarks> /// The bytes are encoded before writing. /// </remarks> public void WriteBase64StringValue(ReadOnlySpan<byte> bytes) { JsonWriterHelper.ValidateBytes(bytes); WriteBase64ByOptions(bytes); SetFlagToAddListSeparatorBeforeNextItem(); _tokenType = JsonTokenType.String; } private void WriteBase64ByOptions(ReadOnlySpan<byte> bytes) { if (!_options.SkipValidation) { ValidateWritingValue(); } if (_options.Indented) { WriteBase64Indented(bytes); } else { WriteBase64Minimized(bytes); } } // TODO: https://github.com/dotnet/runtime/issues/29293 private void WriteBase64Minimized(ReadOnlySpan<byte> bytes) { int encodingLength = Base64.GetMaxEncodedToUtf8Length(bytes.Length); Debug.Assert(encodingLength < int.MaxValue - 3); // 2 quotes to surround the base-64 encoded string value. // Optionally, 1 list separator int maxRequired = encodingLength + 3; if (_memory.Length - BytesPending < maxRequired) { Grow(maxRequired); } Span<byte> output = _memory.Span; if (_currentDepth < 0) { output[BytesPending++] = JsonConstants.ListSeparator; } output[BytesPending++] = JsonConstants.Quote; Base64EncodeAndWrite(bytes, output, encodingLength); output[BytesPending++] = JsonConstants.Quote; } // TODO: https://github.com/dotnet/runtime/issues/29293 private void WriteBase64Indented(ReadOnlySpan<byte> bytes) { int indent = Indentation; Debug.Assert(indent <= 2 * _options.MaxDepth); int encodingLength = Base64.GetMaxEncodedToUtf8Length(bytes.Length); Debug.Assert(encodingLength < int.MaxValue - indent - 3 - s_newLineLength); // indentation + 2 quotes to surround the base-64 encoded string value. // Optionally, 1 list separator, and 1-2 bytes for new line int maxRequired = indent + encodingLength + 3 + s_newLineLength; if (_memory.Length - BytesPending < maxRequired) { Grow(maxRequired); } Span<byte> output = _memory.Span; if (_currentDepth < 0) { output[BytesPending++] = JsonConstants.ListSeparator; } if (_tokenType != JsonTokenType.PropertyName) { if (_tokenType != JsonTokenType.None) { WriteNewLine(output); } JsonWriterHelper.WriteIndentation(output.Slice(BytesPending), indent); BytesPending += indent; } output[BytesPending++] = JsonConstants.Quote; Base64EncodeAndWrite(bytes, output, encodingLength); output[BytesPending++] = JsonConstants.Quote; } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodemap.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; namespace System.Xml { // Represents a collection of nodes that can be accessed by name or index. public partial class XmlNamedNodeMap : IEnumerable { internal XmlNode parent; internal SmallXmlNodeList nodes; internal XmlNamedNodeMap(XmlNode parent) { this.parent = parent; } // Retrieves a XmlNode specified by name. public virtual XmlNode? GetNamedItem(string name) { int offset = FindNodeOffset(name); if (offset >= 0) return (XmlNode)nodes[offset]; return null; } // Adds a XmlNode using its Name property public virtual XmlNode? SetNamedItem(XmlNode? node) { if (node == null) return null; int offset = FindNodeOffset(node.LocalName, node.NamespaceURI); if (offset == -1) { AddNode(node); return null; } else { return ReplaceNodeAt(offset, node); } } // Removes the node specified by name. public virtual XmlNode? RemoveNamedItem(string name) { int offset = FindNodeOffset(name); if (offset >= 0) { return RemoveNodeAt(offset); } return null; } // Gets the number of nodes in this XmlNamedNodeMap. public virtual int Count { get { return nodes.Count; } } // Retrieves the node at the specified index in this XmlNamedNodeMap. public virtual XmlNode? Item(int index) { if (index < 0 || index >= nodes.Count) return null; try { return (XmlNode)nodes[index]; } catch (ArgumentOutOfRangeException) { throw new IndexOutOfRangeException(SR.Xdom_IndexOutOfRange); } } // // DOM Level 2 // // Retrieves a node specified by LocalName and NamespaceURI. public virtual XmlNode? GetNamedItem(string localName, string? namespaceURI) { int offset = FindNodeOffset(localName, namespaceURI); if (offset >= 0) return (XmlNode)nodes[offset]; return null; } // Removes a node specified by local name and namespace URI. public virtual XmlNode? RemoveNamedItem(string localName, string? namespaceURI) { int offset = FindNodeOffset(localName, namespaceURI); if (offset >= 0) { return RemoveNodeAt(offset); } return null; } public virtual IEnumerator GetEnumerator() { return nodes.GetEnumerator(); } internal int FindNodeOffset(string name) { int c = this.Count; for (int i = 0; i < c; i++) { XmlNode node = (XmlNode)nodes[i]; if (name == node.Name) return i; } return -1; } internal int FindNodeOffset(string localName, string? namespaceURI) { int c = this.Count; for (int i = 0; i < c; i++) { XmlNode node = (XmlNode)nodes[i]; if (node.LocalName == localName && node.NamespaceURI == namespaceURI) return i; } return -1; } internal virtual XmlNode AddNode(XmlNode node) { XmlNode? oldParent; if (node.NodeType == XmlNodeType.Attribute) oldParent = ((XmlAttribute)node).OwnerElement; else oldParent = node.ParentNode; string? nodeValue = node.Value; XmlNodeChangedEventArgs? args = parent.GetEventArgs(node, oldParent, parent, nodeValue, nodeValue, XmlNodeChangedAction.Insert); if (args != null) parent.BeforeEvent(args); nodes.Add(node); node.SetParent(parent); if (args != null) parent.AfterEvent(args); return node; } internal virtual XmlNode AddNodeForLoad(XmlNode node, XmlDocument doc) { XmlNodeChangedEventArgs? args = doc.GetInsertEventArgsForLoad(node, parent); if (args != null) { doc.BeforeEvent(args); } nodes.Add(node); node.SetParent(parent); if (args != null) { doc.AfterEvent(args); } return node; } internal virtual XmlNode RemoveNodeAt(int i) { XmlNode oldNode = (XmlNode)nodes[i]; string? oldNodeValue = oldNode.Value; XmlNodeChangedEventArgs? args = parent.GetEventArgs(oldNode, parent, null, oldNodeValue, oldNodeValue, XmlNodeChangedAction.Remove); if (args != null) parent.BeforeEvent(args); nodes.RemoveAt(i); oldNode.SetParent(null); if (args != null) parent.AfterEvent(args); return oldNode; } internal XmlNode ReplaceNodeAt(int i, XmlNode node) { XmlNode oldNode = RemoveNodeAt(i); InsertNodeAt(i, node); return oldNode; } internal virtual XmlNode InsertNodeAt(int i, XmlNode node) { XmlNode? oldParent; if (node.NodeType == XmlNodeType.Attribute) oldParent = ((XmlAttribute)node).OwnerElement; else oldParent = node.ParentNode; string? nodeValue = node.Value; XmlNodeChangedEventArgs? args = parent.GetEventArgs(node, oldParent, parent, nodeValue, nodeValue, XmlNodeChangedAction.Insert); if (args != null) parent.BeforeEvent(args); nodes.Insert(i, node); node.SetParent(parent); if (args != null) parent.AfterEvent(args); return node; } } }
// 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; namespace System.Xml { // Represents a collection of nodes that can be accessed by name or index. public partial class XmlNamedNodeMap : IEnumerable { internal XmlNode parent; internal SmallXmlNodeList nodes; internal XmlNamedNodeMap(XmlNode parent) { this.parent = parent; } // Retrieves a XmlNode specified by name. public virtual XmlNode? GetNamedItem(string name) { int offset = FindNodeOffset(name); if (offset >= 0) return (XmlNode)nodes[offset]; return null; } // Adds a XmlNode using its Name property public virtual XmlNode? SetNamedItem(XmlNode? node) { if (node == null) return null; int offset = FindNodeOffset(node.LocalName, node.NamespaceURI); if (offset == -1) { AddNode(node); return null; } else { return ReplaceNodeAt(offset, node); } } // Removes the node specified by name. public virtual XmlNode? RemoveNamedItem(string name) { int offset = FindNodeOffset(name); if (offset >= 0) { return RemoveNodeAt(offset); } return null; } // Gets the number of nodes in this XmlNamedNodeMap. public virtual int Count { get { return nodes.Count; } } // Retrieves the node at the specified index in this XmlNamedNodeMap. public virtual XmlNode? Item(int index) { if (index < 0 || index >= nodes.Count) return null; try { return (XmlNode)nodes[index]; } catch (ArgumentOutOfRangeException) { throw new IndexOutOfRangeException(SR.Xdom_IndexOutOfRange); } } // // DOM Level 2 // // Retrieves a node specified by LocalName and NamespaceURI. public virtual XmlNode? GetNamedItem(string localName, string? namespaceURI) { int offset = FindNodeOffset(localName, namespaceURI); if (offset >= 0) return (XmlNode)nodes[offset]; return null; } // Removes a node specified by local name and namespace URI. public virtual XmlNode? RemoveNamedItem(string localName, string? namespaceURI) { int offset = FindNodeOffset(localName, namespaceURI); if (offset >= 0) { return RemoveNodeAt(offset); } return null; } public virtual IEnumerator GetEnumerator() { return nodes.GetEnumerator(); } internal int FindNodeOffset(string name) { int c = this.Count; for (int i = 0; i < c; i++) { XmlNode node = (XmlNode)nodes[i]; if (name == node.Name) return i; } return -1; } internal int FindNodeOffset(string localName, string? namespaceURI) { int c = this.Count; for (int i = 0; i < c; i++) { XmlNode node = (XmlNode)nodes[i]; if (node.LocalName == localName && node.NamespaceURI == namespaceURI) return i; } return -1; } internal virtual XmlNode AddNode(XmlNode node) { XmlNode? oldParent; if (node.NodeType == XmlNodeType.Attribute) oldParent = ((XmlAttribute)node).OwnerElement; else oldParent = node.ParentNode; string? nodeValue = node.Value; XmlNodeChangedEventArgs? args = parent.GetEventArgs(node, oldParent, parent, nodeValue, nodeValue, XmlNodeChangedAction.Insert); if (args != null) parent.BeforeEvent(args); nodes.Add(node); node.SetParent(parent); if (args != null) parent.AfterEvent(args); return node; } internal virtual XmlNode AddNodeForLoad(XmlNode node, XmlDocument doc) { XmlNodeChangedEventArgs? args = doc.GetInsertEventArgsForLoad(node, parent); if (args != null) { doc.BeforeEvent(args); } nodes.Add(node); node.SetParent(parent); if (args != null) { doc.AfterEvent(args); } return node; } internal virtual XmlNode RemoveNodeAt(int i) { XmlNode oldNode = (XmlNode)nodes[i]; string? oldNodeValue = oldNode.Value; XmlNodeChangedEventArgs? args = parent.GetEventArgs(oldNode, parent, null, oldNodeValue, oldNodeValue, XmlNodeChangedAction.Remove); if (args != null) parent.BeforeEvent(args); nodes.RemoveAt(i); oldNode.SetParent(null); if (args != null) parent.AfterEvent(args); return oldNode; } internal XmlNode ReplaceNodeAt(int i, XmlNode node) { XmlNode oldNode = RemoveNodeAt(i); InsertNodeAt(i, node); return oldNode; } internal virtual XmlNode InsertNodeAt(int i, XmlNode node) { XmlNode? oldParent; if (node.NodeType == XmlNodeType.Attribute) oldParent = ((XmlAttribute)node).OwnerElement; else oldParent = node.ParentNode; string? nodeValue = node.Value; XmlNodeChangedEventArgs? args = parent.GetEventArgs(node, oldParent, parent, nodeValue, nodeValue, XmlNodeChangedAction.Insert); if (args != null) parent.BeforeEvent(args); nodes.Insert(i, node); node.SetParent(parent); if (args != null) parent.AfterEvent(args); return node; } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/HardwareIntrinsics/General/Vector64/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 Vector64<UInt16> _fld1; public Vector64<UInt16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__DotUInt16 testClass) { var result = Vector64.Dot(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector64<UInt16> _clsVar1; private static Vector64<UInt16> _clsVar2; private Vector64<UInt16> _fld1; private Vector64<UInt16> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__DotUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); } public VectorBinaryOpTest__DotUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector64.Dot( Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector64).GetMethod(nameof(Vector64.Dot), new Type[] { typeof(Vector64<UInt16>), typeof(Vector64<UInt16>) }); if (method is null) { method = typeof(Vector64).GetMethod(nameof(Vector64.Dot), 1, new Type[] { typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(UInt16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (UInt16)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector64.Dot( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr); var result = Vector64.Dot(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__DotUInt16(); var result = Vector64.Dot(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector64.Dot(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector64.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(Vector64<UInt16> op1, Vector64<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<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<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(Vector64)}.{nameof(Vector64.Dot)}<UInt16>(Vector64<UInt16>, Vector64<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: {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 Vector64<UInt16> _fld1; public Vector64<UInt16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__DotUInt16 testClass) { var result = Vector64.Dot(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector64<UInt16> _clsVar1; private static Vector64<UInt16> _clsVar2; private Vector64<UInt16> _fld1; private Vector64<UInt16> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__DotUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); } public VectorBinaryOpTest__DotUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector64.Dot( Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector64).GetMethod(nameof(Vector64.Dot), new Type[] { typeof(Vector64<UInt16>), typeof(Vector64<UInt16>) }); if (method is null) { method = typeof(Vector64).GetMethod(nameof(Vector64.Dot), 1, new Type[] { typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(UInt16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (UInt16)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector64.Dot( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr); var result = Vector64.Dot(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__DotUInt16(); var result = Vector64.Dot(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector64.Dot(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector64.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(Vector64<UInt16> op1, Vector64<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<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<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(Vector64)}.{nameof(Vector64.Dot)}<UInt16>(Vector64<UInt16>, Vector64<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: {result}"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/OidEnumerator.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; namespace System.Security.Cryptography { public sealed class OidEnumerator : IEnumerator { internal OidEnumerator(OidCollection oids) { _oids = oids; _current = -1; } public Oid Current => _oids[_current]; object IEnumerator.Current => Current; public bool MoveNext() { if (_current >= _oids.Count - 1) return false; _current++; return true; } public void Reset() { _current = -1; } private readonly OidCollection _oids; private int _current; } }
// 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; namespace System.Security.Cryptography { public sealed class OidEnumerator : IEnumerator { internal OidEnumerator(OidCollection oids) { _oids = oids; _current = -1; } public Oid Current => _oids[_current]; object IEnumerator.Current => Current; public bool MoveNext() { if (_current >= _oids.Count - 1) return false; _current++; return true; } public void Reset() { _current = -1; } private readonly OidCollection _oids; private int _current; } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b79642/b79642.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>PdbOnly</DebugType> <NoStandardLib>True</NoStandardLib> <Noconfig>True</Noconfig> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>PdbOnly</DebugType> <NoStandardLib>True</NoStandardLib> <Noconfig>True</Noconfig> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Private.CoreLib/src/System/Collections/Generic/IReadOnlyDictionary.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.Collections.Generic { // Provides a read-only view of a generic dictionary. public interface IReadOnlyDictionary<TKey, TValue> : IReadOnlyCollection<KeyValuePair<TKey, TValue>> { bool ContainsKey(TKey key); bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value); TValue this[TKey key] { get; } IEnumerable<TKey> Keys { get; } IEnumerable<TValue> Values { get; } } }
// 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.Collections.Generic { // Provides a read-only view of a generic dictionary. public interface IReadOnlyDictionary<TKey, TValue> : IReadOnlyCollection<KeyValuePair<TKey, TValue>> { bool ContainsKey(TKey key); bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value); TValue this[TKey key] { get; } IEnumerable<TKey> Keys { get; } IEnumerable<TValue> Values { get; } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/HardwareIntrinsics/General/Vector128/LessThanOrEqualAny.Int32.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void LessThanOrEqualAnyInt32() { var test = new VectorBooleanBinaryOpTest__LessThanOrEqualAnyInt32(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBooleanBinaryOpTest__LessThanOrEqualAnyInt32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); 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<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 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<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(VectorBooleanBinaryOpTest__LessThanOrEqualAnyInt32 testClass) { var result = Vector128.LessThanOrEqualAny(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } 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 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 VectorBooleanBinaryOpTest__LessThanOrEqualAnyInt32() { 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 VectorBooleanBinaryOpTest__LessThanOrEqualAnyInt32() { 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, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.LessThanOrEqualAny( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_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.LessThanOrEqualAny), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.LessThanOrEqualAny), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int32)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.LessThanOrEqualAny( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } 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 = Vector128.LessThanOrEqualAny(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__LessThanOrEqualAnyInt32(); var result = Vector128.LessThanOrEqualAny(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.LessThanOrEqualAny(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.LessThanOrEqualAny(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<Int32> op1, Vector128<Int32> op2, bool result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; 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>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int32[] left, Int32[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = false; for (var i = 0; i < Op1ElementCount; i++) { expectedResult |= (left[i] <= right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.LessThanOrEqualAny)}<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: ({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 LessThanOrEqualAnyInt32() { var test = new VectorBooleanBinaryOpTest__LessThanOrEqualAnyInt32(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBooleanBinaryOpTest__LessThanOrEqualAnyInt32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); 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<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 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<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(VectorBooleanBinaryOpTest__LessThanOrEqualAnyInt32 testClass) { var result = Vector128.LessThanOrEqualAny(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } 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 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 VectorBooleanBinaryOpTest__LessThanOrEqualAnyInt32() { 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 VectorBooleanBinaryOpTest__LessThanOrEqualAnyInt32() { 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, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.LessThanOrEqualAny( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_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.LessThanOrEqualAny), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.LessThanOrEqualAny), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int32)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.LessThanOrEqualAny( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } 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 = Vector128.LessThanOrEqualAny(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__LessThanOrEqualAnyInt32(); var result = Vector128.LessThanOrEqualAny(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.LessThanOrEqualAny(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.LessThanOrEqualAny(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<Int32> op1, Vector128<Int32> op2, bool result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; 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>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int32[] left, Int32[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = false; for (var i = 0; i < Op1ElementCount; i++) { expectedResult |= (left[i] <= right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.LessThanOrEqualAny)}<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: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/NewArrayFixupSignature.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Internal.Text; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; using Internal.ReadyToRunConstants; namespace ILCompiler.DependencyAnalysis.ReadyToRun { public class NewArrayFixupSignature : Signature { private readonly ArrayType _arrayType; public NewArrayFixupSignature(ArrayType arrayType) { _arrayType = arrayType; // Ensure types in signature are loadable and resolvable, otherwise we'll fail later while emitting the signature ((CompilerTypeSystemContext)arrayType.Context).EnsureLoadableType(arrayType); } public override int ClassCode => 815543321; public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { ObjectDataSignatureBuilder dataBuilder = new ObjectDataSignatureBuilder(); if (!relocsOnly) { dataBuilder.AddSymbol(this); EcmaModule targetModule = factory.SignatureContext.GetTargetModule(_arrayType); SignatureContext innerContext = dataBuilder.EmitFixup(factory, ReadyToRunFixupKind.NewArray, targetModule, factory.SignatureContext); dataBuilder.EmitTypeSignature(_arrayType, innerContext); } return dataBuilder.ToObjectData(); } public override void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(nameMangler.CompilationUnitPrefix); sb.Append($@"NewArraySignature: "); sb.Append(nameMangler.GetMangledTypeName(_arrayType)); } public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { NewArrayFixupSignature otherNode = (NewArrayFixupSignature)other; return comparer.Compare(_arrayType, otherNode._arrayType); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Internal.Text; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; using Internal.ReadyToRunConstants; namespace ILCompiler.DependencyAnalysis.ReadyToRun { public class NewArrayFixupSignature : Signature { private readonly ArrayType _arrayType; public NewArrayFixupSignature(ArrayType arrayType) { _arrayType = arrayType; // Ensure types in signature are loadable and resolvable, otherwise we'll fail later while emitting the signature ((CompilerTypeSystemContext)arrayType.Context).EnsureLoadableType(arrayType); } public override int ClassCode => 815543321; public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { ObjectDataSignatureBuilder dataBuilder = new ObjectDataSignatureBuilder(); if (!relocsOnly) { dataBuilder.AddSymbol(this); EcmaModule targetModule = factory.SignatureContext.GetTargetModule(_arrayType); SignatureContext innerContext = dataBuilder.EmitFixup(factory, ReadyToRunFixupKind.NewArray, targetModule, factory.SignatureContext); dataBuilder.EmitTypeSignature(_arrayType, innerContext); } return dataBuilder.ToObjectData(); } public override void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(nameMangler.CompilationUnitPrefix); sb.Append($@"NewArraySignature: "); sb.Append(nameMangler.GetMangledTypeName(_arrayType)); } public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { NewArrayFixupSignature otherNode = (NewArrayFixupSignature)other; return comparer.Compare(_arrayType, otherNode._arrayType); } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/ComputedStaticDependencyNode.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.Text; using System.Threading.Tasks; using System.Diagnostics; namespace ILCompiler.DependencyAnalysisFramework { public abstract class ComputedStaticDependencyNode<DependencyContextType> : DependencyNodeCore<DependencyContextType> { private IEnumerable<DependencyListEntry> _dependencies; private IEnumerable<CombinedDependencyListEntry> _conditionalDependencies; public void SetStaticDependencies(IEnumerable<DependencyListEntry> dependencies, IEnumerable<CombinedDependencyListEntry> conditionalDependencies) { Debug.Assert(_dependencies == null); Debug.Assert(_conditionalDependencies == null); Debug.Assert(dependencies != null); _dependencies = dependencies; _conditionalDependencies = conditionalDependencies; } public override bool HasConditionalStaticDependencies { get { return _conditionalDependencies != null; } } public override bool HasDynamicDependencies { get { return false; } } public override bool InterestingForDynamicDependencyAnalysis { get { return true; } } public override bool StaticDependenciesAreComputed { get { return _dependencies != null; } } public override IEnumerable<CombinedDependencyListEntry> GetConditionalStaticDependencies(DependencyContextType context) { return _conditionalDependencies; } public override IEnumerable<DependencyListEntry> GetStaticDependencies(DependencyContextType context) { return _dependencies; } public override IEnumerable<CombinedDependencyListEntry> SearchDynamicDependencies(List<DependencyNodeCore<DependencyContextType>> markedNodes, int firstNode, DependencyContextType context) { return Array.Empty<CombinedDependencyListEntry>(); } } }
// 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.Text; using System.Threading.Tasks; using System.Diagnostics; namespace ILCompiler.DependencyAnalysisFramework { public abstract class ComputedStaticDependencyNode<DependencyContextType> : DependencyNodeCore<DependencyContextType> { private IEnumerable<DependencyListEntry> _dependencies; private IEnumerable<CombinedDependencyListEntry> _conditionalDependencies; public void SetStaticDependencies(IEnumerable<DependencyListEntry> dependencies, IEnumerable<CombinedDependencyListEntry> conditionalDependencies) { Debug.Assert(_dependencies == null); Debug.Assert(_conditionalDependencies == null); Debug.Assert(dependencies != null); _dependencies = dependencies; _conditionalDependencies = conditionalDependencies; } public override bool HasConditionalStaticDependencies { get { return _conditionalDependencies != null; } } public override bool HasDynamicDependencies { get { return false; } } public override bool InterestingForDynamicDependencyAnalysis { get { return true; } } public override bool StaticDependenciesAreComputed { get { return _dependencies != null; } } public override IEnumerable<CombinedDependencyListEntry> GetConditionalStaticDependencies(DependencyContextType context) { return _conditionalDependencies; } public override IEnumerable<DependencyListEntry> GetStaticDependencies(DependencyContextType context) { return _dependencies; } public override IEnumerable<CombinedDependencyListEntry> SearchDynamicDependencies(List<DependencyNodeCore<DependencyContextType>> markedNodes, int firstNode, DependencyContextType context) { return Array.Empty<CombinedDependencyListEntry>(); } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/GC/Scenarios/GCSimulator/GCSimulator_45.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <GCStressIncompatible>true</GCStressIncompatible> <CLRTestExecutionArguments>-t 3 -tp 0 -dz 17 -sdz 8500 -dc 10000 -sdc 5000 -lt 2 -f -dp 0.0 -dw 0.0</CLRTestExecutionArguments> <IsGCSimulatorTest>true</IsGCSimulatorTest> <CLRTestProjectToRun>GCSimulator.csproj</CLRTestProjectToRun> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="GCSimulator.cs" /> <Compile Include="lifetimefx.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <GCStressIncompatible>true</GCStressIncompatible> <CLRTestExecutionArguments>-t 3 -tp 0 -dz 17 -sdz 8500 -dc 10000 -sdc 5000 -lt 2 -f -dp 0.0 -dw 0.0</CLRTestExecutionArguments> <IsGCSimulatorTest>true</IsGCSimulatorTest> <CLRTestProjectToRun>GCSimulator.csproj</CLRTestProjectToRun> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="GCSimulator.cs" /> <Compile Include="lifetimefx.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/baseservices/threading/generics/threadstart/thread26.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; struct Gen<T> { public static void Target() { Interlocked.Increment(ref Test_thread26.Xcounter); } public static void ThreadPoolTest() { Thread[] threads = new Thread[Test_thread26.nThreads]; for (int i = 0; i < Test_thread26.nThreads; i++) { threads[i] = new Thread(new ThreadStart(Gen<T>.Target)); threads[i].Start(); } for (int i = 0; i < Test_thread26.nThreads; i++) { threads[i].Join(); } Test_thread26.Eval(Test_thread26.Xcounter==Test_thread26.nThreads); Test_thread26.Xcounter = 0; } } public class Test_thread26 { 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; struct Gen<T> { public static void Target() { Interlocked.Increment(ref Test_thread26.Xcounter); } public static void ThreadPoolTest() { Thread[] threads = new Thread[Test_thread26.nThreads]; for (int i = 0; i < Test_thread26.nThreads; i++) { threads[i] = new Thread(new ThreadStart(Gen<T>.Target)); threads[i].Start(); } for (int i = 0; i < Test_thread26.nThreads; i++) { threads[i].Join(); } Test_thread26.Eval(Test_thread26.Xcounter==Test_thread26.nThreads); Test_thread26.Xcounter = 0; } } public class Test_thread26 { 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
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Windows.Extensions/src/System/Security/Cryptography/X509Certificates/X509Certificate2UI.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.CompilerServices; using System.Runtime.InteropServices; namespace System.Security.Cryptography.X509Certificates { public enum X509SelectionFlag { SingleSelection = 0x00, MultiSelection = 0x01 } public sealed class X509Certificate2UI { internal const int ERROR_SUCCESS = 0; internal const int ERROR_CANCELLED = 1223; public static void DisplayCertificate(X509Certificate2 certificate) { ArgumentNullException.ThrowIfNull(certificate); DisplayX509Certificate(certificate, IntPtr.Zero); } public static void DisplayCertificate(X509Certificate2 certificate, IntPtr hwndParent) { ArgumentNullException.ThrowIfNull(certificate); DisplayX509Certificate(certificate, hwndParent); } public static X509Certificate2Collection SelectFromCollection(X509Certificate2Collection certificates, string? title, string? message, X509SelectionFlag selectionFlag) { return SelectFromCollectionHelper(certificates, title, message, selectionFlag, IntPtr.Zero); } public static X509Certificate2Collection SelectFromCollection(X509Certificate2Collection certificates, string? title, string? message, X509SelectionFlag selectionFlag, IntPtr hwndParent) { return SelectFromCollectionHelper(certificates, title, message, selectionFlag, hwndParent); } private static unsafe void DisplayX509Certificate(X509Certificate2 certificate, IntPtr hwndParent) { using (SafeCertContextHandle safeCertContext = X509Utils.DuplicateCertificateContext(certificate)) { if (safeCertContext.IsInvalid) throw new CryptographicException(SR.Format(SR.Cryptography_InvalidHandle, nameof(safeCertContext))); int dwErrorCode = ERROR_SUCCESS; // Initialize view structure. Interop.CryptUI.CRYPTUI_VIEWCERTIFICATE_STRUCTW ViewInfo = default; #if NET7_0_OR_GREATER ViewInfo.dwSize = (uint)sizeof(Interop.CryptUI.CRYPTUI_VIEWCERTIFICATE_STRUCTW.Native); #else ViewInfo.dwSize = (uint)Marshal.SizeOf<Interop.CryptUI.CRYPTUI_VIEWCERTIFICATE_STRUCTW>(); #endif ViewInfo.hwndParent = hwndParent; ViewInfo.dwFlags = 0; ViewInfo.szTitle = null; ViewInfo.pCertContext = safeCertContext.DangerousGetHandle(); ViewInfo.rgszPurposes = IntPtr.Zero; ViewInfo.cPurposes = 0; ViewInfo.pCryptProviderData = IntPtr.Zero; ViewInfo.fpCryptProviderDataTrustedUsage = false; ViewInfo.idxSigner = 0; ViewInfo.idxCert = 0; ViewInfo.fCounterSigner = false; ViewInfo.idxCounterSigner = 0; ViewInfo.cStores = 0; ViewInfo.rghStores = IntPtr.Zero; ViewInfo.cPropSheetPages = 0; ViewInfo.rgPropSheetPages = IntPtr.Zero; ViewInfo.nStartPage = 0; // View the certificate if (!Interop.CryptUI.CryptUIDlgViewCertificateW(ViewInfo, IntPtr.Zero)) dwErrorCode = Marshal.GetLastWin32Error(); // CryptUIDlgViewCertificateW returns ERROR_CANCELLED if the user closes // the window through the x button or by pressing CANCEL, so ignore this error code if (dwErrorCode != ERROR_SUCCESS && dwErrorCode != ERROR_CANCELLED) throw new CryptographicException(dwErrorCode); } } private static X509Certificate2Collection SelectFromCollectionHelper(X509Certificate2Collection certificates, string? title, string? message, X509SelectionFlag selectionFlag, IntPtr hwndParent) { ArgumentNullException.ThrowIfNull(certificates); if (selectionFlag < X509SelectionFlag.SingleSelection || selectionFlag > X509SelectionFlag.MultiSelection) throw new ArgumentException(SR.Format(SR.Enum_InvalidValue, nameof(selectionFlag))); using (SafeCertStoreHandle safeSourceStoreHandle = X509Utils.ExportToMemoryStore(certificates)) using (SafeCertStoreHandle safeTargetStoreHandle = SelectFromStore(safeSourceStoreHandle, title, message, selectionFlag, hwndParent)) { return X509Utils.GetCertificates(safeTargetStoreHandle); } } private static unsafe SafeCertStoreHandle SelectFromStore(SafeCertStoreHandle safeSourceStoreHandle, string? title, string? message, X509SelectionFlag selectionFlags, IntPtr hwndParent) { int dwErrorCode = ERROR_SUCCESS; SafeCertStoreHandle safeCertStoreHandle = Interop.Crypt32.CertOpenStore( (IntPtr)Interop.Crypt32.CERT_STORE_PROV_MEMORY, Interop.Crypt32.X509_ASN_ENCODING | Interop.Crypt32.PKCS_7_ASN_ENCODING, IntPtr.Zero, 0, IntPtr.Zero); if (safeCertStoreHandle == null || safeCertStoreHandle.IsInvalid) throw new CryptographicException(Marshal.GetLastWin32Error()); Interop.CryptUI.CRYPTUI_SELECTCERTIFICATE_STRUCTW csc = default; // Older versions of CRYPTUI do not check the size correctly, // so always force it to the oldest version of the structure. #if NET7_0_OR_GREATER // Declare a local for Native to enable us to get the managed byte offset // without having a null check cause a failure. Interop.CryptUI.CRYPTUI_SELECTCERTIFICATE_STRUCTW.Native native; Unsafe.SkipInit(out native); csc.dwSize = (uint)Unsafe.ByteOffset(ref Unsafe.As<Interop.CryptUI.CRYPTUI_SELECTCERTIFICATE_STRUCTW.Native, byte>(ref native), ref Unsafe.As<IntPtr, byte>(ref native.hSelectedCertStore)); #else csc.dwSize = (uint)Marshal.OffsetOf(typeof(Interop.CryptUI.CRYPTUI_SELECTCERTIFICATE_STRUCTW), "hSelectedCertStore"); #endif csc.hwndParent = hwndParent; csc.dwFlags = (uint)selectionFlags; csc.szTitle = title; csc.dwDontUseColumn = 0; csc.szDisplayString = message; csc.pFilterCallback = IntPtr.Zero; csc.pDisplayCallback = IntPtr.Zero; csc.pvCallbackData = IntPtr.Zero; csc.cDisplayStores = 1; IntPtr hSourceCertStore = safeSourceStoreHandle.DangerousGetHandle(); csc.rghDisplayStores = new IntPtr(&hSourceCertStore); csc.cStores = 0; csc.rghStores = IntPtr.Zero; csc.cPropSheetPages = 0; csc.rgPropSheetPages = IntPtr.Zero; csc.hSelectedCertStore = safeCertStoreHandle.DangerousGetHandle(); SafeCertContextHandle safeCertContextHandle = Interop.CryptUI.CryptUIDlgSelectCertificateW(ref csc); if (safeCertContextHandle != null && !safeCertContextHandle.IsInvalid) { // Single select, so add it to our hCertStore SafeCertContextHandle ppStoreContext = SafeCertContextHandle.InvalidHandle; if (!Interop.Crypt32.CertAddCertificateLinkToStore(safeCertStoreHandle, safeCertContextHandle, Interop.Crypt32.CERT_STORE_ADD_ALWAYS, ppStoreContext)) { dwErrorCode = Marshal.GetLastWin32Error(); } } if (dwErrorCode != ERROR_SUCCESS) throw new CryptographicException(dwErrorCode); return safeCertStoreHandle; } } }
// 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.CompilerServices; using System.Runtime.InteropServices; namespace System.Security.Cryptography.X509Certificates { public enum X509SelectionFlag { SingleSelection = 0x00, MultiSelection = 0x01 } public sealed class X509Certificate2UI { internal const int ERROR_SUCCESS = 0; internal const int ERROR_CANCELLED = 1223; public static void DisplayCertificate(X509Certificate2 certificate) { ArgumentNullException.ThrowIfNull(certificate); DisplayX509Certificate(certificate, IntPtr.Zero); } public static void DisplayCertificate(X509Certificate2 certificate, IntPtr hwndParent) { ArgumentNullException.ThrowIfNull(certificate); DisplayX509Certificate(certificate, hwndParent); } public static X509Certificate2Collection SelectFromCollection(X509Certificate2Collection certificates, string? title, string? message, X509SelectionFlag selectionFlag) { return SelectFromCollectionHelper(certificates, title, message, selectionFlag, IntPtr.Zero); } public static X509Certificate2Collection SelectFromCollection(X509Certificate2Collection certificates, string? title, string? message, X509SelectionFlag selectionFlag, IntPtr hwndParent) { return SelectFromCollectionHelper(certificates, title, message, selectionFlag, hwndParent); } private static unsafe void DisplayX509Certificate(X509Certificate2 certificate, IntPtr hwndParent) { using (SafeCertContextHandle safeCertContext = X509Utils.DuplicateCertificateContext(certificate)) { if (safeCertContext.IsInvalid) throw new CryptographicException(SR.Format(SR.Cryptography_InvalidHandle, nameof(safeCertContext))); int dwErrorCode = ERROR_SUCCESS; // Initialize view structure. Interop.CryptUI.CRYPTUI_VIEWCERTIFICATE_STRUCTW ViewInfo = default; #if NET7_0_OR_GREATER ViewInfo.dwSize = (uint)sizeof(Interop.CryptUI.CRYPTUI_VIEWCERTIFICATE_STRUCTW.Native); #else ViewInfo.dwSize = (uint)Marshal.SizeOf<Interop.CryptUI.CRYPTUI_VIEWCERTIFICATE_STRUCTW>(); #endif ViewInfo.hwndParent = hwndParent; ViewInfo.dwFlags = 0; ViewInfo.szTitle = null; ViewInfo.pCertContext = safeCertContext.DangerousGetHandle(); ViewInfo.rgszPurposes = IntPtr.Zero; ViewInfo.cPurposes = 0; ViewInfo.pCryptProviderData = IntPtr.Zero; ViewInfo.fpCryptProviderDataTrustedUsage = false; ViewInfo.idxSigner = 0; ViewInfo.idxCert = 0; ViewInfo.fCounterSigner = false; ViewInfo.idxCounterSigner = 0; ViewInfo.cStores = 0; ViewInfo.rghStores = IntPtr.Zero; ViewInfo.cPropSheetPages = 0; ViewInfo.rgPropSheetPages = IntPtr.Zero; ViewInfo.nStartPage = 0; // View the certificate if (!Interop.CryptUI.CryptUIDlgViewCertificateW(ViewInfo, IntPtr.Zero)) dwErrorCode = Marshal.GetLastWin32Error(); // CryptUIDlgViewCertificateW returns ERROR_CANCELLED if the user closes // the window through the x button or by pressing CANCEL, so ignore this error code if (dwErrorCode != ERROR_SUCCESS && dwErrorCode != ERROR_CANCELLED) throw new CryptographicException(dwErrorCode); } } private static X509Certificate2Collection SelectFromCollectionHelper(X509Certificate2Collection certificates, string? title, string? message, X509SelectionFlag selectionFlag, IntPtr hwndParent) { ArgumentNullException.ThrowIfNull(certificates); if (selectionFlag < X509SelectionFlag.SingleSelection || selectionFlag > X509SelectionFlag.MultiSelection) throw new ArgumentException(SR.Format(SR.Enum_InvalidValue, nameof(selectionFlag))); using (SafeCertStoreHandle safeSourceStoreHandle = X509Utils.ExportToMemoryStore(certificates)) using (SafeCertStoreHandle safeTargetStoreHandle = SelectFromStore(safeSourceStoreHandle, title, message, selectionFlag, hwndParent)) { return X509Utils.GetCertificates(safeTargetStoreHandle); } } private static unsafe SafeCertStoreHandle SelectFromStore(SafeCertStoreHandle safeSourceStoreHandle, string? title, string? message, X509SelectionFlag selectionFlags, IntPtr hwndParent) { int dwErrorCode = ERROR_SUCCESS; SafeCertStoreHandle safeCertStoreHandle = Interop.Crypt32.CertOpenStore( (IntPtr)Interop.Crypt32.CERT_STORE_PROV_MEMORY, Interop.Crypt32.X509_ASN_ENCODING | Interop.Crypt32.PKCS_7_ASN_ENCODING, IntPtr.Zero, 0, IntPtr.Zero); if (safeCertStoreHandle == null || safeCertStoreHandle.IsInvalid) throw new CryptographicException(Marshal.GetLastWin32Error()); Interop.CryptUI.CRYPTUI_SELECTCERTIFICATE_STRUCTW csc = default; // Older versions of CRYPTUI do not check the size correctly, // so always force it to the oldest version of the structure. #if NET7_0_OR_GREATER // Declare a local for Native to enable us to get the managed byte offset // without having a null check cause a failure. Interop.CryptUI.CRYPTUI_SELECTCERTIFICATE_STRUCTW.Native native; Unsafe.SkipInit(out native); csc.dwSize = (uint)Unsafe.ByteOffset(ref Unsafe.As<Interop.CryptUI.CRYPTUI_SELECTCERTIFICATE_STRUCTW.Native, byte>(ref native), ref Unsafe.As<IntPtr, byte>(ref native.hSelectedCertStore)); #else csc.dwSize = (uint)Marshal.OffsetOf(typeof(Interop.CryptUI.CRYPTUI_SELECTCERTIFICATE_STRUCTW), "hSelectedCertStore"); #endif csc.hwndParent = hwndParent; csc.dwFlags = (uint)selectionFlags; csc.szTitle = title; csc.dwDontUseColumn = 0; csc.szDisplayString = message; csc.pFilterCallback = IntPtr.Zero; csc.pDisplayCallback = IntPtr.Zero; csc.pvCallbackData = IntPtr.Zero; csc.cDisplayStores = 1; IntPtr hSourceCertStore = safeSourceStoreHandle.DangerousGetHandle(); csc.rghDisplayStores = new IntPtr(&hSourceCertStore); csc.cStores = 0; csc.rghStores = IntPtr.Zero; csc.cPropSheetPages = 0; csc.rgPropSheetPages = IntPtr.Zero; csc.hSelectedCertStore = safeCertStoreHandle.DangerousGetHandle(); SafeCertContextHandle safeCertContextHandle = Interop.CryptUI.CryptUIDlgSelectCertificateW(ref csc); if (safeCertContextHandle != null && !safeCertContextHandle.IsInvalid) { // Single select, so add it to our hCertStore SafeCertContextHandle ppStoreContext = SafeCertContextHandle.InvalidHandle; if (!Interop.Crypt32.CertAddCertificateLinkToStore(safeCertStoreHandle, safeCertContextHandle, Interop.Crypt32.CERT_STORE_ADD_ALWAYS, ppStoreContext)) { dwErrorCode = Marshal.GetLastWin32Error(); } } if (dwErrorCode != ERROR_SUCCESS) throw new CryptographicException(dwErrorCode); return safeCertStoreHandle; } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/Max.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 Max_Vector128_Single() { var test = new SimpleBinaryOpTest__Max_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 SimpleBinaryOpTest__Max_Vector128_Single { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__Max_Vector128_Single testClass) { var result = AdvSimd.Max(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__Max_Vector128_Single testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = AdvSimd.Max( AdvSimd.LoadVector128((Single*)(pFld1)), AdvSimd.LoadVector128((Single*)(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<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = 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 Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__Max_Vector128_Single() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleBinaryOpTest__Max_Vector128_Single() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } 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 < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Max( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_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.Max( AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Max), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(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.Max), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Max( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Max( AdvSimd.LoadVector128((Single*)(pClsVar1)), AdvSimd.LoadVector128((Single*)(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<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = AdvSimd.Max(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((Single*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Max(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__Max_Vector128_Single(); var result = AdvSimd.Max(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__Max_Vector128_Single(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = AdvSimd.Max( AdvSimd.LoadVector128((Single*)(pFld1)), AdvSimd.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Max(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = AdvSimd.Max( AdvSimd.LoadVector128((Single*)(pFld1)), AdvSimd.LoadVector128((Single*)(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.Max(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.Max( AdvSimd.LoadVector128((Single*)(&test._fld1)), AdvSimd.LoadVector128((Single*)(&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<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (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, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(Helpers.Max(left[i], right[i])) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Max)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.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 Max_Vector128_Single() { var test = new SimpleBinaryOpTest__Max_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 SimpleBinaryOpTest__Max_Vector128_Single { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__Max_Vector128_Single testClass) { var result = AdvSimd.Max(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__Max_Vector128_Single testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = AdvSimd.Max( AdvSimd.LoadVector128((Single*)(pFld1)), AdvSimd.LoadVector128((Single*)(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<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = 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 Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__Max_Vector128_Single() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleBinaryOpTest__Max_Vector128_Single() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } 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 < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Max( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_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.Max( AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Max), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(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.Max), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Max( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Max( AdvSimd.LoadVector128((Single*)(pClsVar1)), AdvSimd.LoadVector128((Single*)(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<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = AdvSimd.Max(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((Single*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Max(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__Max_Vector128_Single(); var result = AdvSimd.Max(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__Max_Vector128_Single(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = AdvSimd.Max( AdvSimd.LoadVector128((Single*)(pFld1)), AdvSimd.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Max(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = AdvSimd.Max( AdvSimd.LoadVector128((Single*)(pFld1)), AdvSimd.LoadVector128((Single*)(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.Max(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.Max( AdvSimd.LoadVector128((Single*)(&test._fld1)), AdvSimd.LoadVector128((Single*)(&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<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (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, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(Helpers.Max(left[i], right[i])) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Max)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/Common/src/Interop/Windows/WinSock/Interop.bind.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 System.Net.Sockets; internal static partial class Interop { internal static partial class Winsock { [LibraryImport(Interop.Libraries.Ws2_32, SetLastError = true)] internal static partial SocketError bind( SafeSocketHandle socketHandle, byte[] socketAddress, int socketAddressSize); } }
// 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 System.Net.Sockets; internal static partial class Interop { internal static partial class Winsock { [LibraryImport(Interop.Libraries.Ws2_32, SetLastError = true)] internal static partial SocketError bind( SafeSocketHandle socketHandle, byte[] socketAddress, int socketAddressSize); } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/Common/src/Interop/Windows/Kernel32/Interop.ExpandEnvironmentStrings.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 Kernel32 { [LibraryImport(Libraries.Kernel32, EntryPoint = "ExpandEnvironmentStringsW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] internal static partial uint ExpandEnvironmentStrings(string lpSrc, ref char lpDst, uint nSize); } }
// 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 Kernel32 { [LibraryImport(Libraries.Kernel32, EntryPoint = "ExpandEnvironmentStringsW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] internal static partial uint ExpandEnvironmentStrings(string lpSrc, ref char lpDst, uint nSize); } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Drawing.Primitives/src/System/Drawing/RectangleF.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.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Numerics; namespace System.Drawing { /// <summary> /// Stores the location and size of a rectangular region. /// </summary> [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public struct RectangleF : IEquatable<RectangleF> { /// <summary> /// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> class. /// </summary> public static readonly RectangleF Empty; private float x; // Do not rename (binary serialization) private float y; // Do not rename (binary serialization) private float width; // Do not rename (binary serialization) private float height; // Do not rename (binary serialization) /// <summary> /// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> class with the specified location /// and size. /// </summary> public RectangleF(float x, float y, float width, float height) { this.x = x; this.y = y; this.width = width; this.height = height; } /// <summary> /// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> class with the specified location /// and size. /// </summary> public RectangleF(PointF location, SizeF size) { x = location.X; y = location.Y; width = size.Width; height = size.Height; } /// <summary> /// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> struct from the specified /// <see cref="System.Numerics.Vector4"/>. /// </summary> public RectangleF(Vector4 vector) { x = vector.X; y = vector.Y; width = vector.Z; height = vector.W; } /// <summary> /// Creates a new <see cref="System.Numerics.Vector4"/> from this <see cref="System.Drawing.RectangleF"/>. /// </summary> public Vector4 ToVector4() => new Vector4(x, y, width, height); /// <summary> /// Converts the specified <see cref="System.Drawing.RectangleF"/> to a <see cref="System.Numerics.Vector4"/>. /// </summary> public static explicit operator Vector4(RectangleF rectangle) => rectangle.ToVector4(); /// <summary> /// Converts the specified <see cref="System.Numerics.Vector2"/> to a <see cref="System.Drawing.RectangleF"/>. /// </summary> public static explicit operator RectangleF(Vector4 vector) => new RectangleF(vector); /// <summary> /// Creates a new <see cref='System.Drawing.RectangleF'/> with the specified location and size. /// </summary> public static RectangleF FromLTRB(float left, float top, float right, float bottom) => new RectangleF(left, top, right - left, bottom - top); /// <summary> /// Gets or sets the coordinates of the upper-left corner of the rectangular region represented by this /// <see cref='System.Drawing.RectangleF'/>. /// </summary> [Browsable(false)] public PointF Location { readonly get => new PointF(X, Y); set { X = value.X; Y = value.Y; } } /// <summary> /// Gets or sets the size of this <see cref='System.Drawing.RectangleF'/>. /// </summary> [Browsable(false)] public SizeF Size { readonly get => new SizeF(Width, Height); set { Width = value.Width; Height = value.Height; } } /// <summary> /// Gets or sets the x-coordinate of the upper-left corner of the rectangular region defined by this /// <see cref='System.Drawing.RectangleF'/>. /// </summary> public float X { readonly get => x; set => x = value; } /// <summary> /// Gets or sets the y-coordinate of the upper-left corner of the rectangular region defined by this /// <see cref='System.Drawing.RectangleF'/>. /// </summary> public float Y { readonly get => y; set => y = value; } /// <summary> /// Gets or sets the width of the rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </summary> public float Width { readonly get => width; set => width = value; } /// <summary> /// Gets or sets the height of the rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </summary> public float Height { readonly get => height; set => height = value; } /// <summary> /// Gets the x-coordinate of the upper-left corner of the rectangular region defined by this /// <see cref='System.Drawing.RectangleF'/> . /// </summary> [Browsable(false)] public readonly float Left => X; /// <summary> /// Gets the y-coordinate of the upper-left corner of the rectangular region defined by this /// <see cref='System.Drawing.RectangleF'/>. /// </summary> [Browsable(false)] public readonly float Top => Y; /// <summary> /// Gets the x-coordinate of the lower-right corner of the rectangular region defined by this /// <see cref='System.Drawing.RectangleF'/>. /// </summary> [Browsable(false)] public readonly float Right => X + Width; /// <summary> /// Gets the y-coordinate of the lower-right corner of the rectangular region defined by this /// <see cref='System.Drawing.RectangleF'/>. /// </summary> [Browsable(false)] public readonly float Bottom => Y + Height; /// <summary> /// Tests whether this <see cref='System.Drawing.RectangleF'/> has a <see cref='System.Drawing.RectangleF.Width'/> or a <see cref='System.Drawing.RectangleF.Height'/> of 0. /// </summary> [Browsable(false)] public readonly bool IsEmpty => (Width <= 0) || (Height <= 0); /// <summary> /// Tests whether <paramref name="obj"/> is a <see cref='System.Drawing.RectangleF'/> with the same location and /// size of this <see cref='System.Drawing.RectangleF'/>. /// </summary> public override readonly bool Equals([NotNullWhen(true)] object? obj) => obj is RectangleF && Equals((RectangleF)obj); public readonly bool Equals(RectangleF other) => this == other; /// <summary> /// Tests whether two <see cref='System.Drawing.RectangleF'/> objects have equal location and size. /// </summary> public static bool operator ==(RectangleF left, RectangleF right) => left.X == right.X && left.Y == right.Y && left.Width == right.Width && left.Height == right.Height; /// <summary> /// Tests whether two <see cref='System.Drawing.RectangleF'/> objects differ in location or size. /// </summary> public static bool operator !=(RectangleF left, RectangleF right) => !(left == right); /// <summary> /// Determines if the specified point is contained within the rectangular region defined by this /// <see cref='System.Drawing.Rectangle'/> . /// </summary> public readonly bool Contains(float x, float y) => X <= x && x < X + Width && Y <= y && y < Y + Height; /// <summary> /// Determines if the specified point is contained within the rectangular region defined by this /// <see cref='System.Drawing.Rectangle'/> . /// </summary> public readonly bool Contains(PointF pt) => Contains(pt.X, pt.Y); /// <summary> /// Determines if the rectangular region represented by <paramref name="rect"/> is entirely contained within /// the rectangular region represented by this <see cref='System.Drawing.Rectangle'/> . /// </summary> public readonly bool Contains(RectangleF rect) => (X <= rect.X) && (rect.X + rect.Width <= X + Width) && (Y <= rect.Y) && (rect.Y + rect.Height <= Y + Height); /// <summary> /// Gets the hash code for this <see cref='System.Drawing.RectangleF'/>. /// </summary> public override readonly int GetHashCode() => HashCode.Combine(X, Y, Width, Height); /// <summary> /// Inflates this <see cref='System.Drawing.Rectangle'/> by the specified amount. /// </summary> public void Inflate(float x, float y) { X -= x; Y -= y; Width += 2 * x; Height += 2 * y; } /// <summary> /// Inflates this <see cref='System.Drawing.Rectangle'/> by the specified amount. /// </summary> public void Inflate(SizeF size) => Inflate(size.Width, size.Height); /// <summary> /// Creates a <see cref='System.Drawing.Rectangle'/> that is inflated by the specified amount. /// </summary> public static RectangleF Inflate(RectangleF rect, float x, float y) { RectangleF r = rect; r.Inflate(x, y); return r; } /// <summary> /// Creates a Rectangle that represents the intersection between this Rectangle and rect. /// </summary> public void Intersect(RectangleF rect) { RectangleF result = Intersect(rect, this); X = result.X; Y = result.Y; Width = result.Width; Height = result.Height; } /// <summary> /// Creates a rectangle that represents the intersection between a and b. If there is no intersection, an /// empty rectangle is returned. /// </summary> public static RectangleF Intersect(RectangleF a, RectangleF b) { float x1 = Math.Max(a.X, b.X); float x2 = Math.Min(a.X + a.Width, b.X + b.Width); float y1 = Math.Max(a.Y, b.Y); float y2 = Math.Min(a.Y + a.Height, b.Y + b.Height); if (x2 >= x1 && y2 >= y1) { return new RectangleF(x1, y1, x2 - x1, y2 - y1); } return Empty; } /// <summary> /// Determines if this rectangle intersects with rect. /// </summary> public readonly bool IntersectsWith(RectangleF rect) => (rect.X < X + Width) && (X < rect.X + rect.Width) && (rect.Y < Y + Height) && (Y < rect.Y + rect.Height); /// <summary> /// Creates a rectangle that represents the union between a and b. /// </summary> public static RectangleF Union(RectangleF a, RectangleF b) { float x1 = Math.Min(a.X, b.X); float x2 = Math.Max(a.X + a.Width, b.X + b.Width); float y1 = Math.Min(a.Y, b.Y); float y2 = Math.Max(a.Y + a.Height, b.Y + b.Height); return new RectangleF(x1, y1, x2 - x1, y2 - y1); } /// <summary> /// Adjusts the location of this rectangle by the specified amount. /// </summary> public void Offset(PointF pos) => Offset(pos.X, pos.Y); /// <summary> /// Adjusts the location of this rectangle by the specified amount. /// </summary> public void Offset(float x, float y) { X += x; Y += y; } /// <summary> /// Converts the specified <see cref='System.Drawing.Rectangle'/> to a /// <see cref='System.Drawing.RectangleF'/>. /// </summary> public static implicit operator RectangleF(Rectangle r) => new RectangleF(r.X, r.Y, r.Width, r.Height); /// <summary> /// Converts the <see cref='System.Drawing.RectangleF.Location'/> and <see cref='System.Drawing.RectangleF.Size'/> /// of this <see cref='System.Drawing.RectangleF'/> to a human-readable string. /// </summary> public override readonly string ToString() => $"{{X={X},Y={Y},Width={Width},Height={Height}}}"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Numerics; namespace System.Drawing { /// <summary> /// Stores the location and size of a rectangular region. /// </summary> [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public struct RectangleF : IEquatable<RectangleF> { /// <summary> /// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> class. /// </summary> public static readonly RectangleF Empty; private float x; // Do not rename (binary serialization) private float y; // Do not rename (binary serialization) private float width; // Do not rename (binary serialization) private float height; // Do not rename (binary serialization) /// <summary> /// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> class with the specified location /// and size. /// </summary> public RectangleF(float x, float y, float width, float height) { this.x = x; this.y = y; this.width = width; this.height = height; } /// <summary> /// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> class with the specified location /// and size. /// </summary> public RectangleF(PointF location, SizeF size) { x = location.X; y = location.Y; width = size.Width; height = size.Height; } /// <summary> /// Initializes a new instance of the <see cref='System.Drawing.RectangleF'/> struct from the specified /// <see cref="System.Numerics.Vector4"/>. /// </summary> public RectangleF(Vector4 vector) { x = vector.X; y = vector.Y; width = vector.Z; height = vector.W; } /// <summary> /// Creates a new <see cref="System.Numerics.Vector4"/> from this <see cref="System.Drawing.RectangleF"/>. /// </summary> public Vector4 ToVector4() => new Vector4(x, y, width, height); /// <summary> /// Converts the specified <see cref="System.Drawing.RectangleF"/> to a <see cref="System.Numerics.Vector4"/>. /// </summary> public static explicit operator Vector4(RectangleF rectangle) => rectangle.ToVector4(); /// <summary> /// Converts the specified <see cref="System.Numerics.Vector2"/> to a <see cref="System.Drawing.RectangleF"/>. /// </summary> public static explicit operator RectangleF(Vector4 vector) => new RectangleF(vector); /// <summary> /// Creates a new <see cref='System.Drawing.RectangleF'/> with the specified location and size. /// </summary> public static RectangleF FromLTRB(float left, float top, float right, float bottom) => new RectangleF(left, top, right - left, bottom - top); /// <summary> /// Gets or sets the coordinates of the upper-left corner of the rectangular region represented by this /// <see cref='System.Drawing.RectangleF'/>. /// </summary> [Browsable(false)] public PointF Location { readonly get => new PointF(X, Y); set { X = value.X; Y = value.Y; } } /// <summary> /// Gets or sets the size of this <see cref='System.Drawing.RectangleF'/>. /// </summary> [Browsable(false)] public SizeF Size { readonly get => new SizeF(Width, Height); set { Width = value.Width; Height = value.Height; } } /// <summary> /// Gets or sets the x-coordinate of the upper-left corner of the rectangular region defined by this /// <see cref='System.Drawing.RectangleF'/>. /// </summary> public float X { readonly get => x; set => x = value; } /// <summary> /// Gets or sets the y-coordinate of the upper-left corner of the rectangular region defined by this /// <see cref='System.Drawing.RectangleF'/>. /// </summary> public float Y { readonly get => y; set => y = value; } /// <summary> /// Gets or sets the width of the rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </summary> public float Width { readonly get => width; set => width = value; } /// <summary> /// Gets or sets the height of the rectangular region defined by this <see cref='System.Drawing.RectangleF'/>. /// </summary> public float Height { readonly get => height; set => height = value; } /// <summary> /// Gets the x-coordinate of the upper-left corner of the rectangular region defined by this /// <see cref='System.Drawing.RectangleF'/> . /// </summary> [Browsable(false)] public readonly float Left => X; /// <summary> /// Gets the y-coordinate of the upper-left corner of the rectangular region defined by this /// <see cref='System.Drawing.RectangleF'/>. /// </summary> [Browsable(false)] public readonly float Top => Y; /// <summary> /// Gets the x-coordinate of the lower-right corner of the rectangular region defined by this /// <see cref='System.Drawing.RectangleF'/>. /// </summary> [Browsable(false)] public readonly float Right => X + Width; /// <summary> /// Gets the y-coordinate of the lower-right corner of the rectangular region defined by this /// <see cref='System.Drawing.RectangleF'/>. /// </summary> [Browsable(false)] public readonly float Bottom => Y + Height; /// <summary> /// Tests whether this <see cref='System.Drawing.RectangleF'/> has a <see cref='System.Drawing.RectangleF.Width'/> or a <see cref='System.Drawing.RectangleF.Height'/> of 0. /// </summary> [Browsable(false)] public readonly bool IsEmpty => (Width <= 0) || (Height <= 0); /// <summary> /// Tests whether <paramref name="obj"/> is a <see cref='System.Drawing.RectangleF'/> with the same location and /// size of this <see cref='System.Drawing.RectangleF'/>. /// </summary> public override readonly bool Equals([NotNullWhen(true)] object? obj) => obj is RectangleF && Equals((RectangleF)obj); public readonly bool Equals(RectangleF other) => this == other; /// <summary> /// Tests whether two <see cref='System.Drawing.RectangleF'/> objects have equal location and size. /// </summary> public static bool operator ==(RectangleF left, RectangleF right) => left.X == right.X && left.Y == right.Y && left.Width == right.Width && left.Height == right.Height; /// <summary> /// Tests whether two <see cref='System.Drawing.RectangleF'/> objects differ in location or size. /// </summary> public static bool operator !=(RectangleF left, RectangleF right) => !(left == right); /// <summary> /// Determines if the specified point is contained within the rectangular region defined by this /// <see cref='System.Drawing.Rectangle'/> . /// </summary> public readonly bool Contains(float x, float y) => X <= x && x < X + Width && Y <= y && y < Y + Height; /// <summary> /// Determines if the specified point is contained within the rectangular region defined by this /// <see cref='System.Drawing.Rectangle'/> . /// </summary> public readonly bool Contains(PointF pt) => Contains(pt.X, pt.Y); /// <summary> /// Determines if the rectangular region represented by <paramref name="rect"/> is entirely contained within /// the rectangular region represented by this <see cref='System.Drawing.Rectangle'/> . /// </summary> public readonly bool Contains(RectangleF rect) => (X <= rect.X) && (rect.X + rect.Width <= X + Width) && (Y <= rect.Y) && (rect.Y + rect.Height <= Y + Height); /// <summary> /// Gets the hash code for this <see cref='System.Drawing.RectangleF'/>. /// </summary> public override readonly int GetHashCode() => HashCode.Combine(X, Y, Width, Height); /// <summary> /// Inflates this <see cref='System.Drawing.Rectangle'/> by the specified amount. /// </summary> public void Inflate(float x, float y) { X -= x; Y -= y; Width += 2 * x; Height += 2 * y; } /// <summary> /// Inflates this <see cref='System.Drawing.Rectangle'/> by the specified amount. /// </summary> public void Inflate(SizeF size) => Inflate(size.Width, size.Height); /// <summary> /// Creates a <see cref='System.Drawing.Rectangle'/> that is inflated by the specified amount. /// </summary> public static RectangleF Inflate(RectangleF rect, float x, float y) { RectangleF r = rect; r.Inflate(x, y); return r; } /// <summary> /// Creates a Rectangle that represents the intersection between this Rectangle and rect. /// </summary> public void Intersect(RectangleF rect) { RectangleF result = Intersect(rect, this); X = result.X; Y = result.Y; Width = result.Width; Height = result.Height; } /// <summary> /// Creates a rectangle that represents the intersection between a and b. If there is no intersection, an /// empty rectangle is returned. /// </summary> public static RectangleF Intersect(RectangleF a, RectangleF b) { float x1 = Math.Max(a.X, b.X); float x2 = Math.Min(a.X + a.Width, b.X + b.Width); float y1 = Math.Max(a.Y, b.Y); float y2 = Math.Min(a.Y + a.Height, b.Y + b.Height); if (x2 >= x1 && y2 >= y1) { return new RectangleF(x1, y1, x2 - x1, y2 - y1); } return Empty; } /// <summary> /// Determines if this rectangle intersects with rect. /// </summary> public readonly bool IntersectsWith(RectangleF rect) => (rect.X < X + Width) && (X < rect.X + rect.Width) && (rect.Y < Y + Height) && (Y < rect.Y + rect.Height); /// <summary> /// Creates a rectangle that represents the union between a and b. /// </summary> public static RectangleF Union(RectangleF a, RectangleF b) { float x1 = Math.Min(a.X, b.X); float x2 = Math.Max(a.X + a.Width, b.X + b.Width); float y1 = Math.Min(a.Y, b.Y); float y2 = Math.Max(a.Y + a.Height, b.Y + b.Height); return new RectangleF(x1, y1, x2 - x1, y2 - y1); } /// <summary> /// Adjusts the location of this rectangle by the specified amount. /// </summary> public void Offset(PointF pos) => Offset(pos.X, pos.Y); /// <summary> /// Adjusts the location of this rectangle by the specified amount. /// </summary> public void Offset(float x, float y) { X += x; Y += y; } /// <summary> /// Converts the specified <see cref='System.Drawing.Rectangle'/> to a /// <see cref='System.Drawing.RectangleF'/>. /// </summary> public static implicit operator RectangleF(Rectangle r) => new RectangleF(r.X, r.Y, r.Width, r.Height); /// <summary> /// Converts the <see cref='System.Drawing.RectangleF.Location'/> and <see cref='System.Drawing.RectangleF.Size'/> /// of this <see cref='System.Drawing.RectangleF'/> to a human-readable string. /// </summary> public override readonly string ToString() => $"{{X={X},Y={Y},Width={Width},Height={Height}}}"; } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Reflection.Metadata/tests/Metadata/Ecma335/Encoding/ExceptionRegionEncoderTests.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.Metadata.Tests; using Xunit; namespace System.Reflection.Metadata.Ecma335.Tests { public class ExceptionRegionEncoderTests { [Fact] public void IsSmallRegionCount() { Assert.True(ExceptionRegionEncoder.IsSmallRegionCount(0)); Assert.True(ExceptionRegionEncoder.IsSmallRegionCount(20)); Assert.False(ExceptionRegionEncoder.IsSmallRegionCount(-1)); Assert.False(ExceptionRegionEncoder.IsSmallRegionCount(21)); Assert.False(ExceptionRegionEncoder.IsSmallRegionCount(int.MinValue)); Assert.False(ExceptionRegionEncoder.IsSmallRegionCount(int.MaxValue)); } [Fact] public void IsSmallExceptionRegion() { Assert.True(ExceptionRegionEncoder.IsSmallExceptionRegion(0, 0)); Assert.True(ExceptionRegionEncoder.IsSmallExceptionRegion(ushort.MaxValue, byte.MaxValue)); Assert.False(ExceptionRegionEncoder.IsSmallExceptionRegion(ushort.MaxValue + 1, byte.MaxValue)); Assert.False(ExceptionRegionEncoder.IsSmallExceptionRegion(ushort.MaxValue, byte.MaxValue + 1)); Assert.False(ExceptionRegionEncoder.IsSmallExceptionRegion(-1, 0)); Assert.False(ExceptionRegionEncoder.IsSmallExceptionRegion(0, -1)); Assert.False(ExceptionRegionEncoder.IsSmallExceptionRegion(int.MinValue, int.MinValue)); Assert.False(ExceptionRegionEncoder.IsSmallExceptionRegion(int.MaxValue, int.MaxValue)); Assert.False(ExceptionRegionEncoder.IsSmallExceptionRegion(int.MaxValue, int.MinValue)); Assert.False(ExceptionRegionEncoder.IsSmallExceptionRegion(int.MinValue, int.MaxValue)); } [Fact] public void SerializeTableHeader() { var builder = new BlobBuilder(); builder.WriteByte(0xff); ExceptionRegionEncoder.SerializeTableHeader(builder, ExceptionRegionEncoder.MaxSmallExceptionRegions, hasSmallRegions: true); AssertEx.Equal(new byte[] { 0xff, 0x00, 0x00, 0x00, // padding 0x01, // flags 0xf4, // size 0x00, 0x00 }, builder.ToArray()); builder.Clear(); builder.WriteByte(0xff); ExceptionRegionEncoder.SerializeTableHeader(builder, ExceptionRegionEncoder.MaxExceptionRegions, hasSmallRegions: false); AssertEx.Equal(new byte[] { 0xff, 0x00, 0x00, 0x00, // padding 0x41, // flags 0xf4, 0xff, 0xff, // size }, builder.ToArray()); } [Fact] public void Add_Small() { var builder = new BlobBuilder(); var encoder = new ExceptionRegionEncoder(builder, hasSmallFormat: true); encoder.Add(ExceptionRegionKind.Catch, 1, 2, 4, 5, catchType: MetadataTokens.TypeDefinitionHandle(1)); AssertEx.Equal(new byte[] { 0x00, 0x00, // kind 0x01, 0x00, // try offset 0x02, // try length 0x04, 0x00, // handler offset 0x05, // handler length 0x01, 0x00, 0x00, 0x02 // catch type }, builder.ToArray()); builder.Clear(); encoder.Add(ExceptionRegionKind.Filter, 0xffff, 0xff, 0xffff, 0xff, filterOffset: int.MaxValue); AssertEx.Equal(new byte[] { 0x01, 0x00, // kind 0xff, 0xff, // try offset 0xff, // try length 0xff, 0xff, // handler offset 0xff, // handler length 0xff, 0xff, 0xff, 0x7f // filter offset }, builder.ToArray()); builder.Clear(); encoder.Add(ExceptionRegionKind.Fault, 0xffff, 0xff, 0xffff, 0xff); AssertEx.Equal(new byte[] { 0x04, 0x00, // kind 0xff, 0xff, // try offset 0xff, // try length 0xff, 0xff, // handler offset 0xff, // handler length 0x00, 0x00, 0x00, 0x00 }, builder.ToArray()); builder.Clear(); encoder.Add(ExceptionRegionKind.Finally, 0, 0, 0, 0); AssertEx.Equal(new byte[] { 0x02, 0x00, // kind 0x00, 0x00, // try offset 0x00, // try length 0x00, 0x00, // handler offset 0x00, // handler length 0x00, 0x00, 0x00, 0x00 }, builder.ToArray()); builder.Clear(); } [Fact] public void Add_Large() { var builder = new BlobBuilder(); var encoder = new ExceptionRegionEncoder(builder, hasSmallFormat: false); encoder.Add(ExceptionRegionKind.Catch, 1, 2, 4, 5, catchType: MetadataTokens.TypeDefinitionHandle(1)); AssertEx.Equal(new byte[] { 0x00, 0x00, 0x00, 0x00, // kind 0x01, 0x00, 0x00, 0x00, // try offset 0x02, 0x00, 0x00, 0x00, // try length 0x04, 0x00, 0x00, 0x00, // handler offset 0x05, 0x00, 0x00, 0x00, // handler length 0x01, 0x00, 0x00, 0x02 // catch type }, builder.ToArray()); builder.Clear(); encoder.Add(ExceptionRegionKind.Filter, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, filterOffset: int.MaxValue); AssertEx.Equal(new byte[] { 0x01, 0x00, 0x00, 0x00, // kind 0xff, 0xff, 0xff, 0x7f, // try offset 0xff, 0xff, 0xff, 0x7f, // try length 0xff, 0xff, 0xff, 0x7f, // handler offset 0xff, 0xff, 0xff, 0x7f, // handler length 0xff, 0xff, 0xff, 0x7f // filter offset }, builder.ToArray()); builder.Clear(); encoder.Add(ExceptionRegionKind.Fault, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue); AssertEx.Equal(new byte[] { 0x04, 0x00, 0x00, 0x00, // kind 0xff, 0xff, 0xff, 0x7f, // try offset 0xff, 0xff, 0xff, 0x7f, // try length 0xff, 0xff, 0xff, 0x7f, // handler offset 0xff, 0xff, 0xff, 0x7f, // handler length 0x00, 0x00, 0x00, 0x00 }, builder.ToArray()); builder.Clear(); encoder.Add(ExceptionRegionKind.Finally, 0, 0, 0, 0); AssertEx.Equal(new byte[] { 0x02, 0x00, 0x00, 0x00, // kind 0x00, 0x00, 0x00, 0x00, // try offset 0x00, 0x00, 0x00, 0x00, // try length 0x00, 0x00, 0x00, 0x00, // handler offset 0x00, 0x00, 0x00, 0x00, // handler length 0x00, 0x00, 0x00, 0x00 }, builder.ToArray()); builder.Clear(); } [Fact] public void Add_Errors() { Assert.Throws<InvalidOperationException>(() => default(ExceptionRegionEncoder).Add(ExceptionRegionKind.Fault, 0, 0, 0, 0)); var builder = new BlobBuilder(); var smallEncoder = new ExceptionRegionEncoder(builder, hasSmallFormat: true); var fatEncoder = new ExceptionRegionEncoder(builder, hasSmallFormat: false); Assert.Throws<ArgumentOutOfRangeException>(() => smallEncoder.Add(ExceptionRegionKind.Finally, -1, 2, 4, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => smallEncoder.Add(ExceptionRegionKind.Finally, 1, -1, 4, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => smallEncoder.Add(ExceptionRegionKind.Finally, 1, 2, -1, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => smallEncoder.Add(ExceptionRegionKind.Finally, 1, 2, 4, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => smallEncoder.Add(ExceptionRegionKind.Finally, 0x10000, 2, 4, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => smallEncoder.Add(ExceptionRegionKind.Finally, 1, 0x100, 4, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => smallEncoder.Add(ExceptionRegionKind.Finally, 1, 2, 0x10000, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => smallEncoder.Add(ExceptionRegionKind.Finally, 1, 2, 4, 0x100)); Assert.Throws<ArgumentOutOfRangeException>(() => fatEncoder.Add(ExceptionRegionKind.Finally, -1, 2, 4, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => fatEncoder.Add(ExceptionRegionKind.Finally, 1, -1, 4, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => fatEncoder.Add(ExceptionRegionKind.Finally, 1, 2, -1, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => fatEncoder.Add(ExceptionRegionKind.Finally, 1, 2, 4, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => fatEncoder.Add((ExceptionRegionKind)5, 1, 2, 4, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => fatEncoder.Add(ExceptionRegionKind.Filter, 1, 2, 4, 5, filterOffset: -1)); AssertExtensions.Throws<ArgumentException>("catchType", () => fatEncoder.Add(ExceptionRegionKind.Catch, 1, 2, 4, 5, catchType: default(EntityHandle))); AssertExtensions.Throws<ArgumentException>("catchType", () => fatEncoder.Add(ExceptionRegionKind.Catch, 1, 2, 4, 5, catchType: MetadataTokens.ImportScopeHandle(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.Reflection.Metadata.Tests; using Xunit; namespace System.Reflection.Metadata.Ecma335.Tests { public class ExceptionRegionEncoderTests { [Fact] public void IsSmallRegionCount() { Assert.True(ExceptionRegionEncoder.IsSmallRegionCount(0)); Assert.True(ExceptionRegionEncoder.IsSmallRegionCount(20)); Assert.False(ExceptionRegionEncoder.IsSmallRegionCount(-1)); Assert.False(ExceptionRegionEncoder.IsSmallRegionCount(21)); Assert.False(ExceptionRegionEncoder.IsSmallRegionCount(int.MinValue)); Assert.False(ExceptionRegionEncoder.IsSmallRegionCount(int.MaxValue)); } [Fact] public void IsSmallExceptionRegion() { Assert.True(ExceptionRegionEncoder.IsSmallExceptionRegion(0, 0)); Assert.True(ExceptionRegionEncoder.IsSmallExceptionRegion(ushort.MaxValue, byte.MaxValue)); Assert.False(ExceptionRegionEncoder.IsSmallExceptionRegion(ushort.MaxValue + 1, byte.MaxValue)); Assert.False(ExceptionRegionEncoder.IsSmallExceptionRegion(ushort.MaxValue, byte.MaxValue + 1)); Assert.False(ExceptionRegionEncoder.IsSmallExceptionRegion(-1, 0)); Assert.False(ExceptionRegionEncoder.IsSmallExceptionRegion(0, -1)); Assert.False(ExceptionRegionEncoder.IsSmallExceptionRegion(int.MinValue, int.MinValue)); Assert.False(ExceptionRegionEncoder.IsSmallExceptionRegion(int.MaxValue, int.MaxValue)); Assert.False(ExceptionRegionEncoder.IsSmallExceptionRegion(int.MaxValue, int.MinValue)); Assert.False(ExceptionRegionEncoder.IsSmallExceptionRegion(int.MinValue, int.MaxValue)); } [Fact] public void SerializeTableHeader() { var builder = new BlobBuilder(); builder.WriteByte(0xff); ExceptionRegionEncoder.SerializeTableHeader(builder, ExceptionRegionEncoder.MaxSmallExceptionRegions, hasSmallRegions: true); AssertEx.Equal(new byte[] { 0xff, 0x00, 0x00, 0x00, // padding 0x01, // flags 0xf4, // size 0x00, 0x00 }, builder.ToArray()); builder.Clear(); builder.WriteByte(0xff); ExceptionRegionEncoder.SerializeTableHeader(builder, ExceptionRegionEncoder.MaxExceptionRegions, hasSmallRegions: false); AssertEx.Equal(new byte[] { 0xff, 0x00, 0x00, 0x00, // padding 0x41, // flags 0xf4, 0xff, 0xff, // size }, builder.ToArray()); } [Fact] public void Add_Small() { var builder = new BlobBuilder(); var encoder = new ExceptionRegionEncoder(builder, hasSmallFormat: true); encoder.Add(ExceptionRegionKind.Catch, 1, 2, 4, 5, catchType: MetadataTokens.TypeDefinitionHandle(1)); AssertEx.Equal(new byte[] { 0x00, 0x00, // kind 0x01, 0x00, // try offset 0x02, // try length 0x04, 0x00, // handler offset 0x05, // handler length 0x01, 0x00, 0x00, 0x02 // catch type }, builder.ToArray()); builder.Clear(); encoder.Add(ExceptionRegionKind.Filter, 0xffff, 0xff, 0xffff, 0xff, filterOffset: int.MaxValue); AssertEx.Equal(new byte[] { 0x01, 0x00, // kind 0xff, 0xff, // try offset 0xff, // try length 0xff, 0xff, // handler offset 0xff, // handler length 0xff, 0xff, 0xff, 0x7f // filter offset }, builder.ToArray()); builder.Clear(); encoder.Add(ExceptionRegionKind.Fault, 0xffff, 0xff, 0xffff, 0xff); AssertEx.Equal(new byte[] { 0x04, 0x00, // kind 0xff, 0xff, // try offset 0xff, // try length 0xff, 0xff, // handler offset 0xff, // handler length 0x00, 0x00, 0x00, 0x00 }, builder.ToArray()); builder.Clear(); encoder.Add(ExceptionRegionKind.Finally, 0, 0, 0, 0); AssertEx.Equal(new byte[] { 0x02, 0x00, // kind 0x00, 0x00, // try offset 0x00, // try length 0x00, 0x00, // handler offset 0x00, // handler length 0x00, 0x00, 0x00, 0x00 }, builder.ToArray()); builder.Clear(); } [Fact] public void Add_Large() { var builder = new BlobBuilder(); var encoder = new ExceptionRegionEncoder(builder, hasSmallFormat: false); encoder.Add(ExceptionRegionKind.Catch, 1, 2, 4, 5, catchType: MetadataTokens.TypeDefinitionHandle(1)); AssertEx.Equal(new byte[] { 0x00, 0x00, 0x00, 0x00, // kind 0x01, 0x00, 0x00, 0x00, // try offset 0x02, 0x00, 0x00, 0x00, // try length 0x04, 0x00, 0x00, 0x00, // handler offset 0x05, 0x00, 0x00, 0x00, // handler length 0x01, 0x00, 0x00, 0x02 // catch type }, builder.ToArray()); builder.Clear(); encoder.Add(ExceptionRegionKind.Filter, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, filterOffset: int.MaxValue); AssertEx.Equal(new byte[] { 0x01, 0x00, 0x00, 0x00, // kind 0xff, 0xff, 0xff, 0x7f, // try offset 0xff, 0xff, 0xff, 0x7f, // try length 0xff, 0xff, 0xff, 0x7f, // handler offset 0xff, 0xff, 0xff, 0x7f, // handler length 0xff, 0xff, 0xff, 0x7f // filter offset }, builder.ToArray()); builder.Clear(); encoder.Add(ExceptionRegionKind.Fault, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue); AssertEx.Equal(new byte[] { 0x04, 0x00, 0x00, 0x00, // kind 0xff, 0xff, 0xff, 0x7f, // try offset 0xff, 0xff, 0xff, 0x7f, // try length 0xff, 0xff, 0xff, 0x7f, // handler offset 0xff, 0xff, 0xff, 0x7f, // handler length 0x00, 0x00, 0x00, 0x00 }, builder.ToArray()); builder.Clear(); encoder.Add(ExceptionRegionKind.Finally, 0, 0, 0, 0); AssertEx.Equal(new byte[] { 0x02, 0x00, 0x00, 0x00, // kind 0x00, 0x00, 0x00, 0x00, // try offset 0x00, 0x00, 0x00, 0x00, // try length 0x00, 0x00, 0x00, 0x00, // handler offset 0x00, 0x00, 0x00, 0x00, // handler length 0x00, 0x00, 0x00, 0x00 }, builder.ToArray()); builder.Clear(); } [Fact] public void Add_Errors() { Assert.Throws<InvalidOperationException>(() => default(ExceptionRegionEncoder).Add(ExceptionRegionKind.Fault, 0, 0, 0, 0)); var builder = new BlobBuilder(); var smallEncoder = new ExceptionRegionEncoder(builder, hasSmallFormat: true); var fatEncoder = new ExceptionRegionEncoder(builder, hasSmallFormat: false); Assert.Throws<ArgumentOutOfRangeException>(() => smallEncoder.Add(ExceptionRegionKind.Finally, -1, 2, 4, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => smallEncoder.Add(ExceptionRegionKind.Finally, 1, -1, 4, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => smallEncoder.Add(ExceptionRegionKind.Finally, 1, 2, -1, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => smallEncoder.Add(ExceptionRegionKind.Finally, 1, 2, 4, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => smallEncoder.Add(ExceptionRegionKind.Finally, 0x10000, 2, 4, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => smallEncoder.Add(ExceptionRegionKind.Finally, 1, 0x100, 4, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => smallEncoder.Add(ExceptionRegionKind.Finally, 1, 2, 0x10000, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => smallEncoder.Add(ExceptionRegionKind.Finally, 1, 2, 4, 0x100)); Assert.Throws<ArgumentOutOfRangeException>(() => fatEncoder.Add(ExceptionRegionKind.Finally, -1, 2, 4, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => fatEncoder.Add(ExceptionRegionKind.Finally, 1, -1, 4, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => fatEncoder.Add(ExceptionRegionKind.Finally, 1, 2, -1, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => fatEncoder.Add(ExceptionRegionKind.Finally, 1, 2, 4, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => fatEncoder.Add((ExceptionRegionKind)5, 1, 2, 4, 5)); Assert.Throws<ArgumentOutOfRangeException>(() => fatEncoder.Add(ExceptionRegionKind.Filter, 1, 2, 4, 5, filterOffset: -1)); AssertExtensions.Throws<ArgumentException>("catchType", () => fatEncoder.Add(ExceptionRegionKind.Catch, 1, 2, 4, 5, catchType: default(EntityHandle))); AssertExtensions.Throws<ArgumentException>("catchType", () => fatEncoder.Add(ExceptionRegionKind.Catch, 1, 2, 4, 5, catchType: MetadataTokens.ImportScopeHandle(1))); } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis/System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <RootNamespace>System.Runtime.Loader.Tests</RootNamespace> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <TestRuntime>true</TestRuntime> <DeltaScript>deltascript.json</DeltaScript> </PropertyGroup> <ItemGroup> <Compile Include="AddLambdaCapturingThis.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <RootNamespace>System.Runtime.Loader.Tests</RootNamespace> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <TestRuntime>true</TestRuntime> <DeltaScript>deltascript.json</DeltaScript> </PropertyGroup> <ItemGroup> <Compile Include="AddLambdaCapturingThis.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/HardwareIntrinsics/General/Vector256/Divide.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\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 DivideInt16() { var test = new VectorBinaryOpTest__DivideInt16(); // 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__DivideInt16 { 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 != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<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 Vector256<Int16> _fld1; public Vector256<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<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = Math.Max((short)(1), TestLibrary.Generator.GetInt16()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__DivideInt16 testClass) { var result = Vector256.Divide(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector256<Int16> _clsVar1; private static Vector256<Int16> _clsVar2; private Vector256<Int16> _fld1; private Vector256<Int16> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__DivideInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = Math.Max((short)(1), TestLibrary.Generator.GetInt16()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); } public VectorBinaryOpTest__DivideInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = Math.Max((short)(1), TestLibrary.Generator.GetInt16()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = Math.Max((short)(1), TestLibrary.Generator.GetInt16()); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.Divide( Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<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 method = typeof(Vector256).GetMethod(nameof(Vector256.Divide), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.Divide), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.Divide( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr); var result = Vector256.Divide(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__DivideInt16(); var result = Vector256.Divide(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.Divide(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.Divide(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Int16> op1, Vector256<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<Vector256<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<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (short)(left[0] / right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (short)(left[i] / right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.Divide)}<Int16>(Vector256<Int16>, Vector256<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\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 DivideInt16() { var test = new VectorBinaryOpTest__DivideInt16(); // 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__DivideInt16 { 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 != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<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 Vector256<Int16> _fld1; public Vector256<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<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = Math.Max((short)(1), TestLibrary.Generator.GetInt16()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__DivideInt16 testClass) { var result = Vector256.Divide(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector256<Int16> _clsVar1; private static Vector256<Int16> _clsVar2; private Vector256<Int16> _fld1; private Vector256<Int16> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__DivideInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = Math.Max((short)(1), TestLibrary.Generator.GetInt16()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); } public VectorBinaryOpTest__DivideInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = Math.Max((short)(1), TestLibrary.Generator.GetInt16()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = Math.Max((short)(1), TestLibrary.Generator.GetInt16()); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.Divide( Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<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 method = typeof(Vector256).GetMethod(nameof(Vector256.Divide), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.Divide), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.Divide( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr); var result = Vector256.Divide(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__DivideInt16(); var result = Vector256.Divide(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.Divide(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.Divide(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Int16> op1, Vector256<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<Vector256<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<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (short)(left[0] / right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (short)(left[i] / right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.Divide)}<Int16>(Vector256<Int16>, Vector256<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
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/Program.AdvSimd.Arm64_Part0.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 JIT.HardwareIntrinsics.Arm { public static partial class Program { static Program() { TestList = new Dictionary<string, Action>() { ["Abs.Vector128.Double"] = Abs_Vector128_Double, ["Abs.Vector128.Int64"] = Abs_Vector128_Int64, ["AbsSaturate.Vector128.Int64"] = AbsSaturate_Vector128_Int64, ["AbsSaturateScalar.Vector64.Int16"] = AbsSaturateScalar_Vector64_Int16, ["AbsSaturateScalar.Vector64.Int32"] = AbsSaturateScalar_Vector64_Int32, ["AbsSaturateScalar.Vector64.Int64"] = AbsSaturateScalar_Vector64_Int64, ["AbsSaturateScalar.Vector64.SByte"] = AbsSaturateScalar_Vector64_SByte, ["AbsScalar.Vector64.Int64"] = AbsScalar_Vector64_Int64, ["AbsoluteCompareGreaterThan.Vector128.Double"] = AbsoluteCompareGreaterThan_Vector128_Double, ["AbsoluteCompareGreaterThanScalar.Vector64.Double"] = AbsoluteCompareGreaterThanScalar_Vector64_Double, ["AbsoluteCompareGreaterThanScalar.Vector64.Single"] = AbsoluteCompareGreaterThanScalar_Vector64_Single, ["AbsoluteCompareGreaterThanOrEqual.Vector128.Double"] = AbsoluteCompareGreaterThanOrEqual_Vector128_Double, ["AbsoluteCompareGreaterThanOrEqualScalar.Vector64.Double"] = AbsoluteCompareGreaterThanOrEqualScalar_Vector64_Double, ["AbsoluteCompareGreaterThanOrEqualScalar.Vector64.Single"] = AbsoluteCompareGreaterThanOrEqualScalar_Vector64_Single, ["AbsoluteCompareLessThan.Vector128.Double"] = AbsoluteCompareLessThan_Vector128_Double, ["AbsoluteCompareLessThanScalar.Vector64.Double"] = AbsoluteCompareLessThanScalar_Vector64_Double, ["AbsoluteCompareLessThanScalar.Vector64.Single"] = AbsoluteCompareLessThanScalar_Vector64_Single, ["AbsoluteCompareLessThanOrEqual.Vector128.Double"] = AbsoluteCompareLessThanOrEqual_Vector128_Double, ["AbsoluteCompareLessThanOrEqualScalar.Vector64.Double"] = AbsoluteCompareLessThanOrEqualScalar_Vector64_Double, ["AbsoluteCompareLessThanOrEqualScalar.Vector64.Single"] = AbsoluteCompareLessThanOrEqualScalar_Vector64_Single, ["AbsoluteDifference.Vector128.Double"] = AbsoluteDifference_Vector128_Double, ["AbsoluteDifferenceScalar.Vector64.Double"] = AbsoluteDifferenceScalar_Vector64_Double, ["AbsoluteDifferenceScalar.Vector64.Single"] = AbsoluteDifferenceScalar_Vector64_Single, ["Add.Vector128.Double"] = Add_Vector128_Double, ["AddAcross.Vector64.Byte"] = AddAcross_Vector64_Byte, ["AddAcross.Vector64.Int16"] = AddAcross_Vector64_Int16, ["AddAcross.Vector64.SByte"] = AddAcross_Vector64_SByte, ["AddAcross.Vector64.UInt16"] = AddAcross_Vector64_UInt16, ["AddAcross.Vector128.Byte"] = AddAcross_Vector128_Byte, ["AddAcross.Vector128.Int16"] = AddAcross_Vector128_Int16, ["AddAcross.Vector128.Int32"] = AddAcross_Vector128_Int32, ["AddAcross.Vector128.SByte"] = AddAcross_Vector128_SByte, ["AddAcross.Vector128.UInt16"] = AddAcross_Vector128_UInt16, ["AddAcross.Vector128.UInt32"] = AddAcross_Vector128_UInt32, ["AddAcrossWidening.Vector64.Byte"] = AddAcrossWidening_Vector64_Byte, ["AddAcrossWidening.Vector64.Int16"] = AddAcrossWidening_Vector64_Int16, ["AddAcrossWidening.Vector64.SByte"] = AddAcrossWidening_Vector64_SByte, ["AddAcrossWidening.Vector64.UInt16"] = AddAcrossWidening_Vector64_UInt16, ["AddAcrossWidening.Vector128.Byte"] = AddAcrossWidening_Vector128_Byte, ["AddAcrossWidening.Vector128.Int16"] = AddAcrossWidening_Vector128_Int16, ["AddAcrossWidening.Vector128.Int32"] = AddAcrossWidening_Vector128_Int32, ["AddAcrossWidening.Vector128.SByte"] = AddAcrossWidening_Vector128_SByte, ["AddAcrossWidening.Vector128.UInt16"] = AddAcrossWidening_Vector128_UInt16, ["AddAcrossWidening.Vector128.UInt32"] = AddAcrossWidening_Vector128_UInt32, ["AddPairwise.Vector128.Byte"] = AddPairwise_Vector128_Byte, ["AddPairwise.Vector128.Double"] = AddPairwise_Vector128_Double, ["AddPairwise.Vector128.Int16"] = AddPairwise_Vector128_Int16, ["AddPairwise.Vector128.Int32"] = AddPairwise_Vector128_Int32, ["AddPairwise.Vector128.Int64"] = AddPairwise_Vector128_Int64, ["AddPairwise.Vector128.SByte"] = AddPairwise_Vector128_SByte, ["AddPairwise.Vector128.Single"] = AddPairwise_Vector128_Single, ["AddPairwise.Vector128.UInt16"] = AddPairwise_Vector128_UInt16, ["AddPairwise.Vector128.UInt32"] = AddPairwise_Vector128_UInt32, ["AddPairwise.Vector128.UInt64"] = AddPairwise_Vector128_UInt64, ["AddPairwiseScalar.Vector64.Single"] = AddPairwiseScalar_Vector64_Single, ["AddPairwiseScalar.Vector128.Double"] = AddPairwiseScalar_Vector128_Double, ["AddPairwiseScalar.Vector128.Int64"] = AddPairwiseScalar_Vector128_Int64, ["AddPairwiseScalar.Vector128.UInt64"] = AddPairwiseScalar_Vector128_UInt64, ["AddSaturate.Vector64.Byte.Vector64.SByte"] = AddSaturate_Vector64_Byte_Vector64_SByte, ["AddSaturate.Vector64.Int16.Vector64.UInt16"] = AddSaturate_Vector64_Int16_Vector64_UInt16, ["AddSaturate.Vector64.Int32.Vector64.UInt32"] = AddSaturate_Vector64_Int32_Vector64_UInt32, ["AddSaturate.Vector64.SByte.Vector64.Byte"] = AddSaturate_Vector64_SByte_Vector64_Byte, ["AddSaturate.Vector64.UInt16.Vector64.Int16"] = AddSaturate_Vector64_UInt16_Vector64_Int16, ["AddSaturate.Vector64.UInt32.Vector64.Int32"] = AddSaturate_Vector64_UInt32_Vector64_Int32, ["AddSaturate.Vector128.Byte.Vector128.SByte"] = AddSaturate_Vector128_Byte_Vector128_SByte, ["AddSaturate.Vector128.Int16.Vector128.UInt16"] = AddSaturate_Vector128_Int16_Vector128_UInt16, ["AddSaturate.Vector128.Int32.Vector128.UInt32"] = AddSaturate_Vector128_Int32_Vector128_UInt32, ["AddSaturate.Vector128.Int64.Vector128.UInt64"] = AddSaturate_Vector128_Int64_Vector128_UInt64, ["AddSaturate.Vector128.SByte.Vector128.Byte"] = AddSaturate_Vector128_SByte_Vector128_Byte, ["AddSaturate.Vector128.UInt16.Vector128.Int16"] = AddSaturate_Vector128_UInt16_Vector128_Int16, ["AddSaturate.Vector128.UInt32.Vector128.Int32"] = AddSaturate_Vector128_UInt32_Vector128_Int32, ["AddSaturate.Vector128.UInt64.Vector128.Int64"] = AddSaturate_Vector128_UInt64_Vector128_Int64, ["AddSaturateScalar.Vector64.Byte.Vector64.Byte"] = AddSaturateScalar_Vector64_Byte_Vector64_Byte, ["AddSaturateScalar.Vector64.Byte.Vector64.SByte"] = AddSaturateScalar_Vector64_Byte_Vector64_SByte, ["AddSaturateScalar.Vector64.Int16.Vector64.Int16"] = AddSaturateScalar_Vector64_Int16_Vector64_Int16, ["AddSaturateScalar.Vector64.Int16.Vector64.UInt16"] = AddSaturateScalar_Vector64_Int16_Vector64_UInt16, ["AddSaturateScalar.Vector64.Int32.Vector64.Int32"] = AddSaturateScalar_Vector64_Int32_Vector64_Int32, ["AddSaturateScalar.Vector64.Int32.Vector64.UInt32"] = AddSaturateScalar_Vector64_Int32_Vector64_UInt32, ["AddSaturateScalar.Vector64.Int64.Vector64.UInt64"] = AddSaturateScalar_Vector64_Int64_Vector64_UInt64, ["AddSaturateScalar.Vector64.SByte.Vector64.Byte"] = AddSaturateScalar_Vector64_SByte_Vector64_Byte, ["AddSaturateScalar.Vector64.SByte.Vector64.SByte"] = AddSaturateScalar_Vector64_SByte_Vector64_SByte, ["AddSaturateScalar.Vector64.UInt16.Vector64.Int16"] = AddSaturateScalar_Vector64_UInt16_Vector64_Int16, ["AddSaturateScalar.Vector64.UInt16.Vector64.UInt16"] = AddSaturateScalar_Vector64_UInt16_Vector64_UInt16, ["AddSaturateScalar.Vector64.UInt32.Vector64.Int32"] = AddSaturateScalar_Vector64_UInt32_Vector64_Int32, ["AddSaturateScalar.Vector64.UInt32.Vector64.UInt32"] = AddSaturateScalar_Vector64_UInt32_Vector64_UInt32, ["AddSaturateScalar.Vector64.UInt64.Vector64.Int64"] = AddSaturateScalar_Vector64_UInt64_Vector64_Int64, ["Ceiling.Vector128.Double"] = Ceiling_Vector128_Double, ["CompareEqual.Vector128.Double"] = CompareEqual_Vector128_Double, ["CompareEqual.Vector128.Int64"] = CompareEqual_Vector128_Int64, ["CompareEqual.Vector128.UInt64"] = CompareEqual_Vector128_UInt64, ["CompareEqualScalar.Vector64.Double"] = CompareEqualScalar_Vector64_Double, ["CompareEqualScalar.Vector64.Int64"] = CompareEqualScalar_Vector64_Int64, ["CompareEqualScalar.Vector64.Single"] = CompareEqualScalar_Vector64_Single, ["CompareEqualScalar.Vector64.UInt64"] = CompareEqualScalar_Vector64_UInt64, ["CompareGreaterThan.Vector128.Double"] = CompareGreaterThan_Vector128_Double, ["CompareGreaterThan.Vector128.Int64"] = CompareGreaterThan_Vector128_Int64, ["CompareGreaterThan.Vector128.UInt64"] = CompareGreaterThan_Vector128_UInt64, ["CompareGreaterThanScalar.Vector64.Double"] = CompareGreaterThanScalar_Vector64_Double, ["CompareGreaterThanScalar.Vector64.Int64"] = CompareGreaterThanScalar_Vector64_Int64, ["CompareGreaterThanScalar.Vector64.Single"] = CompareGreaterThanScalar_Vector64_Single, }; } } }
// 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 JIT.HardwareIntrinsics.Arm { public static partial class Program { static Program() { TestList = new Dictionary<string, Action>() { ["Abs.Vector128.Double"] = Abs_Vector128_Double, ["Abs.Vector128.Int64"] = Abs_Vector128_Int64, ["AbsSaturate.Vector128.Int64"] = AbsSaturate_Vector128_Int64, ["AbsSaturateScalar.Vector64.Int16"] = AbsSaturateScalar_Vector64_Int16, ["AbsSaturateScalar.Vector64.Int32"] = AbsSaturateScalar_Vector64_Int32, ["AbsSaturateScalar.Vector64.Int64"] = AbsSaturateScalar_Vector64_Int64, ["AbsSaturateScalar.Vector64.SByte"] = AbsSaturateScalar_Vector64_SByte, ["AbsScalar.Vector64.Int64"] = AbsScalar_Vector64_Int64, ["AbsoluteCompareGreaterThan.Vector128.Double"] = AbsoluteCompareGreaterThan_Vector128_Double, ["AbsoluteCompareGreaterThanScalar.Vector64.Double"] = AbsoluteCompareGreaterThanScalar_Vector64_Double, ["AbsoluteCompareGreaterThanScalar.Vector64.Single"] = AbsoluteCompareGreaterThanScalar_Vector64_Single, ["AbsoluteCompareGreaterThanOrEqual.Vector128.Double"] = AbsoluteCompareGreaterThanOrEqual_Vector128_Double, ["AbsoluteCompareGreaterThanOrEqualScalar.Vector64.Double"] = AbsoluteCompareGreaterThanOrEqualScalar_Vector64_Double, ["AbsoluteCompareGreaterThanOrEqualScalar.Vector64.Single"] = AbsoluteCompareGreaterThanOrEqualScalar_Vector64_Single, ["AbsoluteCompareLessThan.Vector128.Double"] = AbsoluteCompareLessThan_Vector128_Double, ["AbsoluteCompareLessThanScalar.Vector64.Double"] = AbsoluteCompareLessThanScalar_Vector64_Double, ["AbsoluteCompareLessThanScalar.Vector64.Single"] = AbsoluteCompareLessThanScalar_Vector64_Single, ["AbsoluteCompareLessThanOrEqual.Vector128.Double"] = AbsoluteCompareLessThanOrEqual_Vector128_Double, ["AbsoluteCompareLessThanOrEqualScalar.Vector64.Double"] = AbsoluteCompareLessThanOrEqualScalar_Vector64_Double, ["AbsoluteCompareLessThanOrEqualScalar.Vector64.Single"] = AbsoluteCompareLessThanOrEqualScalar_Vector64_Single, ["AbsoluteDifference.Vector128.Double"] = AbsoluteDifference_Vector128_Double, ["AbsoluteDifferenceScalar.Vector64.Double"] = AbsoluteDifferenceScalar_Vector64_Double, ["AbsoluteDifferenceScalar.Vector64.Single"] = AbsoluteDifferenceScalar_Vector64_Single, ["Add.Vector128.Double"] = Add_Vector128_Double, ["AddAcross.Vector64.Byte"] = AddAcross_Vector64_Byte, ["AddAcross.Vector64.Int16"] = AddAcross_Vector64_Int16, ["AddAcross.Vector64.SByte"] = AddAcross_Vector64_SByte, ["AddAcross.Vector64.UInt16"] = AddAcross_Vector64_UInt16, ["AddAcross.Vector128.Byte"] = AddAcross_Vector128_Byte, ["AddAcross.Vector128.Int16"] = AddAcross_Vector128_Int16, ["AddAcross.Vector128.Int32"] = AddAcross_Vector128_Int32, ["AddAcross.Vector128.SByte"] = AddAcross_Vector128_SByte, ["AddAcross.Vector128.UInt16"] = AddAcross_Vector128_UInt16, ["AddAcross.Vector128.UInt32"] = AddAcross_Vector128_UInt32, ["AddAcrossWidening.Vector64.Byte"] = AddAcrossWidening_Vector64_Byte, ["AddAcrossWidening.Vector64.Int16"] = AddAcrossWidening_Vector64_Int16, ["AddAcrossWidening.Vector64.SByte"] = AddAcrossWidening_Vector64_SByte, ["AddAcrossWidening.Vector64.UInt16"] = AddAcrossWidening_Vector64_UInt16, ["AddAcrossWidening.Vector128.Byte"] = AddAcrossWidening_Vector128_Byte, ["AddAcrossWidening.Vector128.Int16"] = AddAcrossWidening_Vector128_Int16, ["AddAcrossWidening.Vector128.Int32"] = AddAcrossWidening_Vector128_Int32, ["AddAcrossWidening.Vector128.SByte"] = AddAcrossWidening_Vector128_SByte, ["AddAcrossWidening.Vector128.UInt16"] = AddAcrossWidening_Vector128_UInt16, ["AddAcrossWidening.Vector128.UInt32"] = AddAcrossWidening_Vector128_UInt32, ["AddPairwise.Vector128.Byte"] = AddPairwise_Vector128_Byte, ["AddPairwise.Vector128.Double"] = AddPairwise_Vector128_Double, ["AddPairwise.Vector128.Int16"] = AddPairwise_Vector128_Int16, ["AddPairwise.Vector128.Int32"] = AddPairwise_Vector128_Int32, ["AddPairwise.Vector128.Int64"] = AddPairwise_Vector128_Int64, ["AddPairwise.Vector128.SByte"] = AddPairwise_Vector128_SByte, ["AddPairwise.Vector128.Single"] = AddPairwise_Vector128_Single, ["AddPairwise.Vector128.UInt16"] = AddPairwise_Vector128_UInt16, ["AddPairwise.Vector128.UInt32"] = AddPairwise_Vector128_UInt32, ["AddPairwise.Vector128.UInt64"] = AddPairwise_Vector128_UInt64, ["AddPairwiseScalar.Vector64.Single"] = AddPairwiseScalar_Vector64_Single, ["AddPairwiseScalar.Vector128.Double"] = AddPairwiseScalar_Vector128_Double, ["AddPairwiseScalar.Vector128.Int64"] = AddPairwiseScalar_Vector128_Int64, ["AddPairwiseScalar.Vector128.UInt64"] = AddPairwiseScalar_Vector128_UInt64, ["AddSaturate.Vector64.Byte.Vector64.SByte"] = AddSaturate_Vector64_Byte_Vector64_SByte, ["AddSaturate.Vector64.Int16.Vector64.UInt16"] = AddSaturate_Vector64_Int16_Vector64_UInt16, ["AddSaturate.Vector64.Int32.Vector64.UInt32"] = AddSaturate_Vector64_Int32_Vector64_UInt32, ["AddSaturate.Vector64.SByte.Vector64.Byte"] = AddSaturate_Vector64_SByte_Vector64_Byte, ["AddSaturate.Vector64.UInt16.Vector64.Int16"] = AddSaturate_Vector64_UInt16_Vector64_Int16, ["AddSaturate.Vector64.UInt32.Vector64.Int32"] = AddSaturate_Vector64_UInt32_Vector64_Int32, ["AddSaturate.Vector128.Byte.Vector128.SByte"] = AddSaturate_Vector128_Byte_Vector128_SByte, ["AddSaturate.Vector128.Int16.Vector128.UInt16"] = AddSaturate_Vector128_Int16_Vector128_UInt16, ["AddSaturate.Vector128.Int32.Vector128.UInt32"] = AddSaturate_Vector128_Int32_Vector128_UInt32, ["AddSaturate.Vector128.Int64.Vector128.UInt64"] = AddSaturate_Vector128_Int64_Vector128_UInt64, ["AddSaturate.Vector128.SByte.Vector128.Byte"] = AddSaturate_Vector128_SByte_Vector128_Byte, ["AddSaturate.Vector128.UInt16.Vector128.Int16"] = AddSaturate_Vector128_UInt16_Vector128_Int16, ["AddSaturate.Vector128.UInt32.Vector128.Int32"] = AddSaturate_Vector128_UInt32_Vector128_Int32, ["AddSaturate.Vector128.UInt64.Vector128.Int64"] = AddSaturate_Vector128_UInt64_Vector128_Int64, ["AddSaturateScalar.Vector64.Byte.Vector64.Byte"] = AddSaturateScalar_Vector64_Byte_Vector64_Byte, ["AddSaturateScalar.Vector64.Byte.Vector64.SByte"] = AddSaturateScalar_Vector64_Byte_Vector64_SByte, ["AddSaturateScalar.Vector64.Int16.Vector64.Int16"] = AddSaturateScalar_Vector64_Int16_Vector64_Int16, ["AddSaturateScalar.Vector64.Int16.Vector64.UInt16"] = AddSaturateScalar_Vector64_Int16_Vector64_UInt16, ["AddSaturateScalar.Vector64.Int32.Vector64.Int32"] = AddSaturateScalar_Vector64_Int32_Vector64_Int32, ["AddSaturateScalar.Vector64.Int32.Vector64.UInt32"] = AddSaturateScalar_Vector64_Int32_Vector64_UInt32, ["AddSaturateScalar.Vector64.Int64.Vector64.UInt64"] = AddSaturateScalar_Vector64_Int64_Vector64_UInt64, ["AddSaturateScalar.Vector64.SByte.Vector64.Byte"] = AddSaturateScalar_Vector64_SByte_Vector64_Byte, ["AddSaturateScalar.Vector64.SByte.Vector64.SByte"] = AddSaturateScalar_Vector64_SByte_Vector64_SByte, ["AddSaturateScalar.Vector64.UInt16.Vector64.Int16"] = AddSaturateScalar_Vector64_UInt16_Vector64_Int16, ["AddSaturateScalar.Vector64.UInt16.Vector64.UInt16"] = AddSaturateScalar_Vector64_UInt16_Vector64_UInt16, ["AddSaturateScalar.Vector64.UInt32.Vector64.Int32"] = AddSaturateScalar_Vector64_UInt32_Vector64_Int32, ["AddSaturateScalar.Vector64.UInt32.Vector64.UInt32"] = AddSaturateScalar_Vector64_UInt32_Vector64_UInt32, ["AddSaturateScalar.Vector64.UInt64.Vector64.Int64"] = AddSaturateScalar_Vector64_UInt64_Vector64_Int64, ["Ceiling.Vector128.Double"] = Ceiling_Vector128_Double, ["CompareEqual.Vector128.Double"] = CompareEqual_Vector128_Double, ["CompareEqual.Vector128.Int64"] = CompareEqual_Vector128_Int64, ["CompareEqual.Vector128.UInt64"] = CompareEqual_Vector128_UInt64, ["CompareEqualScalar.Vector64.Double"] = CompareEqualScalar_Vector64_Double, ["CompareEqualScalar.Vector64.Int64"] = CompareEqualScalar_Vector64_Int64, ["CompareEqualScalar.Vector64.Single"] = CompareEqualScalar_Vector64_Single, ["CompareEqualScalar.Vector64.UInt64"] = CompareEqualScalar_Vector64_UInt64, ["CompareGreaterThan.Vector128.Double"] = CompareGreaterThan_Vector128_Double, ["CompareGreaterThan.Vector128.Int64"] = CompareGreaterThan_Vector128_Int64, ["CompareGreaterThan.Vector128.UInt64"] = CompareGreaterThan_Vector128_UInt64, ["CompareGreaterThanScalar.Vector64.Double"] = CompareGreaterThanScalar_Vector64_Double, ["CompareGreaterThanScalar.Vector64.Int64"] = CompareGreaterThanScalar_Vector64_Int64, ["CompareGreaterThanScalar.Vector64.Single"] = CompareGreaterThanScalar_Vector64_Single, }; } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.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.Xml; using System.Collections; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Data { // This is an internal helper class used during Xml load to DataSet/DataDocument. // XmlToDatasetMap class provides functionality for binding elemants/attributes // to DataTable / DataColumn internal sealed class XmlToDatasetMap { private sealed class XmlNodeIdentety { public string LocalName; public string? NamespaceURI; public XmlNodeIdentety(string localName, string? namespaceURI) { LocalName = localName; NamespaceURI = namespaceURI; } public override int GetHashCode() { return LocalName.GetHashCode(); } public override bool Equals([NotNullWhen(true)] object? obj) { XmlNodeIdentety id = (XmlNodeIdentety)obj!; return ( (string.Equals(LocalName, id.LocalName, StringComparison.OrdinalIgnoreCase)) && (string.Equals(NamespaceURI, id.NamespaceURI, StringComparison.OrdinalIgnoreCase)) ); } } // This class exist to avoid alocatin of XmlNodeIdentety to every access to the hash table. // Unfortunetely XmlNode doesn't export single identety object. internal sealed class XmlNodeIdHashtable : Hashtable { private readonly XmlNodeIdentety _id = new XmlNodeIdentety(string.Empty, string.Empty); public XmlNodeIdHashtable(int capacity) : base(capacity) { } public object? this[XmlNode node] { get { _id.LocalName = node.LocalName; _id.NamespaceURI = node.NamespaceURI; return this[_id]; } } public object? this[XmlReader dataReader] { get { _id.LocalName = dataReader.LocalName; _id.NamespaceURI = dataReader.NamespaceURI; return this[_id]; } } public object? this[DataTable table] { get { _id.LocalName = table.EncodedTableName; _id.NamespaceURI = table.Namespace; return this[_id]; } } public object? this[string name] { get { _id.LocalName = name; _id.NamespaceURI = string.Empty; return this[_id]; } } } private sealed class TableSchemaInfo { public DataTable TableSchema; public XmlNodeIdHashtable ColumnsSchemaMap; public TableSchemaInfo(DataTable tableSchema) { TableSchema = tableSchema; ColumnsSchemaMap = new XmlNodeIdHashtable(tableSchema.Columns.Count); } } private XmlNodeIdHashtable _tableSchemaMap; // Holds all the tables information private TableSchemaInfo? _lastTableSchemaInfo; // Used to infer schema public XmlToDatasetMap(DataSet dataSet, XmlNameTable nameTable) { Debug.Assert(dataSet != null, "DataSet can't be null"); Debug.Assert(nameTable != null, "NameTable can't be null"); BuildIdentityMap(dataSet, nameTable); } // Used to read data with known schema public XmlToDatasetMap(XmlNameTable nameTable, DataSet dataSet) { Debug.Assert(dataSet != null, "DataSet can't be null"); Debug.Assert(nameTable != null, "NameTable can't be null"); BuildIdentityMap(nameTable, dataSet); } // Used to infer schema public XmlToDatasetMap(DataTable dataTable, XmlNameTable nameTable) { Debug.Assert(dataTable != null, "DataTable can't be null"); Debug.Assert(nameTable != null, "NameTable can't be null"); BuildIdentityMap(dataTable, nameTable); } // Used to read data with known schema public XmlToDatasetMap(XmlNameTable nameTable, DataTable dataTable) { Debug.Assert(dataTable != null, "DataTable can't be null"); Debug.Assert(nameTable != null, "NameTable can't be null"); BuildIdentityMap(nameTable, dataTable); } internal static bool IsMappedColumn(DataColumn c) { return (c.ColumnMapping != MappingType.Hidden); } // Used to infere schema private TableSchemaInfo? AddTableSchema(DataTable table, XmlNameTable nameTable) { // SDUB: Because in our case reader already read the document all names that we can meet in the // document already has an entry in NameTable. // If in future we will build identity map before reading XML we can replace Get() to Add() // Sdub: GetIdentity is called from two places: BuildIdentityMap() and LoadRows() // First case deals with decoded names; Second one with encoded names. // We decided encoded names in first case (instead of decoding them in second) // because it save us time in LoadRows(). We have, as usual, more data them schemas string? tableLocalName = nameTable.Get(table.EncodedTableName); string? tableNamespace = nameTable.Get(table.Namespace); if (tableLocalName == null) { // because name of this table isn't present in XML we don't need mapping for it. // Less mapping faster we work. return null; } TableSchemaInfo tableSchemaInfo = new TableSchemaInfo(table); _tableSchemaMap[new XmlNodeIdentety(tableLocalName, tableNamespace)] = tableSchemaInfo; return tableSchemaInfo; } private TableSchemaInfo AddTableSchema(XmlNameTable nameTable, DataTable table) { // Enzol:This is the opposite of the previous function: // we populate the nametable so that the hash comparison can happen as // object comparison instead of strings. // Sdub: GetIdentity is called from two places: BuildIdentityMap() and LoadRows() // First case deals with decoded names; Second one with encoded names. // We decided encoded names in first case (instead of decoding them in second) // because it save us time in LoadRows(). We have, as usual, more data them schemas string _tableLocalName = table.EncodedTableName; // Table name string? tableLocalName = nameTable.Get(_tableLocalName); // Look it up in nametable if (tableLocalName == null) { // If not found tableLocalName = nameTable.Add(_tableLocalName); // Add it } table._encodedTableName = tableLocalName; // And set it back string? tableNamespace = nameTable.Get(table.Namespace); // Look ip table namespace if (tableNamespace == null) { // If not found tableNamespace = nameTable.Add(table.Namespace); // Add it } else { if (table._tableNamespace != null) // Update table namespace table._tableNamespace = tableNamespace; } TableSchemaInfo tableSchemaInfo = new TableSchemaInfo(table); // Create new table schema info _tableSchemaMap[new XmlNodeIdentety(tableLocalName, tableNamespace)] = tableSchemaInfo; // And add it to the hashtable return tableSchemaInfo; // Return it as we have to populate // Column schema map and Child table // schema map in it } private static bool AddColumnSchema(DataColumn col, XmlNameTable nameTable, XmlNodeIdHashtable columns) { string? columnLocalName = nameTable.Get(col.EncodedColumnName); string? columnNamespace = nameTable.Get(col.Namespace); if (columnLocalName == null) { return false; } XmlNodeIdentety idColumn = new XmlNodeIdentety(columnLocalName, columnNamespace); columns[idColumn] = col; if (col.ColumnName.StartsWith("xml", StringComparison.OrdinalIgnoreCase)) { HandleSpecialColumn(col, nameTable, columns); } return true; } private static bool AddColumnSchema(XmlNameTable nameTable, DataColumn col, XmlNodeIdHashtable columns) { string _columnLocalName = XmlConvert.EncodeLocalName(col.ColumnName); string? columnLocalName = nameTable.Get(_columnLocalName); // Look it up in a name table if (columnLocalName == null) { // Not found? columnLocalName = nameTable.Add(_columnLocalName); // Add it } col._encodedColumnName = columnLocalName; // And set it back string? columnNamespace = nameTable.Get(col.Namespace); // Get column namespace from nametable if (columnNamespace == null) { // Not found ? columnNamespace = nameTable.Add(col.Namespace); // Add it } else { if (col._columnUri != null) // Update namespace col._columnUri = columnNamespace; } // Create XmlNodeIdentety // for this column XmlNodeIdentety idColumn = new XmlNodeIdentety(columnLocalName, columnNamespace); columns[idColumn] = col; // And add it to hashtable if (col.ColumnName.StartsWith("xml", StringComparison.OrdinalIgnoreCase)) { HandleSpecialColumn(col, nameTable, columns); } return true; } [MemberNotNull(nameof(_tableSchemaMap))] private void BuildIdentityMap(DataSet dataSet, XmlNameTable nameTable) { _tableSchemaMap = new XmlNodeIdHashtable(dataSet.Tables.Count); foreach (DataTable t in dataSet.Tables) { TableSchemaInfo? tableSchemaInfo = AddTableSchema(t, nameTable); if (tableSchemaInfo != null) { foreach (DataColumn c in t.Columns) { // don't include auto-generated PK, FK and any hidden columns to be part of mapping if (IsMappedColumn(c)) { AddColumnSchema(c, nameTable, tableSchemaInfo.ColumnsSchemaMap); } } } } } // This one is used while reading data with preloaded schema [MemberNotNull(nameof(_tableSchemaMap))] private void BuildIdentityMap(XmlNameTable nameTable, DataSet dataSet) { _tableSchemaMap = new XmlNodeIdHashtable(dataSet.Tables.Count); // This hash table contains // tables schemas as TableSchemaInfo objects // These objects holds reference to the table. // Hash tables with columns schema maps // and child tables schema maps string? dsNamespace = nameTable.Get(dataSet.Namespace); // Attept to look up DataSet namespace // in the name table if (dsNamespace == null) { // Found ? dsNamespace = nameTable.Add(dataSet.Namespace); // Nope. Add it } dataSet._namespaceURI = dsNamespace; // Set a DataSet namespace URI foreach (DataTable t in dataSet.Tables) { // For each table TableSchemaInfo tableSchemaInfo = AddTableSchema(nameTable, t); // Add table schema info to hash table if (tableSchemaInfo != null) { foreach (DataColumn c in t.Columns) { // Add column schema map // don't include auto-generated PK, FK and any hidden columns to be part of mapping if (IsMappedColumn(c)) { // If mapped column AddColumnSchema(nameTable, c, tableSchemaInfo.ColumnsSchemaMap); } // Add it to the map } // Add child nested tables to the schema foreach (DataRelation r in t.ChildRelations) { // Do we have a child tables ? if (r.Nested) { // Is it nested? // don't include non nested tables // Handle namespaces and names as usuall string _tableLocalName = XmlConvert.EncodeLocalName(r.ChildTable.TableName); string? tableLocalName = nameTable.Get(_tableLocalName); if (tableLocalName == null) { tableLocalName = nameTable.Add(_tableLocalName); } string? tableNamespace = nameTable.Get(r.ChildTable.Namespace); if (tableNamespace == null) { tableNamespace = nameTable.Add(r.ChildTable.Namespace); } XmlNodeIdentety idTable = new XmlNodeIdentety(tableLocalName, tableNamespace); tableSchemaInfo.ColumnsSchemaMap[idTable] = r.ChildTable; } } } } } // Used for inference [MemberNotNull(nameof(_tableSchemaMap))] private void BuildIdentityMap(DataTable dataTable, XmlNameTable nameTable) { _tableSchemaMap = new XmlNodeIdHashtable(1); TableSchemaInfo? tableSchemaInfo = AddTableSchema(dataTable, nameTable); if (tableSchemaInfo != null) { foreach (DataColumn c in dataTable.Columns) { // don't include auto-generated PK, FK and any hidden columns to be part of mapping if (IsMappedColumn(c)) { AddColumnSchema(c, nameTable, tableSchemaInfo.ColumnsSchemaMap); } } } } // This one is used while reading data with preloaded schema [MemberNotNull(nameof(_tableSchemaMap))] private void BuildIdentityMap(XmlNameTable nameTable, DataTable dataTable) { ArrayList tableList = GetSelfAndDescendants(dataTable); // Get list of tables we're loading // This includes our table and // related tables tree _tableSchemaMap = new XmlNodeIdHashtable(tableList.Count); // Create hash table to hold all // tables to load. foreach (DataTable t in tableList) { // For each table TableSchemaInfo tableSchemaInfo = AddTableSchema(nameTable, t); // Create schema info if (tableSchemaInfo != null) { foreach (DataColumn c in t.Columns) { // Add column information // don't include auto-generated PK, FK and any hidden columns to be part of mapping if (IsMappedColumn(c)) { AddColumnSchema(nameTable, c, tableSchemaInfo.ColumnsSchemaMap); } } foreach (DataRelation r in t.ChildRelations) { // Add nested tables information if (r.Nested) { // Is it nested? // don't include non nested tables // Handle namespaces and names as usuall string _tableLocalName = XmlConvert.EncodeLocalName(r.ChildTable.TableName); string? tableLocalName = nameTable.Get(_tableLocalName); if (tableLocalName == null) { tableLocalName = nameTable.Add(_tableLocalName); } string? tableNamespace = nameTable.Get(r.ChildTable.Namespace); if (tableNamespace == null) { tableNamespace = nameTable.Add(r.ChildTable.Namespace); } XmlNodeIdentety idTable = new XmlNodeIdentety(tableLocalName, tableNamespace); tableSchemaInfo.ColumnsSchemaMap[idTable] = r.ChildTable; } } } } } private static ArrayList GetSelfAndDescendants(DataTable dt) { // breadth-first ArrayList tableList = new ArrayList(); tableList.Add(dt); int nCounter = 0; while (nCounter < tableList.Count) { foreach (DataRelation childRelations in ((DataTable)tableList[nCounter]!).ChildRelations) { if (!tableList.Contains(childRelations.ChildTable)) tableList.Add(childRelations.ChildTable); } nCounter++; } return tableList; } // Used to infer schema and top most node public object? GetColumnSchema(XmlNode node, bool fIgnoreNamespace) { Debug.Assert(node != null, "Argument validation"); TableSchemaInfo? tableSchemaInfo; XmlNode? nodeRegion = (node.NodeType == XmlNodeType.Attribute) ? ((XmlAttribute)node).OwnerElement : node.ParentNode; do { if (nodeRegion == null || nodeRegion.NodeType != XmlNodeType.Element) { return null; } tableSchemaInfo = (TableSchemaInfo?)(fIgnoreNamespace ? _tableSchemaMap[nodeRegion.LocalName] : _tableSchemaMap[nodeRegion]); nodeRegion = nodeRegion.ParentNode; } while (tableSchemaInfo == null); if (fIgnoreNamespace) return tableSchemaInfo.ColumnsSchemaMap[node.LocalName]; else return tableSchemaInfo.ColumnsSchemaMap[node]; } public object? GetColumnSchema(DataTable table, XmlReader dataReader, bool fIgnoreNamespace) { if ((_lastTableSchemaInfo == null) || (_lastTableSchemaInfo.TableSchema != table)) { _lastTableSchemaInfo = (TableSchemaInfo)(fIgnoreNamespace ? _tableSchemaMap[table.EncodedTableName]! : _tableSchemaMap[table]!); } if (fIgnoreNamespace) return _lastTableSchemaInfo.ColumnsSchemaMap[dataReader.LocalName]; return _lastTableSchemaInfo.ColumnsSchemaMap[dataReader]; } // Used to infer schema public object? GetSchemaForNode(XmlNode node, bool fIgnoreNamespace) { TableSchemaInfo? tableSchemaInfo = null; if (node.NodeType == XmlNodeType.Element) { // If element tableSchemaInfo = (TableSchemaInfo?)(fIgnoreNamespace ? _tableSchemaMap[node.LocalName] : _tableSchemaMap[node]); } // Look up table schema info for it if (tableSchemaInfo != null) { // Got info ? return tableSchemaInfo.TableSchema; // Yes, Return table } return GetColumnSchema(node, fIgnoreNamespace); // Attempt to locate column } public DataTable? GetTableForNode(XmlReader node, bool fIgnoreNamespace) { TableSchemaInfo? tableSchemaInfo = (TableSchemaInfo?)(fIgnoreNamespace ? _tableSchemaMap[node.LocalName] : _tableSchemaMap[node]); if (tableSchemaInfo != null) { _lastTableSchemaInfo = tableSchemaInfo; return _lastTableSchemaInfo.TableSchema; } return null; } private static void HandleSpecialColumn(DataColumn col, XmlNameTable nameTable, XmlNodeIdHashtable columns) { // if column name starts with xml, we encode it manualy and add it for look up Debug.Assert(col.ColumnName.StartsWith("xml", StringComparison.OrdinalIgnoreCase), "column name should start with xml"); string tempColumnName; if ('x' == col.ColumnName[0]) { tempColumnName = "_x0078_"; // lower case xml... -> _x0078_ml... } else { tempColumnName = "_x0058_"; // upper case Xml... -> _x0058_ml... } tempColumnName = string.Concat(tempColumnName, col.ColumnName.AsSpan(1)); if (nameTable.Get(tempColumnName) == null) { nameTable.Add(tempColumnName); } string? columnNamespace = nameTable.Get(col.Namespace); XmlNodeIdentety idColumn = new XmlNodeIdentety(tempColumnName, columnNamespace); columns[idColumn] = col; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Xml; using System.Collections; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Data { // This is an internal helper class used during Xml load to DataSet/DataDocument. // XmlToDatasetMap class provides functionality for binding elemants/attributes // to DataTable / DataColumn internal sealed class XmlToDatasetMap { private sealed class XmlNodeIdentety { public string LocalName; public string? NamespaceURI; public XmlNodeIdentety(string localName, string? namespaceURI) { LocalName = localName; NamespaceURI = namespaceURI; } public override int GetHashCode() { return LocalName.GetHashCode(); } public override bool Equals([NotNullWhen(true)] object? obj) { XmlNodeIdentety id = (XmlNodeIdentety)obj!; return ( (string.Equals(LocalName, id.LocalName, StringComparison.OrdinalIgnoreCase)) && (string.Equals(NamespaceURI, id.NamespaceURI, StringComparison.OrdinalIgnoreCase)) ); } } // This class exist to avoid alocatin of XmlNodeIdentety to every access to the hash table. // Unfortunetely XmlNode doesn't export single identety object. internal sealed class XmlNodeIdHashtable : Hashtable { private readonly XmlNodeIdentety _id = new XmlNodeIdentety(string.Empty, string.Empty); public XmlNodeIdHashtable(int capacity) : base(capacity) { } public object? this[XmlNode node] { get { _id.LocalName = node.LocalName; _id.NamespaceURI = node.NamespaceURI; return this[_id]; } } public object? this[XmlReader dataReader] { get { _id.LocalName = dataReader.LocalName; _id.NamespaceURI = dataReader.NamespaceURI; return this[_id]; } } public object? this[DataTable table] { get { _id.LocalName = table.EncodedTableName; _id.NamespaceURI = table.Namespace; return this[_id]; } } public object? this[string name] { get { _id.LocalName = name; _id.NamespaceURI = string.Empty; return this[_id]; } } } private sealed class TableSchemaInfo { public DataTable TableSchema; public XmlNodeIdHashtable ColumnsSchemaMap; public TableSchemaInfo(DataTable tableSchema) { TableSchema = tableSchema; ColumnsSchemaMap = new XmlNodeIdHashtable(tableSchema.Columns.Count); } } private XmlNodeIdHashtable _tableSchemaMap; // Holds all the tables information private TableSchemaInfo? _lastTableSchemaInfo; // Used to infer schema public XmlToDatasetMap(DataSet dataSet, XmlNameTable nameTable) { Debug.Assert(dataSet != null, "DataSet can't be null"); Debug.Assert(nameTable != null, "NameTable can't be null"); BuildIdentityMap(dataSet, nameTable); } // Used to read data with known schema public XmlToDatasetMap(XmlNameTable nameTable, DataSet dataSet) { Debug.Assert(dataSet != null, "DataSet can't be null"); Debug.Assert(nameTable != null, "NameTable can't be null"); BuildIdentityMap(nameTable, dataSet); } // Used to infer schema public XmlToDatasetMap(DataTable dataTable, XmlNameTable nameTable) { Debug.Assert(dataTable != null, "DataTable can't be null"); Debug.Assert(nameTable != null, "NameTable can't be null"); BuildIdentityMap(dataTable, nameTable); } // Used to read data with known schema public XmlToDatasetMap(XmlNameTable nameTable, DataTable dataTable) { Debug.Assert(dataTable != null, "DataTable can't be null"); Debug.Assert(nameTable != null, "NameTable can't be null"); BuildIdentityMap(nameTable, dataTable); } internal static bool IsMappedColumn(DataColumn c) { return (c.ColumnMapping != MappingType.Hidden); } // Used to infere schema private TableSchemaInfo? AddTableSchema(DataTable table, XmlNameTable nameTable) { // SDUB: Because in our case reader already read the document all names that we can meet in the // document already has an entry in NameTable. // If in future we will build identity map before reading XML we can replace Get() to Add() // Sdub: GetIdentity is called from two places: BuildIdentityMap() and LoadRows() // First case deals with decoded names; Second one with encoded names. // We decided encoded names in first case (instead of decoding them in second) // because it save us time in LoadRows(). We have, as usual, more data them schemas string? tableLocalName = nameTable.Get(table.EncodedTableName); string? tableNamespace = nameTable.Get(table.Namespace); if (tableLocalName == null) { // because name of this table isn't present in XML we don't need mapping for it. // Less mapping faster we work. return null; } TableSchemaInfo tableSchemaInfo = new TableSchemaInfo(table); _tableSchemaMap[new XmlNodeIdentety(tableLocalName, tableNamespace)] = tableSchemaInfo; return tableSchemaInfo; } private TableSchemaInfo AddTableSchema(XmlNameTable nameTable, DataTable table) { // Enzol:This is the opposite of the previous function: // we populate the nametable so that the hash comparison can happen as // object comparison instead of strings. // Sdub: GetIdentity is called from two places: BuildIdentityMap() and LoadRows() // First case deals with decoded names; Second one with encoded names. // We decided encoded names in first case (instead of decoding them in second) // because it save us time in LoadRows(). We have, as usual, more data them schemas string _tableLocalName = table.EncodedTableName; // Table name string? tableLocalName = nameTable.Get(_tableLocalName); // Look it up in nametable if (tableLocalName == null) { // If not found tableLocalName = nameTable.Add(_tableLocalName); // Add it } table._encodedTableName = tableLocalName; // And set it back string? tableNamespace = nameTable.Get(table.Namespace); // Look ip table namespace if (tableNamespace == null) { // If not found tableNamespace = nameTable.Add(table.Namespace); // Add it } else { if (table._tableNamespace != null) // Update table namespace table._tableNamespace = tableNamespace; } TableSchemaInfo tableSchemaInfo = new TableSchemaInfo(table); // Create new table schema info _tableSchemaMap[new XmlNodeIdentety(tableLocalName, tableNamespace)] = tableSchemaInfo; // And add it to the hashtable return tableSchemaInfo; // Return it as we have to populate // Column schema map and Child table // schema map in it } private static bool AddColumnSchema(DataColumn col, XmlNameTable nameTable, XmlNodeIdHashtable columns) { string? columnLocalName = nameTable.Get(col.EncodedColumnName); string? columnNamespace = nameTable.Get(col.Namespace); if (columnLocalName == null) { return false; } XmlNodeIdentety idColumn = new XmlNodeIdentety(columnLocalName, columnNamespace); columns[idColumn] = col; if (col.ColumnName.StartsWith("xml", StringComparison.OrdinalIgnoreCase)) { HandleSpecialColumn(col, nameTable, columns); } return true; } private static bool AddColumnSchema(XmlNameTable nameTable, DataColumn col, XmlNodeIdHashtable columns) { string _columnLocalName = XmlConvert.EncodeLocalName(col.ColumnName); string? columnLocalName = nameTable.Get(_columnLocalName); // Look it up in a name table if (columnLocalName == null) { // Not found? columnLocalName = nameTable.Add(_columnLocalName); // Add it } col._encodedColumnName = columnLocalName; // And set it back string? columnNamespace = nameTable.Get(col.Namespace); // Get column namespace from nametable if (columnNamespace == null) { // Not found ? columnNamespace = nameTable.Add(col.Namespace); // Add it } else { if (col._columnUri != null) // Update namespace col._columnUri = columnNamespace; } // Create XmlNodeIdentety // for this column XmlNodeIdentety idColumn = new XmlNodeIdentety(columnLocalName, columnNamespace); columns[idColumn] = col; // And add it to hashtable if (col.ColumnName.StartsWith("xml", StringComparison.OrdinalIgnoreCase)) { HandleSpecialColumn(col, nameTable, columns); } return true; } [MemberNotNull(nameof(_tableSchemaMap))] private void BuildIdentityMap(DataSet dataSet, XmlNameTable nameTable) { _tableSchemaMap = new XmlNodeIdHashtable(dataSet.Tables.Count); foreach (DataTable t in dataSet.Tables) { TableSchemaInfo? tableSchemaInfo = AddTableSchema(t, nameTable); if (tableSchemaInfo != null) { foreach (DataColumn c in t.Columns) { // don't include auto-generated PK, FK and any hidden columns to be part of mapping if (IsMappedColumn(c)) { AddColumnSchema(c, nameTable, tableSchemaInfo.ColumnsSchemaMap); } } } } } // This one is used while reading data with preloaded schema [MemberNotNull(nameof(_tableSchemaMap))] private void BuildIdentityMap(XmlNameTable nameTable, DataSet dataSet) { _tableSchemaMap = new XmlNodeIdHashtable(dataSet.Tables.Count); // This hash table contains // tables schemas as TableSchemaInfo objects // These objects holds reference to the table. // Hash tables with columns schema maps // and child tables schema maps string? dsNamespace = nameTable.Get(dataSet.Namespace); // Attept to look up DataSet namespace // in the name table if (dsNamespace == null) { // Found ? dsNamespace = nameTable.Add(dataSet.Namespace); // Nope. Add it } dataSet._namespaceURI = dsNamespace; // Set a DataSet namespace URI foreach (DataTable t in dataSet.Tables) { // For each table TableSchemaInfo tableSchemaInfo = AddTableSchema(nameTable, t); // Add table schema info to hash table if (tableSchemaInfo != null) { foreach (DataColumn c in t.Columns) { // Add column schema map // don't include auto-generated PK, FK and any hidden columns to be part of mapping if (IsMappedColumn(c)) { // If mapped column AddColumnSchema(nameTable, c, tableSchemaInfo.ColumnsSchemaMap); } // Add it to the map } // Add child nested tables to the schema foreach (DataRelation r in t.ChildRelations) { // Do we have a child tables ? if (r.Nested) { // Is it nested? // don't include non nested tables // Handle namespaces and names as usuall string _tableLocalName = XmlConvert.EncodeLocalName(r.ChildTable.TableName); string? tableLocalName = nameTable.Get(_tableLocalName); if (tableLocalName == null) { tableLocalName = nameTable.Add(_tableLocalName); } string? tableNamespace = nameTable.Get(r.ChildTable.Namespace); if (tableNamespace == null) { tableNamespace = nameTable.Add(r.ChildTable.Namespace); } XmlNodeIdentety idTable = new XmlNodeIdentety(tableLocalName, tableNamespace); tableSchemaInfo.ColumnsSchemaMap[idTable] = r.ChildTable; } } } } } // Used for inference [MemberNotNull(nameof(_tableSchemaMap))] private void BuildIdentityMap(DataTable dataTable, XmlNameTable nameTable) { _tableSchemaMap = new XmlNodeIdHashtable(1); TableSchemaInfo? tableSchemaInfo = AddTableSchema(dataTable, nameTable); if (tableSchemaInfo != null) { foreach (DataColumn c in dataTable.Columns) { // don't include auto-generated PK, FK and any hidden columns to be part of mapping if (IsMappedColumn(c)) { AddColumnSchema(c, nameTable, tableSchemaInfo.ColumnsSchemaMap); } } } } // This one is used while reading data with preloaded schema [MemberNotNull(nameof(_tableSchemaMap))] private void BuildIdentityMap(XmlNameTable nameTable, DataTable dataTable) { ArrayList tableList = GetSelfAndDescendants(dataTable); // Get list of tables we're loading // This includes our table and // related tables tree _tableSchemaMap = new XmlNodeIdHashtable(tableList.Count); // Create hash table to hold all // tables to load. foreach (DataTable t in tableList) { // For each table TableSchemaInfo tableSchemaInfo = AddTableSchema(nameTable, t); // Create schema info if (tableSchemaInfo != null) { foreach (DataColumn c in t.Columns) { // Add column information // don't include auto-generated PK, FK and any hidden columns to be part of mapping if (IsMappedColumn(c)) { AddColumnSchema(nameTable, c, tableSchemaInfo.ColumnsSchemaMap); } } foreach (DataRelation r in t.ChildRelations) { // Add nested tables information if (r.Nested) { // Is it nested? // don't include non nested tables // Handle namespaces and names as usuall string _tableLocalName = XmlConvert.EncodeLocalName(r.ChildTable.TableName); string? tableLocalName = nameTable.Get(_tableLocalName); if (tableLocalName == null) { tableLocalName = nameTable.Add(_tableLocalName); } string? tableNamespace = nameTable.Get(r.ChildTable.Namespace); if (tableNamespace == null) { tableNamespace = nameTable.Add(r.ChildTable.Namespace); } XmlNodeIdentety idTable = new XmlNodeIdentety(tableLocalName, tableNamespace); tableSchemaInfo.ColumnsSchemaMap[idTable] = r.ChildTable; } } } } } private static ArrayList GetSelfAndDescendants(DataTable dt) { // breadth-first ArrayList tableList = new ArrayList(); tableList.Add(dt); int nCounter = 0; while (nCounter < tableList.Count) { foreach (DataRelation childRelations in ((DataTable)tableList[nCounter]!).ChildRelations) { if (!tableList.Contains(childRelations.ChildTable)) tableList.Add(childRelations.ChildTable); } nCounter++; } return tableList; } // Used to infer schema and top most node public object? GetColumnSchema(XmlNode node, bool fIgnoreNamespace) { Debug.Assert(node != null, "Argument validation"); TableSchemaInfo? tableSchemaInfo; XmlNode? nodeRegion = (node.NodeType == XmlNodeType.Attribute) ? ((XmlAttribute)node).OwnerElement : node.ParentNode; do { if (nodeRegion == null || nodeRegion.NodeType != XmlNodeType.Element) { return null; } tableSchemaInfo = (TableSchemaInfo?)(fIgnoreNamespace ? _tableSchemaMap[nodeRegion.LocalName] : _tableSchemaMap[nodeRegion]); nodeRegion = nodeRegion.ParentNode; } while (tableSchemaInfo == null); if (fIgnoreNamespace) return tableSchemaInfo.ColumnsSchemaMap[node.LocalName]; else return tableSchemaInfo.ColumnsSchemaMap[node]; } public object? GetColumnSchema(DataTable table, XmlReader dataReader, bool fIgnoreNamespace) { if ((_lastTableSchemaInfo == null) || (_lastTableSchemaInfo.TableSchema != table)) { _lastTableSchemaInfo = (TableSchemaInfo)(fIgnoreNamespace ? _tableSchemaMap[table.EncodedTableName]! : _tableSchemaMap[table]!); } if (fIgnoreNamespace) return _lastTableSchemaInfo.ColumnsSchemaMap[dataReader.LocalName]; return _lastTableSchemaInfo.ColumnsSchemaMap[dataReader]; } // Used to infer schema public object? GetSchemaForNode(XmlNode node, bool fIgnoreNamespace) { TableSchemaInfo? tableSchemaInfo = null; if (node.NodeType == XmlNodeType.Element) { // If element tableSchemaInfo = (TableSchemaInfo?)(fIgnoreNamespace ? _tableSchemaMap[node.LocalName] : _tableSchemaMap[node]); } // Look up table schema info for it if (tableSchemaInfo != null) { // Got info ? return tableSchemaInfo.TableSchema; // Yes, Return table } return GetColumnSchema(node, fIgnoreNamespace); // Attempt to locate column } public DataTable? GetTableForNode(XmlReader node, bool fIgnoreNamespace) { TableSchemaInfo? tableSchemaInfo = (TableSchemaInfo?)(fIgnoreNamespace ? _tableSchemaMap[node.LocalName] : _tableSchemaMap[node]); if (tableSchemaInfo != null) { _lastTableSchemaInfo = tableSchemaInfo; return _lastTableSchemaInfo.TableSchema; } return null; } private static void HandleSpecialColumn(DataColumn col, XmlNameTable nameTable, XmlNodeIdHashtable columns) { // if column name starts with xml, we encode it manualy and add it for look up Debug.Assert(col.ColumnName.StartsWith("xml", StringComparison.OrdinalIgnoreCase), "column name should start with xml"); string tempColumnName; if ('x' == col.ColumnName[0]) { tempColumnName = "_x0078_"; // lower case xml... -> _x0078_ml... } else { tempColumnName = "_x0058_"; // upper case Xml... -> _x0058_ml... } tempColumnName = string.Concat(tempColumnName, col.ColumnName.AsSpan(1)); if (nameTable.Get(tempColumnName) == null) { nameTable.Add(tempColumnName); } string? columnNamespace = nameTable.Get(col.Namespace); XmlNodeIdentety idColumn = new XmlNodeIdentety(tempColumnName, columnNamespace); columns[idColumn] = col; } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Threading.Tasks.Extensions/tests/AsyncValueTaskMethodBuilderTests.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.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks.Sources.Tests; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Threading.Tasks.Tests { public class AsyncValueTaskMethodBuilderTests { [Fact] public void Create_ReturnsDefaultInstance() // implementation detail being verified { Assert.Equal(default, AsyncValueTaskMethodBuilder.Create()); Assert.Equal(default, AsyncValueTaskMethodBuilder<int>.Create()); } [Fact] public void NonGeneric_SetResult_BeforeAccessTask_ValueTaskIsDefault() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); b.SetResult(); Assert.Equal(default, b.Task); } [Fact] public void Generic_SetResult_BeforeAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); b.SetResult(42); ValueTask<int> vt = b.Task; Assert.Equal(vt, b.Task); Assert.Equal(new ValueTask<int>(42), vt); } [Fact] public void NonGeneric_SetResult_AfterAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); ValueTask vt = b.Task; Assert.NotEqual(default, vt); Assert.Equal(vt, b.Task); b.SetResult(); Assert.Equal(vt, b.Task); Assert.True(vt.IsCompletedSuccessfully); } [Fact] public void Generic_SetResult_AfterAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); ValueTask<int> vt = b.Task; Assert.NotEqual(default, vt); Assert.Equal(vt, b.Task); b.SetResult(42); Assert.Equal(vt, b.Task); Assert.True(vt.IsCompletedSuccessfully); Assert.Equal(42, vt.Result); } [Fact] public void NonGeneric_SetException_BeforeAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); var e = new FormatException(); b.SetException(e); ValueTask vt = b.Task; Assert.Equal(vt, b.Task); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void Generic_SetException_BeforeAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); var e = new FormatException(); b.SetException(e); ValueTask<int> vt = b.Task; Assert.Equal(vt, b.Task); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void NonGeneric_SetException_AfterAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); ValueTask vt = b.Task; Assert.Equal(vt, b.Task); var e = new FormatException(); b.SetException(e); Assert.Equal(vt, b.Task); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void Generic_SetException_AfterAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); ValueTask<int> vt = b.Task; Assert.Equal(vt, b.Task); var e = new FormatException(); b.SetException(e); Assert.Equal(vt, b.Task); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void NonGeneric_SetException_OperationCanceledException_CancelsTask() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); ValueTask vt = b.Task; Assert.Equal(vt, b.Task); var e = new OperationCanceledException(); b.SetException(e); Assert.Equal(vt, b.Task); Assert.True(vt.IsCanceled); Assert.Same(e, Assert.Throws<OperationCanceledException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void Generic_SetException_OperationCanceledException_CancelsTask() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); ValueTask<int> vt = b.Task; Assert.Equal(vt, b.Task); var e = new OperationCanceledException(); b.SetException(e); Assert.Equal(vt, b.Task); Assert.True(vt.IsCanceled); Assert.Same(e, Assert.Throws<OperationCanceledException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void NonGeneric_SetExceptionWithNullException_Throws() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); AssertExtensions.Throws<ArgumentNullException>("exception", () => b.SetException(null)); } [Fact] public void Generic_SetExceptionWithNullException_Throws() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); AssertExtensions.Throws<ArgumentNullException>("exception", () => b.SetException(null)); } [Fact] public void NonGeneric_Start_InvokesMoveNext() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); int invokes = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => invokes++ }; b.Start(ref dsm); Assert.Equal(1, invokes); } [Fact] public void Generic_Start_InvokesMoveNext() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); int invokes = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => invokes++ }; b.Start(ref dsm); Assert.Equal(1, invokes); } [Theory] [InlineData(1, false)] [InlineData(2, false)] [InlineData(1, true)] [InlineData(2, true)] public void NonGeneric_AwaitOnCompleted_ForcesTaskCreation(int numAwaits, bool awaitUnsafe) { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); var dsm = new DelegateStateMachine(); TaskAwaiter<int> t = new TaskCompletionSource<int>().Task.GetAwaiter(); Assert.InRange(numAwaits, 1, int.MaxValue); for (int i = 1; i <= numAwaits; i++) { if (awaitUnsafe) { b.AwaitUnsafeOnCompleted(ref t, ref dsm); } else { b.AwaitOnCompleted(ref t, ref dsm); } } b.SetResult(); ValueTask vt = b.Task; Assert.NotEqual(default, vt); Assert.True(vt.IsCompletedSuccessfully); } [Theory] [InlineData(1, false)] [InlineData(2, false)] [InlineData(1, true)] [InlineData(2, true)] public void Generic_AwaitOnCompleted_ForcesTaskCreation(int numAwaits, bool awaitUnsafe) { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); var dsm = new DelegateStateMachine(); TaskAwaiter<int> t = new TaskCompletionSource<int>().Task.GetAwaiter(); Assert.InRange(numAwaits, 1, int.MaxValue); for (int i = 1; i <= numAwaits; i++) { if (awaitUnsafe) { b.AwaitUnsafeOnCompleted(ref t, ref dsm); } else { b.AwaitOnCompleted(ref t, ref dsm); } } b.SetResult(42); ValueTask<int> vt = b.Task; Assert.NotEqual(default, vt); Assert.True(vt.IsCompletedSuccessfully); Assert.Equal(42, vt.Result); } [Fact] public void NonGeneric_SetStateMachine_InvalidArgument_ThrowsException() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); AssertExtensions.Throws<ArgumentNullException>("stateMachine", () => b.SetStateMachine(null)); } [Fact] public void Generic_SetStateMachine_InvalidArgument_ThrowsException() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); AssertExtensions.Throws<ArgumentNullException>("stateMachine", () => b.SetStateMachine(null)); } [Fact] public void NonGeneric_Start_ExecutionContextChangesInMoveNextDontFlowOut() { var al = new AsyncLocal<int> { Value = 0 }; int calls = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => { al.Value++; calls++; } }; dsm.MoveNext(); Assert.Equal(1, al.Value); Assert.Equal(1, calls); dsm.MoveNext(); Assert.Equal(2, al.Value); Assert.Equal(2, calls); AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); b.Start(ref dsm); Assert.Equal(2, al.Value); // change should not be visible Assert.Equal(3, calls); // Make sure we've not caused the Task to be allocated b.SetResult(); Assert.Equal(default, b.Task); } [Fact] public void Generic_Start_ExecutionContextChangesInMoveNextDontFlowOut() { var al = new AsyncLocal<int> { Value = 0 }; int calls = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => { al.Value++; calls++; } }; dsm.MoveNext(); Assert.Equal(1, al.Value); Assert.Equal(1, calls); dsm.MoveNext(); Assert.Equal(2, al.Value); Assert.Equal(2, calls); AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); b.Start(ref dsm); Assert.Equal(2, al.Value); // change should not be visible Assert.Equal(3, calls); // Make sure we've not caused the Task to be allocated b.SetResult(42); Assert.Equal(new ValueTask<int>(42), b.Task); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(10)] public static async Task NonGeneric_UsedWithAsyncMethod_CompletesSuccessfully(int yields) { StrongBox<int> result; result = new StrongBox<int>(); await ValueTaskReturningAsyncMethod(42, result); Assert.Equal(42 + yields, result.Value); result = new StrongBox<int>(); await ValueTaskReturningAsyncMethod(84, result); Assert.Equal(84 + yields, result.Value); async ValueTask ValueTaskReturningAsyncMethod(int result, StrongBox<int> output) { for (int i = 0; i < yields; i++) { await Task.Yield(); result++; } output.Value = result; } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(10)] public static async Task Generic_UsedWithAsyncMethod_CompletesSuccessfully(int yields) { Assert.Equal(42 + yields, await ValueTaskReturningAsyncMethod(42)); Assert.Equal(84 + yields, await ValueTaskReturningAsyncMethod(84)); async ValueTask<int> ValueTaskReturningAsyncMethod(int result) { for (int i = 0; i < yields; i++) { await Task.Yield(); result++; } return result; } } [Fact] public static async Task AwaitTasksAndValueTasks_InTaskAndValueTaskMethods() { for (int i = 0; i < 2; i++) { await TaskReturningMethod(); Assert.Equal(17, await TaskInt32ReturningMethod()); await ValueTaskReturningMethod(); Assert.Equal(18, await ValueTaskInt32ReturningMethod()); } async Task TaskReturningMethod() { for (int i = 0; i < 3; i++) { // Complete await Task.CompletedTask; await Task.FromResult(42); await new ValueTask(); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(42)); Assert.Equal(42, await new ValueTask<int>(Task.FromResult(42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); // Incomplete await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.Delay(1).ContinueWith(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(Task.Delay(1).ContinueWith(_ => 42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.Delay(1).ContinueWith<int>(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); await Task.Yield(); } } async Task<int> TaskInt32ReturningMethod() { for (int i = 0; i < 3; i++) { // Complete await Task.CompletedTask; await Task.FromResult(42); await new ValueTask(); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(42)); Assert.Equal(42, await new ValueTask<int>(Task.FromResult(42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); // Incomplete await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.Delay(1).ContinueWith(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(Task.Delay(1).ContinueWith(_ => 42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.Delay(1).ContinueWith<int>(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); await Task.Yield(); } return 17; } async ValueTask ValueTaskReturningMethod() { for (int i = 0; i < 3; i++) { // Complete await Task.CompletedTask; await Task.FromResult(42); await new ValueTask(); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(42)); Assert.Equal(42, await new ValueTask<int>(Task.FromResult(42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); // Incomplete await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.Delay(1).ContinueWith(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(Task.Delay(1).ContinueWith(_ => 42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.Delay(1).ContinueWith<int>(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); await Task.Yield(); } } async ValueTask<int> ValueTaskInt32ReturningMethod() { for (int i = 0; i < 3; i++) { // Complete await Task.CompletedTask; await Task.FromResult(42); await new ValueTask(); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(42)); Assert.Equal(42, await new ValueTask<int>(Task.FromResult(42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); // Incomplete await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.Delay(1).ContinueWith(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(Task.Delay(1).ContinueWith(_ => 42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.Delay(1).ContinueWith<int>(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); await Task.Yield(); } return 18; } } [Fact] public async Task NonGeneric_ConcurrentBuilders_WorkCorrectly() { await Task.WhenAll(Enumerable.Range(0, Environment.ProcessorCount).Select(async _ => { for (int i = 0; i < 10; i++) { await ValueTaskAsync(); static async ValueTask ValueTaskAsync() { await Task.Delay(1); } } })); } [Fact] public async Task Generic_ConcurrentBuilders_WorkCorrectly() { await Task.WhenAll(Enumerable.Range(0, Environment.ProcessorCount).Select(async _ => { for (int i = 0; i < 10; i++) { Assert.Equal(42 + i, await ValueTaskAsync(i)); static async ValueTask<int> ValueTaskAsync(int i) { await Task.Delay(1); return 42 + i; } } })); } private struct DelegateStateMachine : IAsyncStateMachine { internal Action MoveNextDelegate; public void MoveNext() => MoveNextDelegate?.Invoke(); public void SetStateMachine(IAsyncStateMachine stateMachine) { } } } }
// 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.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks.Sources.Tests; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Threading.Tasks.Tests { public class AsyncValueTaskMethodBuilderTests { [Fact] public void Create_ReturnsDefaultInstance() // implementation detail being verified { Assert.Equal(default, AsyncValueTaskMethodBuilder.Create()); Assert.Equal(default, AsyncValueTaskMethodBuilder<int>.Create()); } [Fact] public void NonGeneric_SetResult_BeforeAccessTask_ValueTaskIsDefault() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); b.SetResult(); Assert.Equal(default, b.Task); } [Fact] public void Generic_SetResult_BeforeAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); b.SetResult(42); ValueTask<int> vt = b.Task; Assert.Equal(vt, b.Task); Assert.Equal(new ValueTask<int>(42), vt); } [Fact] public void NonGeneric_SetResult_AfterAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); ValueTask vt = b.Task; Assert.NotEqual(default, vt); Assert.Equal(vt, b.Task); b.SetResult(); Assert.Equal(vt, b.Task); Assert.True(vt.IsCompletedSuccessfully); } [Fact] public void Generic_SetResult_AfterAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); ValueTask<int> vt = b.Task; Assert.NotEqual(default, vt); Assert.Equal(vt, b.Task); b.SetResult(42); Assert.Equal(vt, b.Task); Assert.True(vt.IsCompletedSuccessfully); Assert.Equal(42, vt.Result); } [Fact] public void NonGeneric_SetException_BeforeAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); var e = new FormatException(); b.SetException(e); ValueTask vt = b.Task; Assert.Equal(vt, b.Task); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void Generic_SetException_BeforeAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); var e = new FormatException(); b.SetException(e); ValueTask<int> vt = b.Task; Assert.Equal(vt, b.Task); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void NonGeneric_SetException_AfterAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); ValueTask vt = b.Task; Assert.Equal(vt, b.Task); var e = new FormatException(); b.SetException(e); Assert.Equal(vt, b.Task); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void Generic_SetException_AfterAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); ValueTask<int> vt = b.Task; Assert.Equal(vt, b.Task); var e = new FormatException(); b.SetException(e); Assert.Equal(vt, b.Task); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void NonGeneric_SetException_OperationCanceledException_CancelsTask() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); ValueTask vt = b.Task; Assert.Equal(vt, b.Task); var e = new OperationCanceledException(); b.SetException(e); Assert.Equal(vt, b.Task); Assert.True(vt.IsCanceled); Assert.Same(e, Assert.Throws<OperationCanceledException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void Generic_SetException_OperationCanceledException_CancelsTask() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); ValueTask<int> vt = b.Task; Assert.Equal(vt, b.Task); var e = new OperationCanceledException(); b.SetException(e); Assert.Equal(vt, b.Task); Assert.True(vt.IsCanceled); Assert.Same(e, Assert.Throws<OperationCanceledException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void NonGeneric_SetExceptionWithNullException_Throws() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); AssertExtensions.Throws<ArgumentNullException>("exception", () => b.SetException(null)); } [Fact] public void Generic_SetExceptionWithNullException_Throws() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); AssertExtensions.Throws<ArgumentNullException>("exception", () => b.SetException(null)); } [Fact] public void NonGeneric_Start_InvokesMoveNext() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); int invokes = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => invokes++ }; b.Start(ref dsm); Assert.Equal(1, invokes); } [Fact] public void Generic_Start_InvokesMoveNext() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); int invokes = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => invokes++ }; b.Start(ref dsm); Assert.Equal(1, invokes); } [Theory] [InlineData(1, false)] [InlineData(2, false)] [InlineData(1, true)] [InlineData(2, true)] public void NonGeneric_AwaitOnCompleted_ForcesTaskCreation(int numAwaits, bool awaitUnsafe) { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); var dsm = new DelegateStateMachine(); TaskAwaiter<int> t = new TaskCompletionSource<int>().Task.GetAwaiter(); Assert.InRange(numAwaits, 1, int.MaxValue); for (int i = 1; i <= numAwaits; i++) { if (awaitUnsafe) { b.AwaitUnsafeOnCompleted(ref t, ref dsm); } else { b.AwaitOnCompleted(ref t, ref dsm); } } b.SetResult(); ValueTask vt = b.Task; Assert.NotEqual(default, vt); Assert.True(vt.IsCompletedSuccessfully); } [Theory] [InlineData(1, false)] [InlineData(2, false)] [InlineData(1, true)] [InlineData(2, true)] public void Generic_AwaitOnCompleted_ForcesTaskCreation(int numAwaits, bool awaitUnsafe) { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); var dsm = new DelegateStateMachine(); TaskAwaiter<int> t = new TaskCompletionSource<int>().Task.GetAwaiter(); Assert.InRange(numAwaits, 1, int.MaxValue); for (int i = 1; i <= numAwaits; i++) { if (awaitUnsafe) { b.AwaitUnsafeOnCompleted(ref t, ref dsm); } else { b.AwaitOnCompleted(ref t, ref dsm); } } b.SetResult(42); ValueTask<int> vt = b.Task; Assert.NotEqual(default, vt); Assert.True(vt.IsCompletedSuccessfully); Assert.Equal(42, vt.Result); } [Fact] public void NonGeneric_SetStateMachine_InvalidArgument_ThrowsException() { AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); AssertExtensions.Throws<ArgumentNullException>("stateMachine", () => b.SetStateMachine(null)); } [Fact] public void Generic_SetStateMachine_InvalidArgument_ThrowsException() { AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); AssertExtensions.Throws<ArgumentNullException>("stateMachine", () => b.SetStateMachine(null)); } [Fact] public void NonGeneric_Start_ExecutionContextChangesInMoveNextDontFlowOut() { var al = new AsyncLocal<int> { Value = 0 }; int calls = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => { al.Value++; calls++; } }; dsm.MoveNext(); Assert.Equal(1, al.Value); Assert.Equal(1, calls); dsm.MoveNext(); Assert.Equal(2, al.Value); Assert.Equal(2, calls); AsyncValueTaskMethodBuilder b = AsyncValueTaskMethodBuilder.Create(); b.Start(ref dsm); Assert.Equal(2, al.Value); // change should not be visible Assert.Equal(3, calls); // Make sure we've not caused the Task to be allocated b.SetResult(); Assert.Equal(default, b.Task); } [Fact] public void Generic_Start_ExecutionContextChangesInMoveNextDontFlowOut() { var al = new AsyncLocal<int> { Value = 0 }; int calls = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => { al.Value++; calls++; } }; dsm.MoveNext(); Assert.Equal(1, al.Value); Assert.Equal(1, calls); dsm.MoveNext(); Assert.Equal(2, al.Value); Assert.Equal(2, calls); AsyncValueTaskMethodBuilder<int> b = AsyncValueTaskMethodBuilder<int>.Create(); b.Start(ref dsm); Assert.Equal(2, al.Value); // change should not be visible Assert.Equal(3, calls); // Make sure we've not caused the Task to be allocated b.SetResult(42); Assert.Equal(new ValueTask<int>(42), b.Task); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(10)] public static async Task NonGeneric_UsedWithAsyncMethod_CompletesSuccessfully(int yields) { StrongBox<int> result; result = new StrongBox<int>(); await ValueTaskReturningAsyncMethod(42, result); Assert.Equal(42 + yields, result.Value); result = new StrongBox<int>(); await ValueTaskReturningAsyncMethod(84, result); Assert.Equal(84 + yields, result.Value); async ValueTask ValueTaskReturningAsyncMethod(int result, StrongBox<int> output) { for (int i = 0; i < yields; i++) { await Task.Yield(); result++; } output.Value = result; } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(10)] public static async Task Generic_UsedWithAsyncMethod_CompletesSuccessfully(int yields) { Assert.Equal(42 + yields, await ValueTaskReturningAsyncMethod(42)); Assert.Equal(84 + yields, await ValueTaskReturningAsyncMethod(84)); async ValueTask<int> ValueTaskReturningAsyncMethod(int result) { for (int i = 0; i < yields; i++) { await Task.Yield(); result++; } return result; } } [Fact] public static async Task AwaitTasksAndValueTasks_InTaskAndValueTaskMethods() { for (int i = 0; i < 2; i++) { await TaskReturningMethod(); Assert.Equal(17, await TaskInt32ReturningMethod()); await ValueTaskReturningMethod(); Assert.Equal(18, await ValueTaskInt32ReturningMethod()); } async Task TaskReturningMethod() { for (int i = 0; i < 3; i++) { // Complete await Task.CompletedTask; await Task.FromResult(42); await new ValueTask(); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(42)); Assert.Equal(42, await new ValueTask<int>(Task.FromResult(42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); // Incomplete await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.Delay(1).ContinueWith(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(Task.Delay(1).ContinueWith(_ => 42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.Delay(1).ContinueWith<int>(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); await Task.Yield(); } } async Task<int> TaskInt32ReturningMethod() { for (int i = 0; i < 3; i++) { // Complete await Task.CompletedTask; await Task.FromResult(42); await new ValueTask(); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(42)); Assert.Equal(42, await new ValueTask<int>(Task.FromResult(42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); // Incomplete await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.Delay(1).ContinueWith(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(Task.Delay(1).ContinueWith(_ => 42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.Delay(1).ContinueWith<int>(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); await Task.Yield(); } return 17; } async ValueTask ValueTaskReturningMethod() { for (int i = 0; i < 3; i++) { // Complete await Task.CompletedTask; await Task.FromResult(42); await new ValueTask(); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(42)); Assert.Equal(42, await new ValueTask<int>(Task.FromResult(42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); // Incomplete await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.Delay(1).ContinueWith(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(Task.Delay(1).ContinueWith(_ => 42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.Delay(1).ContinueWith<int>(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); await Task.Yield(); } } async ValueTask<int> ValueTaskInt32ReturningMethod() { for (int i = 0; i < 3; i++) { // Complete await Task.CompletedTask; await Task.FromResult(42); await new ValueTask(); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(42)); Assert.Equal(42, await new ValueTask<int>(Task.FromResult(42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.FromException<int>(new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Completed(0, new FormatException()), 0)); // Incomplete await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(Task.Delay(1).ContinueWith(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); Assert.Equal(42, await new ValueTask<int>(Task.Delay(1).ContinueWith(_ => 42))); Assert.Equal(42, await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 42, null), 0)); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(Task.Delay(1).ContinueWith<int>(_ => throw new FormatException()))); await Assert.ThrowsAsync<FormatException>(async () => await new ValueTask<int>(ManualResetValueTaskSourceFactory.Delay(1, 0, new FormatException()), 0)); await Task.Yield(); } return 18; } } [Fact] public async Task NonGeneric_ConcurrentBuilders_WorkCorrectly() { await Task.WhenAll(Enumerable.Range(0, Environment.ProcessorCount).Select(async _ => { for (int i = 0; i < 10; i++) { await ValueTaskAsync(); static async ValueTask ValueTaskAsync() { await Task.Delay(1); } } })); } [Fact] public async Task Generic_ConcurrentBuilders_WorkCorrectly() { await Task.WhenAll(Enumerable.Range(0, Environment.ProcessorCount).Select(async _ => { for (int i = 0; i < 10; i++) { Assert.Equal(42 + i, await ValueTaskAsync(i)); static async ValueTask<int> ValueTaskAsync(int i) { await Task.Delay(1); return 42 + i; } } })); } private struct DelegateStateMachine : IAsyncStateMachine { internal Action MoveNextDelegate; public void MoveNext() => MoveNextDelegate?.Invoke(); public void SetStateMachine(IAsyncStateMachine stateMachine) { } } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonNode/ParseTests.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.IO; using System.Reflection; using System.Text.Json.Serialization.Tests; using Xunit; namespace System.Text.Json.Nodes.Tests { public static class ParseTests { [Fact] public static void Parse() { JsonObject jObject = JsonNode.Parse(JsonNodeTests.ExpectedDomJson).AsObject(); Assert.Equal("Hello!", jObject["MyString"].GetValue<string>()); Assert.Null(jObject["MyNull"]); Assert.False(jObject["MyBoolean"].GetValue<bool>()); Assert.Equal("ed957609-cdfe-412f-88c1-02daca1b4f51", jObject["MyGuid"].GetValue<string>()); Assert.IsType<JsonArray>(jObject["MyArray"]); Assert.IsType<JsonObject>(jObject["MyObject"]); Assert.Equal(43, jObject["MyInt"].GetValue<int>()); Assert.Equal<uint>(43, jObject["MyInt"].GetValue<uint>()); Assert.Equal(43, jObject["MyInt"].GetValue<long>()); Assert.Equal<ulong>(43, jObject["MyInt"].GetValue<ulong>()); Assert.Equal(43, jObject["MyInt"].GetValue<short>()); Assert.Equal<ushort>(43, jObject["MyInt"].GetValue<ushort>()); Assert.Equal(43, jObject["MyInt"].GetValue<byte>()); Assert.Equal(43, jObject["MyInt"].GetValue<sbyte>()); Assert.Equal(43, jObject["MyInt"].GetValue<decimal>()); Assert.Equal(43, jObject["MyInt"].GetValue<float>()); DateTime dt = JsonNode.Parse("\"2020-07-08T01:02:03\"").GetValue<DateTime>(); Assert.Equal(2020, dt.Year); Assert.Equal(7, dt.Month); Assert.Equal(8, dt.Day); Assert.Equal(1, dt.Hour); Assert.Equal(2, dt.Minute); Assert.Equal(3, dt.Second); DateTimeOffset dtOffset = JsonNode.Parse("\"2020-07-08T01:02:03+01:15\"").GetValue<DateTimeOffset>(); Assert.Equal(2020, dtOffset.Year); Assert.Equal(7, dtOffset.Month); Assert.Equal(8, dtOffset.Day); Assert.Equal(1, dtOffset.Hour); Assert.Equal(2, dtOffset.Minute); Assert.Equal(3, dtOffset.Second); Assert.Equal(new TimeSpan(1,15,0), dtOffset.Offset); } [Fact] public static void Parse_TryGetPropertyValue() { JsonObject jObject = JsonNode.Parse(JsonNodeTests.ExpectedDomJson).AsObject(); JsonNode? node; Assert.True(jObject.TryGetPropertyValue("MyString", out node)); Assert.Equal("Hello!", node.GetValue<string>()); Assert.True(jObject.TryGetPropertyValue("MyNull", out node)); Assert.Null(node); Assert.True(jObject.TryGetPropertyValue("MyBoolean", out node)); Assert.False(node.GetValue<bool>()); Assert.True(jObject.TryGetPropertyValue("MyArray", out node)); Assert.IsType<JsonArray>(node); Assert.True(jObject.TryGetPropertyValue("MyInt", out node)); Assert.Equal(43, node.GetValue<int>()); Assert.True(jObject.TryGetPropertyValue("MyDateTime", out node)); Assert.Equal("2020-07-08T00:00:00", node.GetValue<string>()); Assert.True(jObject.TryGetPropertyValue("MyGuid", out node)); Assert.Equal("ed957609-cdfe-412f-88c1-02daca1b4f51", node.AsValue().GetValue<Guid>().ToString()); Assert.True(jObject.TryGetPropertyValue("MyObject", out node)); Assert.IsType<JsonObject>(node); } [Fact] public static void Parse_TryGetValue() { Assert.True(JsonNode.Parse("\"Hello\"").AsValue().TryGetValue(out string? _)); Assert.True(JsonNode.Parse("true").AsValue().TryGetValue(out bool? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out byte? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out sbyte? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out short? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out ushort? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out int? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out uint? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out long? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out ulong? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out decimal? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out float? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out double? _)); Assert.True(JsonNode.Parse("\"2020-07-08T00:00:00\"").AsValue().TryGetValue(out DateTime? _)); Assert.True(JsonNode.Parse("\"ed957609-cdfe-412f-88c1-02daca1b4f51\"").AsValue().TryGetValue(out Guid? _)); Assert.True(JsonNode.Parse("\"2020-07-08T01:02:03+01:15\"").AsValue().TryGetValue(out DateTimeOffset? _)); JsonValue? jValue = JsonNode.Parse("\"Hello!\"").AsValue(); Assert.False(jValue.TryGetValue(out int _)); Assert.False(jValue.TryGetValue(out DateTime _)); Assert.False(jValue.TryGetValue(out DateTimeOffset _)); Assert.False(jValue.TryGetValue(out Guid _)); } [Fact] public static void Parse_Fail() { JsonObject jObject = JsonNode.Parse(JsonNodeTests.ExpectedDomJson).AsObject(); Assert.Throws<InvalidOperationException>(() => jObject["MyString"].GetValue<int>()); Assert.Throws<InvalidOperationException>(() => jObject["MyBoolean"].GetValue<int>()); Assert.Throws<InvalidOperationException>(() => jObject["MyGuid"].GetValue<int>()); Assert.Throws<InvalidOperationException>(() => jObject["MyInt"].GetValue<string>()); Assert.Throws<InvalidOperationException>(() => jObject["MyDateTime"].GetValue<int>()); Assert.Throws<InvalidOperationException>(() => jObject["MyObject"].GetValue<int>()); Assert.Throws<InvalidOperationException>(() => jObject["MyArray"].GetValue<int>()); } [Fact] public static void NullReference_Fail() { Assert.Throws<ArgumentNullException>(() => JsonSerializer.Deserialize<JsonNode>((string)null)); Assert.Throws<ArgumentNullException>(() => JsonNode.Parse((string)null)); Assert.Throws<ArgumentNullException>(() => JsonNode.Parse((Stream)null)); } [Fact] public static void NullLiteral() { Assert.Null(JsonSerializer.Deserialize<JsonNode>("null")); Assert.Null(JsonNode.Parse("null")); using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("null"))) { Assert.Null(JsonNode.Parse(stream)); } } [Fact] public static void InternalValueFields() { // Use reflection to inspect the internal state of the 3 fields that hold values. // There is not another way to verify, and using a debug watch causes nodes to be created. FieldInfo elementField = typeof(JsonObject).GetField("_jsonElement", BindingFlags.Instance | BindingFlags.NonPublic); Assert.NotNull(elementField); FieldInfo jsonDictionaryField = typeof(JsonObject).GetField("_dictionary", BindingFlags.Instance | BindingFlags.NonPublic); Assert.NotNull(jsonDictionaryField); Type jsonPropertyDictionaryType = typeof(JsonObject).Assembly.GetType("System.Text.Json.JsonPropertyDictionary`1"); Assert.NotNull(jsonPropertyDictionaryType); jsonPropertyDictionaryType = jsonPropertyDictionaryType.MakeGenericType(new Type[] { typeof(JsonNode) }); FieldInfo listField = jsonPropertyDictionaryType.GetField("_propertyList", BindingFlags.Instance | BindingFlags.NonPublic); Assert.NotNull(listField); FieldInfo dictionaryField = jsonPropertyDictionaryType.GetField("_propertyDictionary", BindingFlags.Instance | BindingFlags.NonPublic); Assert.NotNull(dictionaryField); using (MemoryStream stream = new MemoryStream(SimpleTestClass.s_data)) { // Only JsonElement is present. JsonNode node = JsonNode.Parse(stream); object jsonDictionary = jsonDictionaryField.GetValue(node); Assert.Null(jsonDictionary); // Value is null until converted from JsonElement. Assert.NotNull(elementField.GetValue(node)); Test(); // Cause the single JsonElement to expand into individual JsonElement nodes. Assert.Equal(1, node.AsObject()["MyInt16"].GetValue<int>()); Assert.Null(elementField.GetValue(node)); jsonDictionary = jsonDictionaryField.GetValue(node); Assert.NotNull(jsonDictionary); Assert.NotNull(listField.GetValue(jsonDictionary)); Assert.NotNull(dictionaryField.GetValue(jsonDictionary)); // The dictionary threshold was reached. Test(); void Test() { string actual = node.ToJsonString(); // Replace the escaped "+" sign used with DateTimeOffset. actual = actual.Replace("\\u002B", "+"); Assert.Equal(SimpleTestClass.s_json.StripWhitespace(), actual); } } } [Fact] public static void ReadSimpleObjectWithTrailingTrivia() { byte[] data = Encoding.UTF8.GetBytes(SimpleTestClass.s_json + " /* Multi\r\nLine Comment */\t"); using (MemoryStream stream = new MemoryStream(data)) { var options = new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip }; JsonNode node = JsonNode.Parse(stream, nodeOptions: null, options); string actual = node.ToJsonString(); // Replace the escaped "+" sign used with DateTimeOffset. actual = actual.Replace("\\u002B", "+"); Assert.Equal(SimpleTestClass.s_json.StripWhitespace(), actual); } } [Fact] public static void ReadPrimitives() { using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(@"1"))) { int i = JsonNode.Parse(stream).AsValue().GetValue<int>(); Assert.Equal(1, i); } } [Fact] public static void ParseThenEdit() { const string Expected = "{\"MyString\":null,\"Node\":42,\"Array\":[43],\"Value\":44,\"IntValue\":45,\"Object\":{\"Property\":46}}"; JsonNode node = JsonNode.Parse(Expected); Assert.Equal(Expected, node.ToJsonString()); // Change a primitive node["IntValue"] = 1; const string ExpectedAfterEdit1 = "{\"MyString\":null,\"Node\":42,\"Array\":[43],\"Value\":44,\"IntValue\":1,\"Object\":{\"Property\":46}}"; Assert.Equal(ExpectedAfterEdit1, node.ToJsonString()); // Change element node["Array"][0] = 2; const string ExpectedAfterEdit2 = "{\"MyString\":null,\"Node\":42,\"Array\":[2],\"Value\":44,\"IntValue\":1,\"Object\":{\"Property\":46}}"; Assert.Equal(ExpectedAfterEdit2, node.ToJsonString()); // Change property node["MyString"] = "3"; const string ExpectedAfterEdit3 = "{\"MyString\":\"3\",\"Node\":42,\"Array\":[2],\"Value\":44,\"IntValue\":1,\"Object\":{\"Property\":46}}"; Assert.Equal(ExpectedAfterEdit3, node.ToJsonString()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Reflection; using System.Text.Json.Serialization.Tests; using Xunit; namespace System.Text.Json.Nodes.Tests { public static class ParseTests { [Fact] public static void Parse() { JsonObject jObject = JsonNode.Parse(JsonNodeTests.ExpectedDomJson).AsObject(); Assert.Equal("Hello!", jObject["MyString"].GetValue<string>()); Assert.Null(jObject["MyNull"]); Assert.False(jObject["MyBoolean"].GetValue<bool>()); Assert.Equal("ed957609-cdfe-412f-88c1-02daca1b4f51", jObject["MyGuid"].GetValue<string>()); Assert.IsType<JsonArray>(jObject["MyArray"]); Assert.IsType<JsonObject>(jObject["MyObject"]); Assert.Equal(43, jObject["MyInt"].GetValue<int>()); Assert.Equal<uint>(43, jObject["MyInt"].GetValue<uint>()); Assert.Equal(43, jObject["MyInt"].GetValue<long>()); Assert.Equal<ulong>(43, jObject["MyInt"].GetValue<ulong>()); Assert.Equal(43, jObject["MyInt"].GetValue<short>()); Assert.Equal<ushort>(43, jObject["MyInt"].GetValue<ushort>()); Assert.Equal(43, jObject["MyInt"].GetValue<byte>()); Assert.Equal(43, jObject["MyInt"].GetValue<sbyte>()); Assert.Equal(43, jObject["MyInt"].GetValue<decimal>()); Assert.Equal(43, jObject["MyInt"].GetValue<float>()); DateTime dt = JsonNode.Parse("\"2020-07-08T01:02:03\"").GetValue<DateTime>(); Assert.Equal(2020, dt.Year); Assert.Equal(7, dt.Month); Assert.Equal(8, dt.Day); Assert.Equal(1, dt.Hour); Assert.Equal(2, dt.Minute); Assert.Equal(3, dt.Second); DateTimeOffset dtOffset = JsonNode.Parse("\"2020-07-08T01:02:03+01:15\"").GetValue<DateTimeOffset>(); Assert.Equal(2020, dtOffset.Year); Assert.Equal(7, dtOffset.Month); Assert.Equal(8, dtOffset.Day); Assert.Equal(1, dtOffset.Hour); Assert.Equal(2, dtOffset.Minute); Assert.Equal(3, dtOffset.Second); Assert.Equal(new TimeSpan(1,15,0), dtOffset.Offset); } [Fact] public static void Parse_TryGetPropertyValue() { JsonObject jObject = JsonNode.Parse(JsonNodeTests.ExpectedDomJson).AsObject(); JsonNode? node; Assert.True(jObject.TryGetPropertyValue("MyString", out node)); Assert.Equal("Hello!", node.GetValue<string>()); Assert.True(jObject.TryGetPropertyValue("MyNull", out node)); Assert.Null(node); Assert.True(jObject.TryGetPropertyValue("MyBoolean", out node)); Assert.False(node.GetValue<bool>()); Assert.True(jObject.TryGetPropertyValue("MyArray", out node)); Assert.IsType<JsonArray>(node); Assert.True(jObject.TryGetPropertyValue("MyInt", out node)); Assert.Equal(43, node.GetValue<int>()); Assert.True(jObject.TryGetPropertyValue("MyDateTime", out node)); Assert.Equal("2020-07-08T00:00:00", node.GetValue<string>()); Assert.True(jObject.TryGetPropertyValue("MyGuid", out node)); Assert.Equal("ed957609-cdfe-412f-88c1-02daca1b4f51", node.AsValue().GetValue<Guid>().ToString()); Assert.True(jObject.TryGetPropertyValue("MyObject", out node)); Assert.IsType<JsonObject>(node); } [Fact] public static void Parse_TryGetValue() { Assert.True(JsonNode.Parse("\"Hello\"").AsValue().TryGetValue(out string? _)); Assert.True(JsonNode.Parse("true").AsValue().TryGetValue(out bool? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out byte? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out sbyte? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out short? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out ushort? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out int? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out uint? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out long? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out ulong? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out decimal? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out float? _)); Assert.True(JsonNode.Parse("42").AsValue().TryGetValue(out double? _)); Assert.True(JsonNode.Parse("\"2020-07-08T00:00:00\"").AsValue().TryGetValue(out DateTime? _)); Assert.True(JsonNode.Parse("\"ed957609-cdfe-412f-88c1-02daca1b4f51\"").AsValue().TryGetValue(out Guid? _)); Assert.True(JsonNode.Parse("\"2020-07-08T01:02:03+01:15\"").AsValue().TryGetValue(out DateTimeOffset? _)); JsonValue? jValue = JsonNode.Parse("\"Hello!\"").AsValue(); Assert.False(jValue.TryGetValue(out int _)); Assert.False(jValue.TryGetValue(out DateTime _)); Assert.False(jValue.TryGetValue(out DateTimeOffset _)); Assert.False(jValue.TryGetValue(out Guid _)); } [Fact] public static void Parse_Fail() { JsonObject jObject = JsonNode.Parse(JsonNodeTests.ExpectedDomJson).AsObject(); Assert.Throws<InvalidOperationException>(() => jObject["MyString"].GetValue<int>()); Assert.Throws<InvalidOperationException>(() => jObject["MyBoolean"].GetValue<int>()); Assert.Throws<InvalidOperationException>(() => jObject["MyGuid"].GetValue<int>()); Assert.Throws<InvalidOperationException>(() => jObject["MyInt"].GetValue<string>()); Assert.Throws<InvalidOperationException>(() => jObject["MyDateTime"].GetValue<int>()); Assert.Throws<InvalidOperationException>(() => jObject["MyObject"].GetValue<int>()); Assert.Throws<InvalidOperationException>(() => jObject["MyArray"].GetValue<int>()); } [Fact] public static void NullReference_Fail() { Assert.Throws<ArgumentNullException>(() => JsonSerializer.Deserialize<JsonNode>((string)null)); Assert.Throws<ArgumentNullException>(() => JsonNode.Parse((string)null)); Assert.Throws<ArgumentNullException>(() => JsonNode.Parse((Stream)null)); } [Fact] public static void NullLiteral() { Assert.Null(JsonSerializer.Deserialize<JsonNode>("null")); Assert.Null(JsonNode.Parse("null")); using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("null"))) { Assert.Null(JsonNode.Parse(stream)); } } [Fact] public static void InternalValueFields() { // Use reflection to inspect the internal state of the 3 fields that hold values. // There is not another way to verify, and using a debug watch causes nodes to be created. FieldInfo elementField = typeof(JsonObject).GetField("_jsonElement", BindingFlags.Instance | BindingFlags.NonPublic); Assert.NotNull(elementField); FieldInfo jsonDictionaryField = typeof(JsonObject).GetField("_dictionary", BindingFlags.Instance | BindingFlags.NonPublic); Assert.NotNull(jsonDictionaryField); Type jsonPropertyDictionaryType = typeof(JsonObject).Assembly.GetType("System.Text.Json.JsonPropertyDictionary`1"); Assert.NotNull(jsonPropertyDictionaryType); jsonPropertyDictionaryType = jsonPropertyDictionaryType.MakeGenericType(new Type[] { typeof(JsonNode) }); FieldInfo listField = jsonPropertyDictionaryType.GetField("_propertyList", BindingFlags.Instance | BindingFlags.NonPublic); Assert.NotNull(listField); FieldInfo dictionaryField = jsonPropertyDictionaryType.GetField("_propertyDictionary", BindingFlags.Instance | BindingFlags.NonPublic); Assert.NotNull(dictionaryField); using (MemoryStream stream = new MemoryStream(SimpleTestClass.s_data)) { // Only JsonElement is present. JsonNode node = JsonNode.Parse(stream); object jsonDictionary = jsonDictionaryField.GetValue(node); Assert.Null(jsonDictionary); // Value is null until converted from JsonElement. Assert.NotNull(elementField.GetValue(node)); Test(); // Cause the single JsonElement to expand into individual JsonElement nodes. Assert.Equal(1, node.AsObject()["MyInt16"].GetValue<int>()); Assert.Null(elementField.GetValue(node)); jsonDictionary = jsonDictionaryField.GetValue(node); Assert.NotNull(jsonDictionary); Assert.NotNull(listField.GetValue(jsonDictionary)); Assert.NotNull(dictionaryField.GetValue(jsonDictionary)); // The dictionary threshold was reached. Test(); void Test() { string actual = node.ToJsonString(); // Replace the escaped "+" sign used with DateTimeOffset. actual = actual.Replace("\\u002B", "+"); Assert.Equal(SimpleTestClass.s_json.StripWhitespace(), actual); } } } [Fact] public static void ReadSimpleObjectWithTrailingTrivia() { byte[] data = Encoding.UTF8.GetBytes(SimpleTestClass.s_json + " /* Multi\r\nLine Comment */\t"); using (MemoryStream stream = new MemoryStream(data)) { var options = new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip }; JsonNode node = JsonNode.Parse(stream, nodeOptions: null, options); string actual = node.ToJsonString(); // Replace the escaped "+" sign used with DateTimeOffset. actual = actual.Replace("\\u002B", "+"); Assert.Equal(SimpleTestClass.s_json.StripWhitespace(), actual); } } [Fact] public static void ReadPrimitives() { using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(@"1"))) { int i = JsonNode.Parse(stream).AsValue().GetValue<int>(); Assert.Equal(1, i); } } [Fact] public static void ParseThenEdit() { const string Expected = "{\"MyString\":null,\"Node\":42,\"Array\":[43],\"Value\":44,\"IntValue\":45,\"Object\":{\"Property\":46}}"; JsonNode node = JsonNode.Parse(Expected); Assert.Equal(Expected, node.ToJsonString()); // Change a primitive node["IntValue"] = 1; const string ExpectedAfterEdit1 = "{\"MyString\":null,\"Node\":42,\"Array\":[43],\"Value\":44,\"IntValue\":1,\"Object\":{\"Property\":46}}"; Assert.Equal(ExpectedAfterEdit1, node.ToJsonString()); // Change element node["Array"][0] = 2; const string ExpectedAfterEdit2 = "{\"MyString\":null,\"Node\":42,\"Array\":[2],\"Value\":44,\"IntValue\":1,\"Object\":{\"Property\":46}}"; Assert.Equal(ExpectedAfterEdit2, node.ToJsonString()); // Change property node["MyString"] = "3"; const string ExpectedAfterEdit3 = "{\"MyString\":\"3\",\"Node\":42,\"Array\":[2],\"Value\":44,\"IntValue\":1,\"Object\":{\"Property\":46}}"; Assert.Equal(ExpectedAfterEdit3, node.ToJsonString()); } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncTaskMethodBuilder.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.Threading.Tasks; namespace System.Runtime.CompilerServices { /// <summary> /// Provides a builder for asynchronous methods that return <see cref="System.Threading.Tasks.Task"/>. /// This type is intended for compiler use only. /// </summary> /// <remarks> /// AsyncTaskMethodBuilder is a value type, and thus it is copied by value. /// Prior to being copied, one of its Task, SetResult, or SetException members must be accessed, /// or else the copies may end up building distinct Task instances. /// </remarks> public struct AsyncTaskMethodBuilder { /// <summary>The lazily-initialized built task.</summary> private Task<VoidTaskResult>? m_task; // Debugger depends on the exact name of this field. /// <summary>Initializes a new <see cref="AsyncTaskMethodBuilder"/>.</summary> /// <returns>The initialized <see cref="AsyncTaskMethodBuilder"/>.</returns> public static AsyncTaskMethodBuilder Create() => default; /// <summary>Initiates the builder's execution with the associated state machine.</summary> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="stateMachine">The state machine instance, passed by reference.</param> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine => AsyncMethodBuilderCore.Start(ref stateMachine); /// <summary>Associates the builder with the state machine it represents.</summary> /// <param name="stateMachine">The heap-allocated state machine object.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The builder is incorrectly initialized.</exception> public void SetStateMachine(IAsyncStateMachine stateMachine) => AsyncMethodBuilderCore.SetStateMachine(stateMachine, task: null); /// <summary> /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// </summary> /// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> public void AwaitOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine => AsyncTaskMethodBuilder<VoidTaskResult>.AwaitOnCompleted(ref awaiter, ref stateMachine, ref m_task); /// <summary> /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// </summary> /// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine => AsyncTaskMethodBuilder<VoidTaskResult>.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine, ref m_task); /// <summary>Gets the <see cref="System.Threading.Tasks.Task"/> for this builder.</summary> /// <returns>The <see cref="System.Threading.Tasks.Task"/> representing the builder's asynchronous operation.</returns> /// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception> public Task Task { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => m_task ?? InitializeTaskAsPromise(); } /// <summary> /// Initializes the task, which must not yet be initialized. Used only when the Task is being forced into /// existence when no state machine is needed, e.g. when the builder is being synchronously completed with /// an exception, when the builder is being used out of the context of an async method, etc. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] private Task<VoidTaskResult> InitializeTaskAsPromise() { Debug.Assert(m_task == null); return m_task = new Task<VoidTaskResult>(); } /// <summary> /// Completes the <see cref="System.Threading.Tasks.Task"/> in the /// <see cref="System.Threading.Tasks.TaskStatus">RanToCompletion</see> state. /// </summary> /// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception> /// <exception cref="System.InvalidOperationException">The task has already completed.</exception> public void SetResult() { // Get the currently stored task, which will be non-null if get_Task has already been accessed. // If there isn't one, store the supplied completed task. if (m_task is null) { m_task = Task.s_cachedCompleted; } else { // Otherwise, complete the task that's there. AsyncTaskMethodBuilder<VoidTaskResult>.SetExistingTaskResult(m_task, default!); } } /// <summary> /// Completes the <see cref="System.Threading.Tasks.Task"/> in the /// <see cref="System.Threading.Tasks.TaskStatus">Faulted</see> state with the specified exception. /// </summary> /// <param name="exception">The <see cref="System.Exception"/> to use to fault the task.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="exception"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception> /// <exception cref="System.InvalidOperationException">The task has already completed.</exception> public void SetException(Exception exception) => AsyncTaskMethodBuilder<VoidTaskResult>.SetException(exception, ref m_task); /// <summary> /// Called by the debugger to request notification when the first wait operation /// (await, Wait, Result, etc.) on this builder's task completes. /// </summary> /// <param name="enabled"> /// true to enable notification; false to disable a previously set notification. /// </param> internal void SetNotificationForWaitCompletion(bool enabled) => AsyncTaskMethodBuilder<VoidTaskResult>.SetNotificationForWaitCompletion(enabled, ref m_task); /// <summary> /// Gets an object that may be used to uniquely identify this builder to the debugger. /// </summary> /// <remarks> /// This property lazily instantiates the ID in a non-thread-safe manner. /// It must only be used by the debugger and tracing purposes, and only in a single-threaded manner /// when no other threads are in the middle of accessing this property or this.Task. /// </remarks> internal object ObjectIdForDebugger => m_task ??= AsyncTaskMethodBuilder<VoidTaskResult>.CreateWeaklyTypedStateMachineBox(); } }
// 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.Threading.Tasks; namespace System.Runtime.CompilerServices { /// <summary> /// Provides a builder for asynchronous methods that return <see cref="System.Threading.Tasks.Task"/>. /// This type is intended for compiler use only. /// </summary> /// <remarks> /// AsyncTaskMethodBuilder is a value type, and thus it is copied by value. /// Prior to being copied, one of its Task, SetResult, or SetException members must be accessed, /// or else the copies may end up building distinct Task instances. /// </remarks> public struct AsyncTaskMethodBuilder { /// <summary>The lazily-initialized built task.</summary> private Task<VoidTaskResult>? m_task; // Debugger depends on the exact name of this field. /// <summary>Initializes a new <see cref="AsyncTaskMethodBuilder"/>.</summary> /// <returns>The initialized <see cref="AsyncTaskMethodBuilder"/>.</returns> public static AsyncTaskMethodBuilder Create() => default; /// <summary>Initiates the builder's execution with the associated state machine.</summary> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="stateMachine">The state machine instance, passed by reference.</param> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine => AsyncMethodBuilderCore.Start(ref stateMachine); /// <summary>Associates the builder with the state machine it represents.</summary> /// <param name="stateMachine">The heap-allocated state machine object.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The builder is incorrectly initialized.</exception> public void SetStateMachine(IAsyncStateMachine stateMachine) => AsyncMethodBuilderCore.SetStateMachine(stateMachine, task: null); /// <summary> /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// </summary> /// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> public void AwaitOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine => AsyncTaskMethodBuilder<VoidTaskResult>.AwaitOnCompleted(ref awaiter, ref stateMachine, ref m_task); /// <summary> /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// </summary> /// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine => AsyncTaskMethodBuilder<VoidTaskResult>.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine, ref m_task); /// <summary>Gets the <see cref="System.Threading.Tasks.Task"/> for this builder.</summary> /// <returns>The <see cref="System.Threading.Tasks.Task"/> representing the builder's asynchronous operation.</returns> /// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception> public Task Task { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => m_task ?? InitializeTaskAsPromise(); } /// <summary> /// Initializes the task, which must not yet be initialized. Used only when the Task is being forced into /// existence when no state machine is needed, e.g. when the builder is being synchronously completed with /// an exception, when the builder is being used out of the context of an async method, etc. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] private Task<VoidTaskResult> InitializeTaskAsPromise() { Debug.Assert(m_task == null); return m_task = new Task<VoidTaskResult>(); } /// <summary> /// Completes the <see cref="System.Threading.Tasks.Task"/> in the /// <see cref="System.Threading.Tasks.TaskStatus">RanToCompletion</see> state. /// </summary> /// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception> /// <exception cref="System.InvalidOperationException">The task has already completed.</exception> public void SetResult() { // Get the currently stored task, which will be non-null if get_Task has already been accessed. // If there isn't one, store the supplied completed task. if (m_task is null) { m_task = Task.s_cachedCompleted; } else { // Otherwise, complete the task that's there. AsyncTaskMethodBuilder<VoidTaskResult>.SetExistingTaskResult(m_task, default!); } } /// <summary> /// Completes the <see cref="System.Threading.Tasks.Task"/> in the /// <see cref="System.Threading.Tasks.TaskStatus">Faulted</see> state with the specified exception. /// </summary> /// <param name="exception">The <see cref="System.Exception"/> to use to fault the task.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="exception"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception> /// <exception cref="System.InvalidOperationException">The task has already completed.</exception> public void SetException(Exception exception) => AsyncTaskMethodBuilder<VoidTaskResult>.SetException(exception, ref m_task); /// <summary> /// Called by the debugger to request notification when the first wait operation /// (await, Wait, Result, etc.) on this builder's task completes. /// </summary> /// <param name="enabled"> /// true to enable notification; false to disable a previously set notification. /// </param> internal void SetNotificationForWaitCompletion(bool enabled) => AsyncTaskMethodBuilder<VoidTaskResult>.SetNotificationForWaitCompletion(enabled, ref m_task); /// <summary> /// Gets an object that may be used to uniquely identify this builder to the debugger. /// </summary> /// <remarks> /// This property lazily instantiates the ID in a non-thread-safe manner. /// It must only be used by the debugger and tracing purposes, and only in a single-threaded manner /// when no other threads are in the middle of accessing this property or this.Task. /// </remarks> internal object ObjectIdForDebugger => m_task ??= AsyncTaskMethodBuilder<VoidTaskResult>.CreateWeaklyTypedStateMachineBox(); } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/jit64/valuetypes/nullable/box-unbox/box-unbox/box-unbox002.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="box-unbox002.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-unbox002.cs" /> <Compile Include="..\structdef.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/jit64/valuetypes/nullable/box-unbox/null/box-unbox-null032.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 System; internal class NullableTest { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((NestedStruct?)o) == null; } private static int Main() { NestedStruct? s = null; if (BoxUnboxToNQ(s) && BoxUnboxToQ(s) && BoxUnboxToNQGen(s) && BoxUnboxToQGen(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
// 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 System; internal class NullableTest { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((NestedStruct?)o) == null; } private static int Main() { NestedStruct? s = null; if (BoxUnboxToNQ(s) && BoxUnboxToQ(s) && BoxUnboxToNQGen(s) && BoxUnboxToQGen(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/Interop/COM/NETServer/LicenseTesting.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.Runtime.InteropServices; [ComVisible(true)] [Guid(Server.Contract.Guids.LicenseTesting)] [LicenseProvider(typeof(MockLicenseProvider))] public class LicenseTesting : Server.Contract.ILicenseTesting { public LicenseTesting() { LicenseManager.Validate(typeof(LicenseTesting), this); } public string LicenseUsed { get; set; } void Server.Contract.ILicenseTesting.SetNextDenyLicense(bool denyLicense) { MockLicenseProvider.DenyLicense = denyLicense; } void Server.Contract.ILicenseTesting.SetNextLicense(string lic) { MockLicenseProvider.License = lic; } string Server.Contract.ILicenseTesting.GetLicense() { return LicenseUsed; } } public class MockLicenseProvider : LicenseProvider { public static bool DenyLicense { get; set; } public static string License { get; set; } public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions) { if (DenyLicense) { if (allowExceptions) { throw new LicenseException(type); } else { return null; } } if (type != typeof(LicenseTesting)) { throw new Exception(); } var lic = new MockLicense(); if (instance != null) { ((LicenseTesting)instance).LicenseUsed = lic.LicenseKey; } return lic; } private class MockLicense : License { public override string LicenseKey => MockLicenseProvider.License ?? "__MOCK_LICENSE_KEY__"; public override 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.ComponentModel; using System.Runtime.InteropServices; [ComVisible(true)] [Guid(Server.Contract.Guids.LicenseTesting)] [LicenseProvider(typeof(MockLicenseProvider))] public class LicenseTesting : Server.Contract.ILicenseTesting { public LicenseTesting() { LicenseManager.Validate(typeof(LicenseTesting), this); } public string LicenseUsed { get; set; } void Server.Contract.ILicenseTesting.SetNextDenyLicense(bool denyLicense) { MockLicenseProvider.DenyLicense = denyLicense; } void Server.Contract.ILicenseTesting.SetNextLicense(string lic) { MockLicenseProvider.License = lic; } string Server.Contract.ILicenseTesting.GetLicense() { return LicenseUsed; } } public class MockLicenseProvider : LicenseProvider { public static bool DenyLicense { get; set; } public static string License { get; set; } public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions) { if (DenyLicense) { if (allowExceptions) { throw new LicenseException(type); } else { return null; } } if (type != typeof(LicenseTesting)) { throw new Exception(); } var lic = new MockLicense(); if (instance != null) { ((LicenseTesting)instance).LicenseUsed = lic.LicenseKey; } return lic; } private class MockLicense : License { public override string LicenseKey => MockLicenseProvider.License ?? "__MOCK_LICENSE_KEY__"; public override void Dispose () { } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/Common/src/System/IO/ChunkedMemoryStream.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.Threading; using System.Threading.Tasks; using System; namespace System.IO { /// <summary>Provides an in-memory stream composed of non-contiguous chunks.</summary> internal sealed class ChunkedMemoryStream : Stream { private MemoryChunk? _headChunk; private MemoryChunk? _currentChunk; private const int InitialChunkDefaultSize = 1024; private const int MaxChunkSize = 1024 * InitialChunkDefaultSize; private int _totalLength; internal ChunkedMemoryStream() { } public byte[] ToArray() { byte[] result = new byte[_totalLength]; int offset = 0; for (MemoryChunk? chunk = _headChunk; chunk != null; chunk = chunk._next) { Debug.Assert(chunk._next == null || chunk._freeOffset == chunk._buffer.Length); Buffer.BlockCopy(chunk._buffer, 0, result, offset, chunk._freeOffset); offset += chunk._freeOffset; } return result; } public override void Write(byte[] buffer, int offset, int count) { Write(new ReadOnlySpan<byte>(buffer, offset, count)); } public override void Write(ReadOnlySpan<byte> buffer) { while (!buffer.IsEmpty) { if (_currentChunk != null) { int remaining = _currentChunk._buffer.Length - _currentChunk._freeOffset; if (remaining > 0) { int toCopy = Math.Min(remaining, buffer.Length); buffer.Slice(0, toCopy).CopyTo(new Span<byte>(_currentChunk._buffer, _currentChunk._freeOffset, toCopy)); buffer = buffer.Slice(toCopy); _totalLength += toCopy; _currentChunk._freeOffset += toCopy; continue; } } AppendChunk(buffer.Length); } } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } Write(buffer, offset, count); return Task.CompletedTask; } public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return ValueTask.FromCanceled(cancellationToken); } Write(buffer.Span); return ValueTask.CompletedTask; } private void AppendChunk(long count) { int nextChunkLength = _currentChunk != null ? _currentChunk._buffer.Length * 2 : InitialChunkDefaultSize; if (count > nextChunkLength) { nextChunkLength = (int)Math.Min(count, MaxChunkSize); } MemoryChunk newChunk = new MemoryChunk(nextChunkLength); if (_currentChunk == null) { Debug.Assert(_headChunk == null); _headChunk = _currentChunk = newChunk; } else { Debug.Assert(_headChunk != null); _currentChunk._next = newChunk; _currentChunk = newChunk; } } public override bool CanRead => false; public override bool CanSeek => false; public override bool CanWrite => true; public override long Length => _totalLength; public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask; public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { if (_currentChunk != null) throw new NotSupportedException(); AppendChunk(value); } private sealed class MemoryChunk { internal readonly byte[] _buffer; internal int _freeOffset; internal MemoryChunk? _next; internal MemoryChunk(int bufferSize) { _buffer = new byte[bufferSize]; } } } }
// 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.Threading; using System.Threading.Tasks; using System; namespace System.IO { /// <summary>Provides an in-memory stream composed of non-contiguous chunks.</summary> internal sealed class ChunkedMemoryStream : Stream { private MemoryChunk? _headChunk; private MemoryChunk? _currentChunk; private const int InitialChunkDefaultSize = 1024; private const int MaxChunkSize = 1024 * InitialChunkDefaultSize; private int _totalLength; internal ChunkedMemoryStream() { } public byte[] ToArray() { byte[] result = new byte[_totalLength]; int offset = 0; for (MemoryChunk? chunk = _headChunk; chunk != null; chunk = chunk._next) { Debug.Assert(chunk._next == null || chunk._freeOffset == chunk._buffer.Length); Buffer.BlockCopy(chunk._buffer, 0, result, offset, chunk._freeOffset); offset += chunk._freeOffset; } return result; } public override void Write(byte[] buffer, int offset, int count) { Write(new ReadOnlySpan<byte>(buffer, offset, count)); } public override void Write(ReadOnlySpan<byte> buffer) { while (!buffer.IsEmpty) { if (_currentChunk != null) { int remaining = _currentChunk._buffer.Length - _currentChunk._freeOffset; if (remaining > 0) { int toCopy = Math.Min(remaining, buffer.Length); buffer.Slice(0, toCopy).CopyTo(new Span<byte>(_currentChunk._buffer, _currentChunk._freeOffset, toCopy)); buffer = buffer.Slice(toCopy); _totalLength += toCopy; _currentChunk._freeOffset += toCopy; continue; } } AppendChunk(buffer.Length); } } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } Write(buffer, offset, count); return Task.CompletedTask; } public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return ValueTask.FromCanceled(cancellationToken); } Write(buffer.Span); return ValueTask.CompletedTask; } private void AppendChunk(long count) { int nextChunkLength = _currentChunk != null ? _currentChunk._buffer.Length * 2 : InitialChunkDefaultSize; if (count > nextChunkLength) { nextChunkLength = (int)Math.Min(count, MaxChunkSize); } MemoryChunk newChunk = new MemoryChunk(nextChunkLength); if (_currentChunk == null) { Debug.Assert(_headChunk == null); _headChunk = _currentChunk = newChunk; } else { Debug.Assert(_headChunk != null); _currentChunk._next = newChunk; _currentChunk = newChunk; } } public override bool CanRead => false; public override bool CanSeek => false; public override bool CanWrite => true; public override long Length => _totalLength; public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask; public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { if (_currentChunk != null) throw new NotSupportedException(); AppendChunk(value); } private sealed class MemoryChunk { internal readonly byte[] _buffer; internal int _freeOffset; internal MemoryChunk? _next; internal MemoryChunk(int bufferSize) { _buffer = new byte[bufferSize]; } } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/MetaHeader.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.Drawing.Imaging { [StructLayout(LayoutKind.Sequential, Pack = 2)] public sealed class MetaHeader { // The ENHMETAHEADER structure is defined natively as a union with WmfHeader. // Extreme care should be taken if changing the layout of the corresponding managaed // structures to minimize the risk of buffer overruns. The affected managed classes // are the following: ENHMETAHEADER, MetaHeader, MetafileHeaderWmf, MetafileHeaderEmf. private WmfMetaHeader _data; public MetaHeader() { } internal MetaHeader(WmfMetaHeader header) { _data._type = header._type; _data._headerSize = header._headerSize; _data._version = header._version; _data._size = header._size; _data._noObjects = header._noObjects; _data._maxRecord = header._maxRecord; _data._noParameters = header._noParameters; } /// <summary> /// Represents the type of the associated <see cref='Metafile'/>. /// </summary> public short Type { get { return _data._type; } set { _data._type = value; } } /// <summary> /// Represents the sizi, in bytes, of the header file. /// </summary> public short HeaderSize { get { return _data._headerSize; } set { _data._headerSize = value; } } /// <summary> /// Represents the version number of the header format. /// </summary> public short Version { get { return _data._version; } set { _data._version = value; } } /// <summary> /// Represents the size, in bytes, of the associated <see cref='Metafile'/>. /// </summary> public int Size { get { return _data._size; } set { _data._size = value; } } public short NoObjects { get { return _data._noObjects; } set { _data._noObjects = value; } } public int MaxRecord { get { return _data._maxRecord; } set { _data._maxRecord = value; } } public short NoParameters { get { return _data._noParameters; } set { _data._noParameters = value; } } internal WmfMetaHeader GetNativeValue() => _data; } [StructLayout(LayoutKind.Sequential, Pack = 2)] internal struct WmfMetaHeader { internal short _type; internal short _headerSize; internal short _version; internal int _size; internal short _noObjects; internal int _maxRecord; internal short _noParameters; } }
// 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.Drawing.Imaging { [StructLayout(LayoutKind.Sequential, Pack = 2)] public sealed class MetaHeader { // The ENHMETAHEADER structure is defined natively as a union with WmfHeader. // Extreme care should be taken if changing the layout of the corresponding managaed // structures to minimize the risk of buffer overruns. The affected managed classes // are the following: ENHMETAHEADER, MetaHeader, MetafileHeaderWmf, MetafileHeaderEmf. private WmfMetaHeader _data; public MetaHeader() { } internal MetaHeader(WmfMetaHeader header) { _data._type = header._type; _data._headerSize = header._headerSize; _data._version = header._version; _data._size = header._size; _data._noObjects = header._noObjects; _data._maxRecord = header._maxRecord; _data._noParameters = header._noParameters; } /// <summary> /// Represents the type of the associated <see cref='Metafile'/>. /// </summary> public short Type { get { return _data._type; } set { _data._type = value; } } /// <summary> /// Represents the sizi, in bytes, of the header file. /// </summary> public short HeaderSize { get { return _data._headerSize; } set { _data._headerSize = value; } } /// <summary> /// Represents the version number of the header format. /// </summary> public short Version { get { return _data._version; } set { _data._version = value; } } /// <summary> /// Represents the size, in bytes, of the associated <see cref='Metafile'/>. /// </summary> public int Size { get { return _data._size; } set { _data._size = value; } } public short NoObjects { get { return _data._noObjects; } set { _data._noObjects = value; } } public int MaxRecord { get { return _data._maxRecord; } set { _data._maxRecord = value; } } public short NoParameters { get { return _data._noParameters; } set { _data._noParameters = value; } } internal WmfMetaHeader GetNativeValue() => _data; } [StructLayout(LayoutKind.Sequential, Pack = 2)] internal struct WmfMetaHeader { internal short _type; internal short _headerSize; internal short _version; internal int _size; internal short _noObjects; internal int _maxRecord; internal short _noParameters; } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/Math/Functions/Double/FusedMultiplyAdd.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 System.MathBenchmarks { public partial class Double { // Tests Math.FusedMultiplyAdd(double, double, double) over 5000 iterations for the domain x: +2, +1; y: -2, -1, z: +1, -1 private const double fusedMultiplyAddDeltaX = -0.0004; private const double fusedMultiplyAddDeltaY = 0.0004; private const double fusedMultiplyAddDeltaZ = -0.0004; private const double fusedMultiplyAddExpectedResult = -6667.6668000005066; public void FusedMultiplyAdd() => FusedMultiplyAddTest(); public static void FusedMultiplyAddTest() { double result = 0.0, valueX = 2.0, valueY = -2.0, valueZ = 1.0; for (int iteration = 0; iteration < MathTests.Iterations; iteration++) { result += Math.FusedMultiplyAdd(valueX, valueY, valueZ); valueX += fusedMultiplyAddDeltaX; valueY += fusedMultiplyAddDeltaY; valueZ += fusedMultiplyAddDeltaZ; } double diff = Math.Abs(fusedMultiplyAddExpectedResult - result); if (double.IsNaN(result) || (diff > MathTests.DoubleEpsilon)) { throw new Exception($"Expected Result {fusedMultiplyAddExpectedResult,20:g17}; Actual Result {result,20:g17}"); } } } }
// 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 System.MathBenchmarks { public partial class Double { // Tests Math.FusedMultiplyAdd(double, double, double) over 5000 iterations for the domain x: +2, +1; y: -2, -1, z: +1, -1 private const double fusedMultiplyAddDeltaX = -0.0004; private const double fusedMultiplyAddDeltaY = 0.0004; private const double fusedMultiplyAddDeltaZ = -0.0004; private const double fusedMultiplyAddExpectedResult = -6667.6668000005066; public void FusedMultiplyAdd() => FusedMultiplyAddTest(); public static void FusedMultiplyAddTest() { double result = 0.0, valueX = 2.0, valueY = -2.0, valueZ = 1.0; for (int iteration = 0; iteration < MathTests.Iterations; iteration++) { result += Math.FusedMultiplyAdd(valueX, valueY, valueZ); valueX += fusedMultiplyAddDeltaX; valueY += fusedMultiplyAddDeltaY; valueZ += fusedMultiplyAddDeltaZ; } double diff = Math.Abs(fusedMultiplyAddExpectedResult - result); if (double.IsNaN(result) || (diff > MathTests.DoubleEpsilon)) { throw new Exception($"Expected Result {fusedMultiplyAddExpectedResult,20:g17}; Actual Result {result,20:g17}"); } } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Security.Cryptography.OpenSsl/tests/EcDiffieHellmanOpenSslTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Security.Cryptography.EcDiffieHellman.Tests; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.EcDiffieHellman.OpenSsl.Tests { public class EcDiffieHellmanOpenSslTests : ECDiffieHellmanTests { [Fact] public void DefaultCtor() { using (var e = new ECDiffieHellmanOpenSsl()) { int keySize = e.KeySize; Assert.Equal(521, keySize); e.Exercise(); } } [Fact] public void Ctor256() { int expectedKeySize = 256; using (var e = new ECDiffieHellmanOpenSsl(expectedKeySize)) { int keySize = e.KeySize; Assert.Equal(expectedKeySize, keySize); e.Exercise(); } } [Fact] public void Ctor384() { int expectedKeySize = 384; using (var e = new ECDiffieHellmanOpenSsl(expectedKeySize)) { int keySize = e.KeySize; Assert.Equal(expectedKeySize, keySize); e.Exercise(); } } [Fact] public void Ctor521() { int expectedKeySize = 521; using (var e = new ECDiffieHellmanOpenSsl(expectedKeySize)) { int keySize = e.KeySize; Assert.Equal(expectedKeySize, keySize); e.Exercise(); } } [ConditionalFact(nameof(ECDsa224Available))] public void CtorHandle224() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByOid(ECDSA_P224_OID_VALUE); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (var e = new ECDiffieHellmanOpenSsl(ecKey)) { int keySize = e.KeySize; Assert.Equal(224, keySize); e.Exercise(); } Interop.Crypto.EcKeyDestroy(ecKey); } [Fact] public void CtorHandle384() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByOid(ECDSA_P384_OID_VALUE); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (var e = new ECDiffieHellmanOpenSsl(ecKey)) { int keySize = e.KeySize; Assert.Equal(384, keySize); e.Exercise(); } Interop.Crypto.EcKeyDestroy(ecKey); } [Fact] public void CtorHandle521() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByOid(ECDSA_P521_OID_VALUE); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (var e = new ECDiffieHellmanOpenSsl(ecKey)) { int keySize = e.KeySize; Assert.Equal(521, keySize); e.Exercise(); } Interop.Crypto.EcKeyDestroy(ecKey); } [Fact] public void CtorHandleDuplicate() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByOid(ECDSA_P521_OID_VALUE); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (var e = new ECDiffieHellmanOpenSsl(ecKey)) { // Make sure ECDsaOpenSsl did its own ref-count bump. Interop.Crypto.EcKeyDestroy(ecKey); int keySize = e.KeySize; Assert.Equal(521, keySize); e.Exercise(); } } [Fact] public void KeySizePropWithExercise() { using (var e = new ECDiffieHellmanOpenSsl()) { e.KeySize = 384; Assert.Equal(384, e.KeySize); e.Exercise(); ECParameters p384 = e.ExportParameters(false); Assert.Equal(ECCurve.ECCurveType.Named, p384.Curve.CurveType); e.KeySize = 521; Assert.Equal(521, e.KeySize); e.Exercise(); ECParameters p521 = e.ExportParameters(false); Assert.Equal(ECCurve.ECCurveType.Named, p521.Curve.CurveType); // ensure the key was regenerated Assert.NotEqual(p384.Curve.Oid.Value, p521.Curve.Oid.Value); } } [Fact] public void VerifyDuplicateKey_ValidHandle() { using (var first = new ECDiffieHellmanOpenSsl()) using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle()) using (ECDiffieHellman second = new ECDiffieHellmanOpenSsl(firstHandle)) using (ECDiffieHellmanPublicKey firstPublic = first.PublicKey) using (ECDiffieHellmanPublicKey secondPublic = second.PublicKey) { byte[] firstSecond = first.DeriveKeyFromHash(secondPublic, HashAlgorithmName.SHA256); byte[] secondFirst = second.DeriveKeyFromHash(firstPublic, HashAlgorithmName.SHA256); byte[] firstFirst = first.DeriveKeyFromHash(firstPublic, HashAlgorithmName.SHA256); Assert.Equal(firstSecond, secondFirst); Assert.Equal(firstFirst, firstSecond); } } [Fact] public void VerifyDuplicateKey_DistinctHandles() { using (var first = new ECDiffieHellmanOpenSsl()) using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle()) using (SafeEvpPKeyHandle firstHandle2 = first.DuplicateKeyHandle()) { Assert.NotSame(firstHandle, firstHandle2); } } [Fact] public void VerifyDuplicateKey_RefCounts() { byte[] derived; ECDiffieHellman second; using (var first = new ECDiffieHellmanOpenSsl()) using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle()) using (ECDiffieHellmanPublicKey firstPublic = first.PublicKey) { derived = first.DeriveKeyFromHmac(firstPublic, HashAlgorithmName.SHA384, null); second = new ECDiffieHellmanOpenSsl(firstHandle); } // Now show that second still works, despite first and firstHandle being Disposed. using (second) using (ECDiffieHellmanPublicKey secondPublic = second.PublicKey) { byte[] derived2 = second.DeriveKeyFromHmac(secondPublic, HashAlgorithmName.SHA384, null); Assert.Equal(derived, derived2); } } [Fact] public void VerifyDuplicateKey_NullHandle() { SafeEvpPKeyHandle pkey = null; Assert.Throws<ArgumentNullException>(() => new ECDiffieHellmanOpenSsl(pkey)); } [Fact] public void VerifyDuplicateKey_InvalidHandle() { using (var ecdsa = new ECDiffieHellmanOpenSsl()) { SafeEvpPKeyHandle pkey = ecdsa.DuplicateKeyHandle(); using (pkey) { } AssertExtensions.Throws<ArgumentException>("pkeyHandle", () => new ECDiffieHellmanOpenSsl(pkey)); } } [Fact] public void VerifyDuplicateKey_NeverValidHandle() { using (SafeEvpPKeyHandle pkey = new SafeEvpPKeyHandle(IntPtr.Zero, false)) { AssertExtensions.Throws<ArgumentException>("pkeyHandle", () => new ECDiffieHellmanOpenSsl(pkey)); } } [Fact] public void VerifyDuplicateKey_RsaHandle() { using (RSAOpenSsl rsa = new RSAOpenSsl()) using (SafeEvpPKeyHandle pkey = rsa.DuplicateKeyHandle()) { Assert.ThrowsAny<CryptographicException>(() => new ECDiffieHellmanOpenSsl(pkey)); } } [Fact] public void LookupCurveByOidValue() { var ec = new ECDiffieHellmanOpenSsl(ECCurve.CreateFromValue(ECDSA_P256_OID_VALUE)); // Same as nistP256 ECParameters param = ec.ExportParameters(false); param.Validate(); Assert.Equal(256, ec.KeySize); Assert.True(param.Curve.IsNamed); Assert.Equal("ECDSA_P256", param.Curve.Oid.FriendlyName); Assert.Equal(ECDSA_P256_OID_VALUE, param.Curve.Oid.Value); } [Fact] public void LookupCurveByOidFriendlyName() { // prime256v1 is alias for nistP256 for OpenSsl var ec = new ECDiffieHellmanOpenSsl(ECCurve.CreateFromFriendlyName("prime256v1")); ECParameters param = ec.ExportParameters(false); param.Validate(); Assert.Equal(256, ec.KeySize); Assert.True(param.Curve.IsNamed); Assert.Equal("ECDSA_P256", param.Curve.Oid.FriendlyName); // OpenSsl maps prime256v1 to ECDSA_P256 Assert.Equal(ECDSA_P256_OID_VALUE, param.Curve.Oid.Value); // secp521r1 is same as nistP521; note Windows uses secP521r1 (uppercase P) ec = new ECDiffieHellmanOpenSsl(ECCurve.CreateFromFriendlyName("secp521r1")); param = ec.ExportParameters(false); param.Validate(); Assert.Equal(521, ec.KeySize); Assert.True(param.Curve.IsNamed); Assert.Equal("ECDSA_P521", param.Curve.Oid.FriendlyName); // OpenSsl maps secp521r1 to ECDSA_P521 Assert.Equal(ECDSA_P521_OID_VALUE, param.Curve.Oid.Value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Security.Cryptography.EcDiffieHellman.Tests; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.EcDiffieHellman.OpenSsl.Tests { public class EcDiffieHellmanOpenSslTests : ECDiffieHellmanTests { [Fact] public void DefaultCtor() { using (var e = new ECDiffieHellmanOpenSsl()) { int keySize = e.KeySize; Assert.Equal(521, keySize); e.Exercise(); } } [Fact] public void Ctor256() { int expectedKeySize = 256; using (var e = new ECDiffieHellmanOpenSsl(expectedKeySize)) { int keySize = e.KeySize; Assert.Equal(expectedKeySize, keySize); e.Exercise(); } } [Fact] public void Ctor384() { int expectedKeySize = 384; using (var e = new ECDiffieHellmanOpenSsl(expectedKeySize)) { int keySize = e.KeySize; Assert.Equal(expectedKeySize, keySize); e.Exercise(); } } [Fact] public void Ctor521() { int expectedKeySize = 521; using (var e = new ECDiffieHellmanOpenSsl(expectedKeySize)) { int keySize = e.KeySize; Assert.Equal(expectedKeySize, keySize); e.Exercise(); } } [ConditionalFact(nameof(ECDsa224Available))] public void CtorHandle224() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByOid(ECDSA_P224_OID_VALUE); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (var e = new ECDiffieHellmanOpenSsl(ecKey)) { int keySize = e.KeySize; Assert.Equal(224, keySize); e.Exercise(); } Interop.Crypto.EcKeyDestroy(ecKey); } [Fact] public void CtorHandle384() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByOid(ECDSA_P384_OID_VALUE); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (var e = new ECDiffieHellmanOpenSsl(ecKey)) { int keySize = e.KeySize; Assert.Equal(384, keySize); e.Exercise(); } Interop.Crypto.EcKeyDestroy(ecKey); } [Fact] public void CtorHandle521() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByOid(ECDSA_P521_OID_VALUE); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (var e = new ECDiffieHellmanOpenSsl(ecKey)) { int keySize = e.KeySize; Assert.Equal(521, keySize); e.Exercise(); } Interop.Crypto.EcKeyDestroy(ecKey); } [Fact] public void CtorHandleDuplicate() { IntPtr ecKey = Interop.Crypto.EcKeyCreateByOid(ECDSA_P521_OID_VALUE); Assert.NotEqual(IntPtr.Zero, ecKey); int success = Interop.Crypto.EcKeyGenerateKey(ecKey); Assert.NotEqual(0, success); using (var e = new ECDiffieHellmanOpenSsl(ecKey)) { // Make sure ECDsaOpenSsl did its own ref-count bump. Interop.Crypto.EcKeyDestroy(ecKey); int keySize = e.KeySize; Assert.Equal(521, keySize); e.Exercise(); } } [Fact] public void KeySizePropWithExercise() { using (var e = new ECDiffieHellmanOpenSsl()) { e.KeySize = 384; Assert.Equal(384, e.KeySize); e.Exercise(); ECParameters p384 = e.ExportParameters(false); Assert.Equal(ECCurve.ECCurveType.Named, p384.Curve.CurveType); e.KeySize = 521; Assert.Equal(521, e.KeySize); e.Exercise(); ECParameters p521 = e.ExportParameters(false); Assert.Equal(ECCurve.ECCurveType.Named, p521.Curve.CurveType); // ensure the key was regenerated Assert.NotEqual(p384.Curve.Oid.Value, p521.Curve.Oid.Value); } } [Fact] public void VerifyDuplicateKey_ValidHandle() { using (var first = new ECDiffieHellmanOpenSsl()) using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle()) using (ECDiffieHellman second = new ECDiffieHellmanOpenSsl(firstHandle)) using (ECDiffieHellmanPublicKey firstPublic = first.PublicKey) using (ECDiffieHellmanPublicKey secondPublic = second.PublicKey) { byte[] firstSecond = first.DeriveKeyFromHash(secondPublic, HashAlgorithmName.SHA256); byte[] secondFirst = second.DeriveKeyFromHash(firstPublic, HashAlgorithmName.SHA256); byte[] firstFirst = first.DeriveKeyFromHash(firstPublic, HashAlgorithmName.SHA256); Assert.Equal(firstSecond, secondFirst); Assert.Equal(firstFirst, firstSecond); } } [Fact] public void VerifyDuplicateKey_DistinctHandles() { using (var first = new ECDiffieHellmanOpenSsl()) using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle()) using (SafeEvpPKeyHandle firstHandle2 = first.DuplicateKeyHandle()) { Assert.NotSame(firstHandle, firstHandle2); } } [Fact] public void VerifyDuplicateKey_RefCounts() { byte[] derived; ECDiffieHellman second; using (var first = new ECDiffieHellmanOpenSsl()) using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle()) using (ECDiffieHellmanPublicKey firstPublic = first.PublicKey) { derived = first.DeriveKeyFromHmac(firstPublic, HashAlgorithmName.SHA384, null); second = new ECDiffieHellmanOpenSsl(firstHandle); } // Now show that second still works, despite first and firstHandle being Disposed. using (second) using (ECDiffieHellmanPublicKey secondPublic = second.PublicKey) { byte[] derived2 = second.DeriveKeyFromHmac(secondPublic, HashAlgorithmName.SHA384, null); Assert.Equal(derived, derived2); } } [Fact] public void VerifyDuplicateKey_NullHandle() { SafeEvpPKeyHandle pkey = null; Assert.Throws<ArgumentNullException>(() => new ECDiffieHellmanOpenSsl(pkey)); } [Fact] public void VerifyDuplicateKey_InvalidHandle() { using (var ecdsa = new ECDiffieHellmanOpenSsl()) { SafeEvpPKeyHandle pkey = ecdsa.DuplicateKeyHandle(); using (pkey) { } AssertExtensions.Throws<ArgumentException>("pkeyHandle", () => new ECDiffieHellmanOpenSsl(pkey)); } } [Fact] public void VerifyDuplicateKey_NeverValidHandle() { using (SafeEvpPKeyHandle pkey = new SafeEvpPKeyHandle(IntPtr.Zero, false)) { AssertExtensions.Throws<ArgumentException>("pkeyHandle", () => new ECDiffieHellmanOpenSsl(pkey)); } } [Fact] public void VerifyDuplicateKey_RsaHandle() { using (RSAOpenSsl rsa = new RSAOpenSsl()) using (SafeEvpPKeyHandle pkey = rsa.DuplicateKeyHandle()) { Assert.ThrowsAny<CryptographicException>(() => new ECDiffieHellmanOpenSsl(pkey)); } } [Fact] public void LookupCurveByOidValue() { var ec = new ECDiffieHellmanOpenSsl(ECCurve.CreateFromValue(ECDSA_P256_OID_VALUE)); // Same as nistP256 ECParameters param = ec.ExportParameters(false); param.Validate(); Assert.Equal(256, ec.KeySize); Assert.True(param.Curve.IsNamed); Assert.Equal("ECDSA_P256", param.Curve.Oid.FriendlyName); Assert.Equal(ECDSA_P256_OID_VALUE, param.Curve.Oid.Value); } [Fact] public void LookupCurveByOidFriendlyName() { // prime256v1 is alias for nistP256 for OpenSsl var ec = new ECDiffieHellmanOpenSsl(ECCurve.CreateFromFriendlyName("prime256v1")); ECParameters param = ec.ExportParameters(false); param.Validate(); Assert.Equal(256, ec.KeySize); Assert.True(param.Curve.IsNamed); Assert.Equal("ECDSA_P256", param.Curve.Oid.FriendlyName); // OpenSsl maps prime256v1 to ECDSA_P256 Assert.Equal(ECDSA_P256_OID_VALUE, param.Curve.Oid.Value); // secp521r1 is same as nistP521; note Windows uses secP521r1 (uppercase P) ec = new ECDiffieHellmanOpenSsl(ECCurve.CreateFromFriendlyName("secp521r1")); param = ec.ExportParameters(false); param.Validate(); Assert.Equal(521, ec.KeySize); Assert.True(param.Curve.IsNamed); Assert.Equal("ECDSA_P521", param.Curve.Oid.FriendlyName); // OpenSsl maps secp521r1 to ECDSA_P521 Assert.Equal(ECDSA_P521_OID_VALUE, param.Curve.Oid.Value); } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Text.RegularExpressions/src/System/Threading/StackHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace System.Threading { /// <summary>Provides tools for avoiding stack overflows.</summary> internal static class StackHelper { /// <summary>Tries to ensure there is sufficient stack to execute the average .NET function.</summary> public static bool TryEnsureSufficientExecutionStack() { #if REGEXGENERATOR try { RuntimeHelpers.EnsureSufficientExecutionStack(); return true; } catch { return false; } #else return RuntimeHelpers.TryEnsureSufficientExecutionStack(); #endif } // Queues the supplied delegate to the thread pool, then block waiting for it to complete. // It does so in a way that prevents task inlining (which would defeat the purpose) but that // also plays nicely with the thread pool's sync-over-async aggressive thread injection policies. /// <summary>Calls the provided action on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <param name="action">The action to invoke.</param> /// <param name="arg1">The first argument to pass to the action.</param> public static void CallOnEmptyStack<TArg1>(Action<TArg1> action, TArg1 arg1) => Task.Run(() => action(arg1)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided action on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TArg2">The type of the second argument to pass to the function.</typeparam> /// <param name="action">The action to invoke.</param> /// <param name="arg1">The first argument to pass to the action.</param> /// <param name="arg2">The second argument to pass to the action.</param> public static void CallOnEmptyStack<TArg1, TArg2>(Action<TArg1, TArg2> action, TArg1 arg1, TArg2 arg2) => Task.Run(() => action(arg1, arg2)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided action on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TArg2">The type of the second argument to pass to the function.</typeparam> /// <typeparam name="TArg3">The type of the third argument to pass to the function.</typeparam> /// <param name="action">The action to invoke.</param> /// <param name="arg1">The first argument to pass to the action.</param> /// <param name="arg2">The second argument to pass to the action.</param> /// <param name="arg3">The third argument to pass to the action.</param> public static void CallOnEmptyStack<TArg1, TArg2, TArg3>(Action<TArg1, TArg2, TArg3> action, TArg1 arg1, TArg2 arg2, TArg3 arg3) => Task.Run(() => action(arg1, arg2, arg3)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided function on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TArg2">The type of the second argument to pass to the function.</typeparam> /// <typeparam name="TArg3">The type of the third argument to pass to the function.</typeparam> /// <typeparam name="TArg4">The type of the fourth argument to pass to the function.</typeparam> /// <typeparam name="TArg5">The type of the fifth argument to pass to the function.</typeparam> /// <typeparam name="TArg6">The type of the sixth argument to pass to the function.</typeparam> /// <param name="action">The action to invoke.</param> /// <param name="arg1">The first argument to pass to the action.</param> /// <param name="arg2">The second argument to pass to the action.</param> /// <param name="arg3">The third argument to pass to the action.</param> /// <param name="arg4">The fourth argument to pass to the action.</param> /// <param name="arg5">The fifth argument to pass to the action.</param> /// <param name="arg6">The sixth argument to pass to the action.</param> public static void CallOnEmptyStack<TArg1, TArg2, TArg3, TArg4, TArg5, TArg6>(Action<TArg1, TArg2, TArg3, TArg4, TArg5, TArg6> action, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6) => Task.Run(() => action(arg1, arg2, arg3, arg4, arg5, arg6)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided function on the stack of a different thread pool thread.</summary> /// <typeparam name="TResult">The return type of the function.</typeparam> /// <param name="func">The function to invoke.</param> public static TResult CallOnEmptyStack<TResult>(Func<TResult> func) => Task.Run(() => func()) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided function on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TResult">The return type of the function.</typeparam> /// <param name="func">The function to invoke.</param> /// <param name="arg1">The first argument to pass to the function.</param> public static TResult CallOnEmptyStack<TArg1, TResult>(Func<TArg1, TResult> func, TArg1 arg1) => Task.Run(() => func(arg1)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided function on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TArg2">The type of the second argument to pass to the function.</typeparam> /// <typeparam name="TResult">The return type of the function.</typeparam> /// <param name="func">The function to invoke.</param> /// <param name="arg1">The first argument to pass to the function.</param> /// <param name="arg2">The second argument to pass to the function.</param> public static TResult CallOnEmptyStack<TArg1, TArg2, TResult>(Func<TArg1, TArg2, TResult> func, TArg1 arg1, TArg2 arg2) => Task.Run(() => func(arg1, arg2)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided function on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TArg2">The type of the second argument to pass to the function.</typeparam> /// <typeparam name="TArg3">The type of the third argument to pass to the function.</typeparam> /// <typeparam name="TResult">The return type of the function.</typeparam> /// <param name="func">The function to invoke.</param> /// <param name="arg1">The first argument to pass to the function.</param> /// <param name="arg2">The second argument to pass to the function.</param> /// <param name="arg3">The third argument to pass to the function.</param> public static TResult CallOnEmptyStack<TArg1, TArg2, TArg3, TResult>(Func<TArg1, TArg2, TArg3, TResult> func, TArg1 arg1, TArg2 arg2, TArg3 arg3) => Task.Run(() => func(arg1, arg2, arg3)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace System.Threading { /// <summary>Provides tools for avoiding stack overflows.</summary> internal static class StackHelper { /// <summary>Tries to ensure there is sufficient stack to execute the average .NET function.</summary> public static bool TryEnsureSufficientExecutionStack() { #if REGEXGENERATOR try { RuntimeHelpers.EnsureSufficientExecutionStack(); return true; } catch { return false; } #else return RuntimeHelpers.TryEnsureSufficientExecutionStack(); #endif } // Queues the supplied delegate to the thread pool, then block waiting for it to complete. // It does so in a way that prevents task inlining (which would defeat the purpose) but that // also plays nicely with the thread pool's sync-over-async aggressive thread injection policies. /// <summary>Calls the provided action on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <param name="action">The action to invoke.</param> /// <param name="arg1">The first argument to pass to the action.</param> public static void CallOnEmptyStack<TArg1>(Action<TArg1> action, TArg1 arg1) => Task.Run(() => action(arg1)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided action on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TArg2">The type of the second argument to pass to the function.</typeparam> /// <param name="action">The action to invoke.</param> /// <param name="arg1">The first argument to pass to the action.</param> /// <param name="arg2">The second argument to pass to the action.</param> public static void CallOnEmptyStack<TArg1, TArg2>(Action<TArg1, TArg2> action, TArg1 arg1, TArg2 arg2) => Task.Run(() => action(arg1, arg2)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided action on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TArg2">The type of the second argument to pass to the function.</typeparam> /// <typeparam name="TArg3">The type of the third argument to pass to the function.</typeparam> /// <param name="action">The action to invoke.</param> /// <param name="arg1">The first argument to pass to the action.</param> /// <param name="arg2">The second argument to pass to the action.</param> /// <param name="arg3">The third argument to pass to the action.</param> public static void CallOnEmptyStack<TArg1, TArg2, TArg3>(Action<TArg1, TArg2, TArg3> action, TArg1 arg1, TArg2 arg2, TArg3 arg3) => Task.Run(() => action(arg1, arg2, arg3)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided function on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TArg2">The type of the second argument to pass to the function.</typeparam> /// <typeparam name="TArg3">The type of the third argument to pass to the function.</typeparam> /// <typeparam name="TArg4">The type of the fourth argument to pass to the function.</typeparam> /// <typeparam name="TArg5">The type of the fifth argument to pass to the function.</typeparam> /// <typeparam name="TArg6">The type of the sixth argument to pass to the function.</typeparam> /// <param name="action">The action to invoke.</param> /// <param name="arg1">The first argument to pass to the action.</param> /// <param name="arg2">The second argument to pass to the action.</param> /// <param name="arg3">The third argument to pass to the action.</param> /// <param name="arg4">The fourth argument to pass to the action.</param> /// <param name="arg5">The fifth argument to pass to the action.</param> /// <param name="arg6">The sixth argument to pass to the action.</param> public static void CallOnEmptyStack<TArg1, TArg2, TArg3, TArg4, TArg5, TArg6>(Action<TArg1, TArg2, TArg3, TArg4, TArg5, TArg6> action, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6) => Task.Run(() => action(arg1, arg2, arg3, arg4, arg5, arg6)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided function on the stack of a different thread pool thread.</summary> /// <typeparam name="TResult">The return type of the function.</typeparam> /// <param name="func">The function to invoke.</param> public static TResult CallOnEmptyStack<TResult>(Func<TResult> func) => Task.Run(() => func()) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided function on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TResult">The return type of the function.</typeparam> /// <param name="func">The function to invoke.</param> /// <param name="arg1">The first argument to pass to the function.</param> public static TResult CallOnEmptyStack<TArg1, TResult>(Func<TArg1, TResult> func, TArg1 arg1) => Task.Run(() => func(arg1)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided function on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TArg2">The type of the second argument to pass to the function.</typeparam> /// <typeparam name="TResult">The return type of the function.</typeparam> /// <param name="func">The function to invoke.</param> /// <param name="arg1">The first argument to pass to the function.</param> /// <param name="arg2">The second argument to pass to the function.</param> public static TResult CallOnEmptyStack<TArg1, TArg2, TResult>(Func<TArg1, TArg2, TResult> func, TArg1 arg1, TArg2 arg2) => Task.Run(() => func(arg1, arg2)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); /// <summary>Calls the provided function on the stack of a different thread pool thread.</summary> /// <typeparam name="TArg1">The type of the first argument to pass to the function.</typeparam> /// <typeparam name="TArg2">The type of the second argument to pass to the function.</typeparam> /// <typeparam name="TArg3">The type of the third argument to pass to the function.</typeparam> /// <typeparam name="TResult">The return type of the function.</typeparam> /// <param name="func">The function to invoke.</param> /// <param name="arg1">The first argument to pass to the function.</param> /// <param name="arg2">The second argument to pass to the function.</param> /// <param name="arg3">The third argument to pass to the function.</param> public static TResult CallOnEmptyStack<TArg1, TArg2, TArg3, TResult>(Func<TArg1, TArg2, TArg3, TResult> func, TArg1 arg1, TArg2 arg2, TArg3 arg3) => Task.Run(() => func(arg1, arg2, arg3)) .ContinueWith(t => t.GetAwaiter().GetResult(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) .GetAwaiter().GetResult(); } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/opt/virtualstubdispatch/hashcode/ctest1_cs_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>Full</DebugType> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="ctest1.cs" /> <ProjectReference Include="cderived1.csproj" /> <ProjectReference Include="cderived2.csproj" /> <ProjectReference Include="cderived3.csproj" /> <ProjectReference Include="cderived4.csproj" /> <ProjectReference Include="cderived5.csproj" /> <ProjectReference Include="cderived6.csproj" /> <ProjectReference Include="cderived7.csproj" /> <ProjectReference Include="cderived8.csproj" /> <ProjectReference Include="cderived9.csproj" /> <ProjectReference Include="cderived10.csproj" /> <ProjectReference Include="cderived11.csproj" /> <ProjectReference Include="cderived12.csproj" /> <ProjectReference Include="cderived13.csproj" /> <ProjectReference Include="cderived14.csproj" /> <ProjectReference Include="cderived15.csproj" /> <ProjectReference Include="cderived16.csproj" /> <ProjectReference Include="cderived17.csproj" /> <ProjectReference Include="cderived18.csproj" /> <ProjectReference Include="cderived19.csproj" /> <ProjectReference Include="cderived20.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>Full</DebugType> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="ctest1.cs" /> <ProjectReference Include="cderived1.csproj" /> <ProjectReference Include="cderived2.csproj" /> <ProjectReference Include="cderived3.csproj" /> <ProjectReference Include="cderived4.csproj" /> <ProjectReference Include="cderived5.csproj" /> <ProjectReference Include="cderived6.csproj" /> <ProjectReference Include="cderived7.csproj" /> <ProjectReference Include="cderived8.csproj" /> <ProjectReference Include="cderived9.csproj" /> <ProjectReference Include="cderived10.csproj" /> <ProjectReference Include="cderived11.csproj" /> <ProjectReference Include="cderived12.csproj" /> <ProjectReference Include="cderived13.csproj" /> <ProjectReference Include="cderived14.csproj" /> <ProjectReference Include="cderived15.csproj" /> <ProjectReference Include="cderived16.csproj" /> <ProjectReference Include="cderived17.csproj" /> <ProjectReference Include="cderived18.csproj" /> <ProjectReference Include="cderived19.csproj" /> <ProjectReference Include="cderived20.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/Methodical/eh/finallyexec/switchincatch_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="switchincatch.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\common\eh_common.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="switchincatch.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\common\eh_common.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/Directed/TypedReference/TypedReference.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 BringUpTest_TypedReference { const int Pass = 100; const int Fail = -1; const string Apple = "apple"; const string Orange = "orange"; public static int Main() { int i = Fail; F(__makeref(i)); if (i != Pass) return Fail; string j = Apple; G(__makeref(j)); if (j != Orange) return Fail; return Pass; } static void F(System.TypedReference t) { __refvalue(t, int) = Pass; } static void G(System.TypedReference t) { __refvalue(t, string) = Orange; } }
// 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 BringUpTest_TypedReference { const int Pass = 100; const int Fail = -1; const string Apple = "apple"; const string Orange = "orange"; public static int Main() { int i = Fail; F(__makeref(i)); if (i != Pass) return Fail; string j = Apple; G(__makeref(j)); if (j != Orange) return Fail; return Pass; } static void F(System.TypedReference t) { __refvalue(t, int) = Pass; } static void G(System.TypedReference t) { __refvalue(t, string) = Orange; } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Linq/src/System/Linq/Intersect.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; namespace System.Linq { public static partial class Enumerable { public static IEnumerable<TSource> Intersect<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second) => Intersect(first, second, null); public static IEnumerable<TSource> Intersect<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource>? comparer) { if (first == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.first); } if (second == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.second); } return IntersectIterator(first, second, comparer); } /// <summary>Produces the set intersection of two sequences according to a specified key selector function.</summary> /// <typeparam name="TSource">The type of the elements of the input sequences.</typeparam> /// <typeparam name="TKey">The type of key to identify elements by.</typeparam> /// <param name="first">An <see cref="IEnumerable{T}" /> whose distinct elements that also appear in <paramref name="second" /> will be returned.</param> /// <param name="second">An <see cref="IEnumerable{T}" /> whose distinct elements that also appear in the first sequence will be returned.</param> /// <param name="keySelector">A function to extract the key for each element.</param> /// <returns>A sequence that contains the elements that form the set intersection of two sequences.</returns> /// <exception cref="ArgumentNullException"><paramref name="first" /> or <paramref name="second" /> is <see langword="null" />.</exception> /// <remarks> /// <para>This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its `GetEnumerator` method directly or by using `foreach` in Visual C# or `For Each` in Visual Basic.</para> /// <para>The intersection of two sets A and B is defined as the set that contains all the elements of A that also appear in B, but no other elements.</para> /// <para>When the object returned by this method is enumerated, `Intersect` yields distinct elements occurring in both sequences in the order in which they appear in <paramref name="first" />.</para> /// <para>The default equality comparer, <see cref="EqualityComparer{T}.Default" />, is used to compare values.</para> /// </remarks> public static IEnumerable<TSource> IntersectBy<TSource, TKey>(this IEnumerable<TSource> first, IEnumerable<TKey> second, Func<TSource, TKey> keySelector) => IntersectBy(first, second, keySelector, null); /// <summary>Produces the set intersection of two sequences according to a specified key selector function.</summary> /// <typeparam name="TSource">The type of the elements of the input sequences.</typeparam> /// <typeparam name="TKey">The type of key to identify elements by.</typeparam> /// <param name="first">An <see cref="IEnumerable{T}" /> whose distinct elements that also appear in <paramref name="second" /> will be returned.</param> /// <param name="second">An <see cref="IEnumerable{T}" /> whose distinct elements that also appear in the first sequence will be returned.</param> /// <param name="keySelector">A function to extract the key for each element.</param> /// <param name="comparer">An <see cref="IEqualityComparer{TKey}" /> to compare keys.</param> /// <returns>A sequence that contains the elements that form the set intersection of two sequences.</returns> /// <exception cref="ArgumentNullException"><paramref name="first" /> or <paramref name="second" /> is <see langword="null" />.</exception> /// <remarks> /// <para>This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its `GetEnumerator` method directly or by using `foreach` in Visual C# or `For Each` in Visual Basic.</para> /// <para>The intersection of two sets A and B is defined as the set that contains all the elements of A that also appear in B, but no other elements.</para> /// <para>When the object returned by this method is enumerated, `Intersect` yields distinct elements occurring in both sequences in the order in which they appear in <paramref name="first" />.</para> /// <para>If <paramref name="comparer" /> is <see langword="null" />, the default equality comparer, <see cref="EqualityComparer{T}.Default" />, is used to compare values.</para> /// </remarks> public static IEnumerable<TSource> IntersectBy<TSource, TKey>(this IEnumerable<TSource> first, IEnumerable<TKey> second, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer) { if (first is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.first); } if (second is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.second); } if (keySelector is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keySelector); } return IntersectByIterator(first, second, keySelector, comparer); } private static IEnumerable<TSource> IntersectIterator<TSource>(IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource>? comparer) { var set = new HashSet<TSource>(second, comparer); foreach (TSource element in first) { if (set.Remove(element)) { yield return element; } } } private static IEnumerable<TSource> IntersectByIterator<TSource, TKey>(IEnumerable<TSource> first, IEnumerable<TKey> second, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer) { var set = new HashSet<TKey>(second, comparer); foreach (TSource element in first) { if (set.Remove(keySelector(element))) { yield return element; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; namespace System.Linq { public static partial class Enumerable { public static IEnumerable<TSource> Intersect<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second) => Intersect(first, second, null); public static IEnumerable<TSource> Intersect<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource>? comparer) { if (first == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.first); } if (second == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.second); } return IntersectIterator(first, second, comparer); } /// <summary>Produces the set intersection of two sequences according to a specified key selector function.</summary> /// <typeparam name="TSource">The type of the elements of the input sequences.</typeparam> /// <typeparam name="TKey">The type of key to identify elements by.</typeparam> /// <param name="first">An <see cref="IEnumerable{T}" /> whose distinct elements that also appear in <paramref name="second" /> will be returned.</param> /// <param name="second">An <see cref="IEnumerable{T}" /> whose distinct elements that also appear in the first sequence will be returned.</param> /// <param name="keySelector">A function to extract the key for each element.</param> /// <returns>A sequence that contains the elements that form the set intersection of two sequences.</returns> /// <exception cref="ArgumentNullException"><paramref name="first" /> or <paramref name="second" /> is <see langword="null" />.</exception> /// <remarks> /// <para>This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its `GetEnumerator` method directly or by using `foreach` in Visual C# or `For Each` in Visual Basic.</para> /// <para>The intersection of two sets A and B is defined as the set that contains all the elements of A that also appear in B, but no other elements.</para> /// <para>When the object returned by this method is enumerated, `Intersect` yields distinct elements occurring in both sequences in the order in which they appear in <paramref name="first" />.</para> /// <para>The default equality comparer, <see cref="EqualityComparer{T}.Default" />, is used to compare values.</para> /// </remarks> public static IEnumerable<TSource> IntersectBy<TSource, TKey>(this IEnumerable<TSource> first, IEnumerable<TKey> second, Func<TSource, TKey> keySelector) => IntersectBy(first, second, keySelector, null); /// <summary>Produces the set intersection of two sequences according to a specified key selector function.</summary> /// <typeparam name="TSource">The type of the elements of the input sequences.</typeparam> /// <typeparam name="TKey">The type of key to identify elements by.</typeparam> /// <param name="first">An <see cref="IEnumerable{T}" /> whose distinct elements that also appear in <paramref name="second" /> will be returned.</param> /// <param name="second">An <see cref="IEnumerable{T}" /> whose distinct elements that also appear in the first sequence will be returned.</param> /// <param name="keySelector">A function to extract the key for each element.</param> /// <param name="comparer">An <see cref="IEqualityComparer{TKey}" /> to compare keys.</param> /// <returns>A sequence that contains the elements that form the set intersection of two sequences.</returns> /// <exception cref="ArgumentNullException"><paramref name="first" /> or <paramref name="second" /> is <see langword="null" />.</exception> /// <remarks> /// <para>This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its `GetEnumerator` method directly or by using `foreach` in Visual C# or `For Each` in Visual Basic.</para> /// <para>The intersection of two sets A and B is defined as the set that contains all the elements of A that also appear in B, but no other elements.</para> /// <para>When the object returned by this method is enumerated, `Intersect` yields distinct elements occurring in both sequences in the order in which they appear in <paramref name="first" />.</para> /// <para>If <paramref name="comparer" /> is <see langword="null" />, the default equality comparer, <see cref="EqualityComparer{T}.Default" />, is used to compare values.</para> /// </remarks> public static IEnumerable<TSource> IntersectBy<TSource, TKey>(this IEnumerable<TSource> first, IEnumerable<TKey> second, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer) { if (first is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.first); } if (second is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.second); } if (keySelector is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keySelector); } return IntersectByIterator(first, second, keySelector, comparer); } private static IEnumerable<TSource> IntersectIterator<TSource>(IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource>? comparer) { var set = new HashSet<TSource>(second, comparer); foreach (TSource element in first) { if (set.Remove(element)) { yield return element; } } } private static IEnumerable<TSource> IntersectByIterator<TSource, TKey>(IEnumerable<TSource> first, IEnumerable<TKey> second, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer) { var set = new HashSet<TKey>(second, comparer); foreach (TSource element in first) { if (set.Remove(keySelector(element))) { yield return element; } } } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/Performance/CodeQuality/Math/Functions/Single/CoshSingle.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 Functions { public static partial class MathTests { // Tests MathF.Cosh(float) over 5000 iterations for the domain -1, +1 private const float coshSingleDelta = 0.0004f; private const float coshSingleExpectedResult = 5876.02588f; public static void CoshSingleTest() { var result = 0.0f; var value = -1.0f; for (var iteration = 0; iteration < iterations; iteration++) { value += coshSingleDelta; result += MathF.Cosh(value); } var diff = MathF.Abs(coshSingleExpectedResult - result); if (diff > singleEpsilon) { throw new Exception($"Expected Result {coshSingleExpectedResult,10:g9}; Actual Result {result,10:g9}"); } } } }
// 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 Functions { public static partial class MathTests { // Tests MathF.Cosh(float) over 5000 iterations for the domain -1, +1 private const float coshSingleDelta = 0.0004f; private const float coshSingleExpectedResult = 5876.02588f; public static void CoshSingleTest() { var result = 0.0f; var value = -1.0f; for (var iteration = 0; iteration < iterations; iteration++) { value += coshSingleDelta; result += MathF.Cosh(value); } var diff = MathF.Abs(coshSingleExpectedResult - result); if (diff > singleEpsilon) { throw new Exception($"Expected Result {coshSingleExpectedResult,10:g9}; Actual Result {result,10:g9}"); } } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Data.Common/src/System/Data/Common/DbException.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.Data.Common { [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public abstract class DbException : System.Runtime.InteropServices.ExternalException { protected DbException() : base() { } protected DbException(string? message) : base(message) { } protected DbException(string? message, System.Exception? innerException) : base(message, innerException) { } protected DbException(string? message, int errorCode) : base(message, errorCode) { } protected DbException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Indicates whether the error represented by this <see cref="DbException" /> could be a transient error, i.e. if retrying the triggering /// operation may succeed without any other change. Examples of transient errors include failure to acquire a database lock, networking /// issues. This allows automatic retry execution strategies to be developed without knowledge of specific database error codes. /// </summary> public virtual bool IsTransient => false; /// <summary> /// <para> /// For database providers which support it, contains a standard SQL 5-character return code indicating the success or failure of /// the database operation. The first 2 characters represent the <strong>class</strong> of the return code (e.g. error, success), /// while the last 3 characters represent the <strong>subclass</strong>, allowing detection of error scenarios in a /// database-portable way. /// </para> /// <para> /// For database providers which don't support it, or for inapplicable error scenarios, contains <see langword="null" />. /// </para> /// </summary> /// <returns> /// A standard SQL 5-character return code, or <see langword="null" />. /// </returns> public virtual string? SqlState => null; public DbBatchCommand? BatchCommand => DbBatchCommand; protected virtual DbBatchCommand? DbBatchCommand => null; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Data.Common { [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public abstract class DbException : System.Runtime.InteropServices.ExternalException { protected DbException() : base() { } protected DbException(string? message) : base(message) { } protected DbException(string? message, System.Exception? innerException) : base(message, innerException) { } protected DbException(string? message, int errorCode) : base(message, errorCode) { } protected DbException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Indicates whether the error represented by this <see cref="DbException" /> could be a transient error, i.e. if retrying the triggering /// operation may succeed without any other change. Examples of transient errors include failure to acquire a database lock, networking /// issues. This allows automatic retry execution strategies to be developed without knowledge of specific database error codes. /// </summary> public virtual bool IsTransient => false; /// <summary> /// <para> /// For database providers which support it, contains a standard SQL 5-character return code indicating the success or failure of /// the database operation. The first 2 characters represent the <strong>class</strong> of the return code (e.g. error, success), /// while the last 3 characters represent the <strong>subclass</strong>, allowing detection of error scenarios in a /// database-portable way. /// </para> /// <para> /// For database providers which don't support it, or for inapplicable error scenarios, contains <see langword="null" />. /// </para> /// </summary> /// <returns> /// A standard SQL 5-character return code, or <see langword="null" />. /// </returns> public virtual string? SqlState => null; public DbBatchCommand? BatchCommand => DbBatchCommand; protected virtual DbBatchCommand? DbBatchCommand => null; } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/Loader/classloader/methodoverriding/regressions/577403/vsw577403.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="vsw577403.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="vsw577403.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/jit64/valuetypes/nullable/box-unbox/value/box-unbox-value016.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 System; internal class NullableTest { private static bool BoxUnboxToNQ(ValueType o) { return Helper.Compare((Guid)o, Helper.Create(default(Guid))); } private static bool BoxUnboxToQ(ValueType o) { return Helper.Compare((Guid?)o, Helper.Create(default(Guid))); } private static int Main() { Guid? s = Helper.Create(default(Guid)); if (BoxUnboxToNQ(s) && BoxUnboxToQ(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
// 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 System; internal class NullableTest { private static bool BoxUnboxToNQ(ValueType o) { return Helper.Compare((Guid)o, Helper.Create(default(Guid))); } private static bool BoxUnboxToQ(ValueType o) { return Helper.Compare((Guid?)o, Helper.Create(default(Guid))); } private static int Main() { Guid? s = Helper.Create(default(Guid)); if (BoxUnboxToNQ(s) && BoxUnboxToQ(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/HardwareIntrinsics/General/Vector128/Min.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\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 MinSByte() { var test = new VectorBinaryOpTest__MinSByte(); // 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__MinSByte { 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, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<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 Vector128<SByte> _fld1; public Vector128<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<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__MinSByte testClass) { var result = Vector128.Min(_fld1, _fld2); 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<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = 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 SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<SByte> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<SByte> _fld1; private Vector128<SByte> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__MinSByte() { 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>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public VectorBinaryOpTest__MinSByte() { 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 < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<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 SByte[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.Min( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<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 method = typeof(Vector128).GetMethod(nameof(Vector128.Min), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.Min), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(SByte)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.Min( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = Vector128.Min(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__MinSByte(); var result = Vector128.Min(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.Min(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.Min(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector128<SByte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[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<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); 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]; 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 inArray2[0]), ref Unsafe.AsRef<byte>(op2), (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, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((left[0] < right[0]) ? left[0] : right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] < right[i]) ? left[i] : right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.Min)}<SByte>(Vector128<SByte>, Vector128<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\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 MinSByte() { var test = new VectorBinaryOpTest__MinSByte(); // 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__MinSByte { 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, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<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 Vector128<SByte> _fld1; public Vector128<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<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__MinSByte testClass) { var result = Vector128.Min(_fld1, _fld2); 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<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = 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 SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<SByte> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<SByte> _fld1; private Vector128<SByte> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__MinSByte() { 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>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public VectorBinaryOpTest__MinSByte() { 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 < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<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 SByte[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.Min( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<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 method = typeof(Vector128).GetMethod(nameof(Vector128.Min), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.Min), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(SByte)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.Min( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = Vector128.Min(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__MinSByte(); var result = Vector128.Min(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.Min(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.Min(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector128<SByte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[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<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); 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]; 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 inArray2[0]), ref Unsafe.AsRef<byte>(op2), (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, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((left[0] < right[0]) ? left[0] : right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] < right[i]) ? left[i] : right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.Min)}<SByte>(Vector128<SByte>, Vector128<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
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Pal.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; using System.Diagnostics; using System.Formats.Asn1; using System.IO; using System.Security.Cryptography; using System.Security.Cryptography.Asn1; namespace System.Security.Cryptography.X509Certificates { internal static partial class X509Pal { private static partial IX509Pal BuildSingleton() { return new AndroidX509Pal(); } private sealed partial class AndroidX509Pal : ManagedX509ExtensionProcessor, IX509Pal { public ECDsa DecodeECDsaPublicKey(ICertificatePal? certificatePal) { if (certificatePal == null) throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); return new ECDsaImplementation.ECDsaAndroid(DecodeECPublicKey(certificatePal)); } public ECDiffieHellman DecodeECDiffieHellmanPublicKey(ICertificatePal? certificatePal) { if (certificatePal == null) throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); return new ECDiffieHellmanImplementation.ECDiffieHellmanAndroid(DecodeECPublicKey(certificatePal)); } public AsymmetricAlgorithm DecodePublicKey(Oid oid, byte[] encodedKeyValue, byte[] encodedParameters, ICertificatePal? certificatePal) { switch (oid.Value) { case Oids.Dsa: if (certificatePal != null) { var handle = new SafeDsaHandle(GetPublicKey(certificatePal, Interop.AndroidCrypto.PAL_KeyAlgorithm.DSA)); return new DSAImplementation.DSAAndroid(handle); } else { return DecodeDsaPublicKey(encodedKeyValue, encodedParameters); } case Oids.Rsa: if (certificatePal != null) { var handle = new SafeRsaHandle(GetPublicKey(certificatePal, Interop.AndroidCrypto.PAL_KeyAlgorithm.RSA)); return new RSAImplementation.RSAAndroid(handle); } else { return DecodeRsaPublicKey(encodedKeyValue); } default: throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); } } public string X500DistinguishedNameDecode(byte[] encodedDistinguishedName, X500DistinguishedNameFlags flag) { return X500NameEncoder.X500DistinguishedNameDecode(encodedDistinguishedName, true, flag); } public byte[] X500DistinguishedNameEncode(string distinguishedName, X500DistinguishedNameFlags flag) { return X500NameEncoder.X500DistinguishedNameEncode(distinguishedName, flag); } public string X500DistinguishedNameFormat(byte[] encodedDistinguishedName, bool multiLine) { return X500NameEncoder.X500DistinguishedNameDecode( encodedDistinguishedName, true, multiLine ? X500DistinguishedNameFlags.UseNewLines : X500DistinguishedNameFlags.None, multiLine); } public X509ContentType GetCertContentType(ReadOnlySpan<byte> rawData) { if (rawData == null || rawData.Length == 0) throw new CryptographicException(); X509ContentType contentType = Interop.AndroidCrypto.X509GetContentType(rawData); if (contentType != X509ContentType.Unknown) { return contentType; } if (AndroidPkcs12Reader.IsPkcs12(rawData)) { return X509ContentType.Pkcs12; } // Throw on unknown type to match Unix and Windows throw new CryptographicException(SR.Cryptography_UnknownCertContentType); } public X509ContentType GetCertContentType(string fileName) { return GetCertContentType(File.ReadAllBytes(fileName)); } private static SafeEcKeyHandle DecodeECPublicKey(ICertificatePal pal) { return new SafeEcKeyHandle(GetPublicKey(pal, Interop.AndroidCrypto.PAL_KeyAlgorithm.EC)); } private static IntPtr GetPublicKey(ICertificatePal pal, Interop.AndroidCrypto.PAL_KeyAlgorithm algorithm) { AndroidCertificatePal certPal = (AndroidCertificatePal)pal; IntPtr ptr = Interop.AndroidCrypto.X509GetPublicKey(certPal.SafeHandle, algorithm); if (ptr == IntPtr.Zero) throw new CryptographicException(); return ptr; } private static RSA DecodeRsaPublicKey(byte[] encodedKeyValue) { RSA rsa = RSA.Create(); try { rsa.ImportRSAPublicKey(new ReadOnlySpan<byte>(encodedKeyValue), out _); return rsa; } catch (Exception) { rsa.Dispose(); throw; } } private static DSA DecodeDsaPublicKey(byte[] encodedKeyValue, byte[] encodedParameters) { SubjectPublicKeyInfoAsn spki = new SubjectPublicKeyInfoAsn { Algorithm = new AlgorithmIdentifierAsn { Algorithm = Oids.Dsa, Parameters = encodedParameters }, SubjectPublicKey = encodedKeyValue, }; AsnWriter writer = new AsnWriter(AsnEncodingRules.DER); spki.Encode(writer); byte[] rented = CryptoPool.Rent(writer.GetEncodedLength()); int written = writer.Encode(rented); DSA dsa = DSA.Create(); IDisposable? toDispose = dsa; try { dsa.ImportSubjectPublicKeyInfo(rented.AsSpan(0, written), out _); toDispose = null; return dsa; } finally { toDispose?.Dispose(); CryptoPool.Return(rented, written); } } } } }
// 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; using System.Formats.Asn1; using System.IO; using System.Security.Cryptography; using System.Security.Cryptography.Asn1; namespace System.Security.Cryptography.X509Certificates { internal static partial class X509Pal { private static partial IX509Pal BuildSingleton() { return new AndroidX509Pal(); } private sealed partial class AndroidX509Pal : ManagedX509ExtensionProcessor, IX509Pal { public ECDsa DecodeECDsaPublicKey(ICertificatePal? certificatePal) { if (certificatePal == null) throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); return new ECDsaImplementation.ECDsaAndroid(DecodeECPublicKey(certificatePal)); } public ECDiffieHellman DecodeECDiffieHellmanPublicKey(ICertificatePal? certificatePal) { if (certificatePal == null) throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); return new ECDiffieHellmanImplementation.ECDiffieHellmanAndroid(DecodeECPublicKey(certificatePal)); } public AsymmetricAlgorithm DecodePublicKey(Oid oid, byte[] encodedKeyValue, byte[] encodedParameters, ICertificatePal? certificatePal) { switch (oid.Value) { case Oids.Dsa: if (certificatePal != null) { var handle = new SafeDsaHandle(GetPublicKey(certificatePal, Interop.AndroidCrypto.PAL_KeyAlgorithm.DSA)); return new DSAImplementation.DSAAndroid(handle); } else { return DecodeDsaPublicKey(encodedKeyValue, encodedParameters); } case Oids.Rsa: if (certificatePal != null) { var handle = new SafeRsaHandle(GetPublicKey(certificatePal, Interop.AndroidCrypto.PAL_KeyAlgorithm.RSA)); return new RSAImplementation.RSAAndroid(handle); } else { return DecodeRsaPublicKey(encodedKeyValue); } default: throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); } } public string X500DistinguishedNameDecode(byte[] encodedDistinguishedName, X500DistinguishedNameFlags flag) { return X500NameEncoder.X500DistinguishedNameDecode(encodedDistinguishedName, true, flag); } public byte[] X500DistinguishedNameEncode(string distinguishedName, X500DistinguishedNameFlags flag) { return X500NameEncoder.X500DistinguishedNameEncode(distinguishedName, flag); } public string X500DistinguishedNameFormat(byte[] encodedDistinguishedName, bool multiLine) { return X500NameEncoder.X500DistinguishedNameDecode( encodedDistinguishedName, true, multiLine ? X500DistinguishedNameFlags.UseNewLines : X500DistinguishedNameFlags.None, multiLine); } public X509ContentType GetCertContentType(ReadOnlySpan<byte> rawData) { if (rawData == null || rawData.Length == 0) throw new CryptographicException(); X509ContentType contentType = Interop.AndroidCrypto.X509GetContentType(rawData); if (contentType != X509ContentType.Unknown) { return contentType; } if (AndroidPkcs12Reader.IsPkcs12(rawData)) { return X509ContentType.Pkcs12; } // Throw on unknown type to match Unix and Windows throw new CryptographicException(SR.Cryptography_UnknownCertContentType); } public X509ContentType GetCertContentType(string fileName) { return GetCertContentType(File.ReadAllBytes(fileName)); } private static SafeEcKeyHandle DecodeECPublicKey(ICertificatePal pal) { return new SafeEcKeyHandle(GetPublicKey(pal, Interop.AndroidCrypto.PAL_KeyAlgorithm.EC)); } private static IntPtr GetPublicKey(ICertificatePal pal, Interop.AndroidCrypto.PAL_KeyAlgorithm algorithm) { AndroidCertificatePal certPal = (AndroidCertificatePal)pal; IntPtr ptr = Interop.AndroidCrypto.X509GetPublicKey(certPal.SafeHandle, algorithm); if (ptr == IntPtr.Zero) throw new CryptographicException(); return ptr; } private static RSA DecodeRsaPublicKey(byte[] encodedKeyValue) { RSA rsa = RSA.Create(); try { rsa.ImportRSAPublicKey(new ReadOnlySpan<byte>(encodedKeyValue), out _); return rsa; } catch (Exception) { rsa.Dispose(); throw; } } private static DSA DecodeDsaPublicKey(byte[] encodedKeyValue, byte[] encodedParameters) { SubjectPublicKeyInfoAsn spki = new SubjectPublicKeyInfoAsn { Algorithm = new AlgorithmIdentifierAsn { Algorithm = Oids.Dsa, Parameters = encodedParameters }, SubjectPublicKey = encodedKeyValue, }; AsnWriter writer = new AsnWriter(AsnEncodingRules.DER); spki.Encode(writer); byte[] rented = CryptoPool.Rent(writer.GetEncodedLength()); int written = writer.Encode(rented); DSA dsa = DSA.Create(); IDisposable? toDispose = dsa; try { dsa.ImportSubjectPublicKeyInfo(rented.AsSpan(0, written), out _); toDispose = null; return dsa; } finally { toDispose?.Dispose(); CryptoPool.Return(rented, written); } } } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.DirectoryServices/src/System/DirectoryServices/ReferalChasingOption.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.DirectoryServices { /// <devdoc> /// Specifies if and how referral chasing is pursued. /// </devdoc> public enum ReferralChasingOption { /// <devdoc> /// Never chase the referred-to server. Setting this option /// prevents a client from contacting other servers in a referral process. /// </devdoc> None = 0, /// <devdoc> /// Chase only subordinate referrals which are a subordinate naming context in a /// directory tree. The ADSI LDAP provider always turns off this flag for paged /// searches. /// </devdoc> Subordinate = 0x20, /// <devdoc> /// Chase external referrals. /// </devdoc> External = 0x40, /// <devdoc> /// Chase referrals of either the subordinate or external type. /// </devdoc> All = Subordinate | External } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.DirectoryServices { /// <devdoc> /// Specifies if and how referral chasing is pursued. /// </devdoc> public enum ReferralChasingOption { /// <devdoc> /// Never chase the referred-to server. Setting this option /// prevents a client from contacting other servers in a referral process. /// </devdoc> None = 0, /// <devdoc> /// Chase only subordinate referrals which are a subordinate naming context in a /// directory tree. The ADSI LDAP provider always turns off this flag for paged /// searches. /// </devdoc> Subordinate = 0x20, /// <devdoc> /// Chase external referrals. /// </devdoc> External = 0x40, /// <devdoc> /// Chase referrals of either the subordinate or external type. /// </devdoc> All = Subordinate | External } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Collections/tests/Generic/SortedDictionary/SortedDictionary.Generic.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.Collections.Tests { public class SortedDictionary_Generic_Tests_string_string : SortedDictionary_Generic_Tests<string, string> { protected override KeyValuePair<string, string> CreateT(int seed) { return new KeyValuePair<string, string>(CreateTKey(seed), CreateTKey(seed + 500)); } protected override string CreateTKey(int seed) { int stringLength = seed % 10 + 5; Random rand = new Random(seed); byte[] bytes1 = new byte[stringLength]; rand.NextBytes(bytes1); return Convert.ToBase64String(bytes1); } protected override string CreateTValue(int seed) { return CreateTKey(seed); } } public class SortedDictionary_Generic_Tests_int_int : SortedDictionary_Generic_Tests<int, int> { protected override bool DefaultValueAllowed { get { return true; } } protected override KeyValuePair<int, int> CreateT(int seed) { Random rand = new Random(seed); return new KeyValuePair<int, int>(rand.Next(), rand.Next()); } protected override int CreateTKey(int seed) { Random rand = new Random(seed); return rand.Next(); } protected override int CreateTValue(int seed) { return CreateTKey(seed); } } [OuterLoop] public class SortedDictionary_Generic_Tests_EquatableBackwardsOrder_int : SortedDictionary_Generic_Tests<EquatableBackwardsOrder, int> { protected override KeyValuePair<EquatableBackwardsOrder, int> CreateT(int seed) { Random rand = new Random(seed); return new KeyValuePair<EquatableBackwardsOrder, int>(new EquatableBackwardsOrder(rand.Next()), rand.Next()); } protected override EquatableBackwardsOrder CreateTKey(int seed) { Random rand = new Random(seed); return new EquatableBackwardsOrder(rand.Next()); } protected override int CreateTValue(int seed) { Random rand = new Random(seed); return rand.Next(); } protected override IDictionary<EquatableBackwardsOrder, int> GenericIDictionaryFactory() { return new SortedDictionary<EquatableBackwardsOrder, int>(); } } }
// 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.Collections.Tests { public class SortedDictionary_Generic_Tests_string_string : SortedDictionary_Generic_Tests<string, string> { protected override KeyValuePair<string, string> CreateT(int seed) { return new KeyValuePair<string, string>(CreateTKey(seed), CreateTKey(seed + 500)); } protected override string CreateTKey(int seed) { int stringLength = seed % 10 + 5; Random rand = new Random(seed); byte[] bytes1 = new byte[stringLength]; rand.NextBytes(bytes1); return Convert.ToBase64String(bytes1); } protected override string CreateTValue(int seed) { return CreateTKey(seed); } } public class SortedDictionary_Generic_Tests_int_int : SortedDictionary_Generic_Tests<int, int> { protected override bool DefaultValueAllowed { get { return true; } } protected override KeyValuePair<int, int> CreateT(int seed) { Random rand = new Random(seed); return new KeyValuePair<int, int>(rand.Next(), rand.Next()); } protected override int CreateTKey(int seed) { Random rand = new Random(seed); return rand.Next(); } protected override int CreateTValue(int seed) { return CreateTKey(seed); } } [OuterLoop] public class SortedDictionary_Generic_Tests_EquatableBackwardsOrder_int : SortedDictionary_Generic_Tests<EquatableBackwardsOrder, int> { protected override KeyValuePair<EquatableBackwardsOrder, int> CreateT(int seed) { Random rand = new Random(seed); return new KeyValuePair<EquatableBackwardsOrder, int>(new EquatableBackwardsOrder(rand.Next()), rand.Next()); } protected override EquatableBackwardsOrder CreateTKey(int seed) { Random rand = new Random(seed); return new EquatableBackwardsOrder(rand.Next()); } protected override int CreateTValue(int seed) { Random rand = new Random(seed); return rand.Next(); } protected override IDictionary<EquatableBackwardsOrder, int> GenericIDictionaryFactory() { return new SortedDictionary<EquatableBackwardsOrder, int>(); } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/CSharpSetIndexBinder.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.Dynamic; using System.Numerics.Hashing; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Semantics; namespace Microsoft.CSharp.RuntimeBinder { /// <summary> /// Represents a dynamic indexer access in C#, providing the binding semantics and the details about the operation. /// Instances of this class are generated by the C# compiler. /// </summary> internal sealed class CSharpSetIndexBinder : SetIndexBinder, ICSharpBinder { public string Name => SpecialNames.Indexer; public BindingFlag BindingFlags => 0; [RequiresUnreferencedCode(Binder.TrimmerWarning)] public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals) => runtimeBinder.BindAssignment(this, arguments, locals); [RequiresUnreferencedCode(Binder.TrimmerWarning)] public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments) => SymbolTable.PopulateSymbolTableWithName(SpecialNames.Indexer, null, arguments[0].Type); public bool IsBinderThatCanHaveRefReceiver => true; internal bool IsCompoundAssignment { get; } private readonly CSharpArgumentInfo[] _argumentInfo; CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index) => _argumentInfo[index]; private readonly RuntimeBinder _binder; private readonly Type _callingContext; private bool IsChecked => _binder.IsChecked; ////////////////////////////////////////////////////////////////////// /// <summary> /// Initializes a new instance of the <see cref="CSharpSetIndexBinder" />. /// </summary> /// <param name="isCompoundAssignment">True if the assignment comes from a compound assignment in source.</param> /// <param name="isChecked">True if the operation is defined in a checked context; otherwise, false.</param> /// <param name="callingContext">The <see cref="Type"/> that indicates where this operation is defined.</param> /// <param name="argumentInfo">The sequence of <see cref="CSharpArgumentInfo"/> instances for the arguments to this operation.</param> [RequiresUnreferencedCode(Binder.TrimmerWarning)] public CSharpSetIndexBinder( bool isCompoundAssignment, bool isChecked, Type callingContext, IEnumerable<CSharpArgumentInfo> argumentInfo) : base(BinderHelper.CreateCallInfo(ref argumentInfo, 2)) // discard 2 arguments: the target object and the value { IsCompoundAssignment = isCompoundAssignment; _argumentInfo = argumentInfo as CSharpArgumentInfo[]; _callingContext = callingContext; _binder = new RuntimeBinder(callingContext, isChecked); } public int GetGetBinderEquivalenceHash() { int hash = _callingContext?.GetHashCode() ?? 0; if (IsChecked) { hash = HashHelpers.Combine(hash, 1); } if (IsCompoundAssignment) { hash = HashHelpers.Combine(hash, 1); } hash = BinderHelper.AddArgHashes(hash, _argumentInfo); return hash; } public bool IsEquivalentTo(ICSharpBinder other) { var otherBinder = other as CSharpSetIndexBinder; if (otherBinder == null) { return false; } if (_callingContext != otherBinder._callingContext || IsChecked != otherBinder.IsChecked || IsCompoundAssignment != otherBinder.IsCompoundAssignment || _argumentInfo.Length != otherBinder._argumentInfo.Length) { return false; } return BinderHelper.CompareArgInfos(_argumentInfo, otherBinder._argumentInfo); } /// <summary> /// Performs the binding of the dynamic set index operation if the target dynamic object cannot bind. /// </summary> /// <param name="target">The target of the dynamic set index operation.</param> /// <param name="indexes">The arguments of the dynamic set index operation.</param> /// <param name="value">The value to set to the collection.</param> /// <param name="errorSuggestion">The binding result to use if binding fails, or null.</param> /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This whole class is unsafe. Constructors are marked as such.")] public override DynamicMetaObject FallbackSetIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject value, DynamicMetaObject errorSuggestion) { #if ENABLECOMBINDER DynamicMetaObject com; if (ComInterop.ComBinder.TryBindSetIndex(this, target, indexes, value, out com)) { return com; } #else BinderHelper.ThrowIfUsingDynamicCom(target); #endif BinderHelper.ValidateBindArgument(target, nameof(target)); BinderHelper.ValidateBindArgument(indexes, nameof(indexes)); BinderHelper.ValidateBindArgument(value, nameof(value)); return BinderHelper.Bind(this, _binder, BinderHelper.Cons(target, indexes, value), _argumentInfo, errorSuggestion); } } }
// 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.Dynamic; using System.Numerics.Hashing; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Semantics; namespace Microsoft.CSharp.RuntimeBinder { /// <summary> /// Represents a dynamic indexer access in C#, providing the binding semantics and the details about the operation. /// Instances of this class are generated by the C# compiler. /// </summary> internal sealed class CSharpSetIndexBinder : SetIndexBinder, ICSharpBinder { public string Name => SpecialNames.Indexer; public BindingFlag BindingFlags => 0; [RequiresUnreferencedCode(Binder.TrimmerWarning)] public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals) => runtimeBinder.BindAssignment(this, arguments, locals); [RequiresUnreferencedCode(Binder.TrimmerWarning)] public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments) => SymbolTable.PopulateSymbolTableWithName(SpecialNames.Indexer, null, arguments[0].Type); public bool IsBinderThatCanHaveRefReceiver => true; internal bool IsCompoundAssignment { get; } private readonly CSharpArgumentInfo[] _argumentInfo; CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index) => _argumentInfo[index]; private readonly RuntimeBinder _binder; private readonly Type _callingContext; private bool IsChecked => _binder.IsChecked; ////////////////////////////////////////////////////////////////////// /// <summary> /// Initializes a new instance of the <see cref="CSharpSetIndexBinder" />. /// </summary> /// <param name="isCompoundAssignment">True if the assignment comes from a compound assignment in source.</param> /// <param name="isChecked">True if the operation is defined in a checked context; otherwise, false.</param> /// <param name="callingContext">The <see cref="Type"/> that indicates where this operation is defined.</param> /// <param name="argumentInfo">The sequence of <see cref="CSharpArgumentInfo"/> instances for the arguments to this operation.</param> [RequiresUnreferencedCode(Binder.TrimmerWarning)] public CSharpSetIndexBinder( bool isCompoundAssignment, bool isChecked, Type callingContext, IEnumerable<CSharpArgumentInfo> argumentInfo) : base(BinderHelper.CreateCallInfo(ref argumentInfo, 2)) // discard 2 arguments: the target object and the value { IsCompoundAssignment = isCompoundAssignment; _argumentInfo = argumentInfo as CSharpArgumentInfo[]; _callingContext = callingContext; _binder = new RuntimeBinder(callingContext, isChecked); } public int GetGetBinderEquivalenceHash() { int hash = _callingContext?.GetHashCode() ?? 0; if (IsChecked) { hash = HashHelpers.Combine(hash, 1); } if (IsCompoundAssignment) { hash = HashHelpers.Combine(hash, 1); } hash = BinderHelper.AddArgHashes(hash, _argumentInfo); return hash; } public bool IsEquivalentTo(ICSharpBinder other) { var otherBinder = other as CSharpSetIndexBinder; if (otherBinder == null) { return false; } if (_callingContext != otherBinder._callingContext || IsChecked != otherBinder.IsChecked || IsCompoundAssignment != otherBinder.IsCompoundAssignment || _argumentInfo.Length != otherBinder._argumentInfo.Length) { return false; } return BinderHelper.CompareArgInfos(_argumentInfo, otherBinder._argumentInfo); } /// <summary> /// Performs the binding of the dynamic set index operation if the target dynamic object cannot bind. /// </summary> /// <param name="target">The target of the dynamic set index operation.</param> /// <param name="indexes">The arguments of the dynamic set index operation.</param> /// <param name="value">The value to set to the collection.</param> /// <param name="errorSuggestion">The binding result to use if binding fails, or null.</param> /// <returns>The <see cref="DynamicMetaObject"/> representing the result of the binding.</returns> [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This whole class is unsafe. Constructors are marked as such.")] public override DynamicMetaObject FallbackSetIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject value, DynamicMetaObject errorSuggestion) { #if ENABLECOMBINDER DynamicMetaObject com; if (ComInterop.ComBinder.TryBindSetIndex(this, target, indexes, value, out com)) { return com; } #else BinderHelper.ThrowIfUsingDynamicCom(target); #endif BinderHelper.ValidateBindArgument(target, nameof(target)); BinderHelper.ValidateBindArgument(indexes, nameof(indexes)); BinderHelper.ValidateBindArgument(value, nameof(value)); return BinderHelper.Bind(this, _binder, BinderHelper.Cons(target, indexes, value), _argumentInfo, errorSuggestion); } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/Common/tests/System/ShouldNotBeInvokedException.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 { internal class ShouldNotBeInvokedException : Exception { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System { internal class ShouldNotBeInvokedException : Exception { } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/ReadyToRunCompilerContext.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.TypeSystem; using Debug = System.Diagnostics.Debug; namespace ILCompiler { partial class CompilerTypeSystemContext { public CompilerTypeSystemContext(TargetDetails details, SharedGenericsMode genericsMode) : base(details) { _genericsMode = genericsMode; } internal DefType GetClosestDefType(TypeDesc type) { if (type.IsArray) { return GetWellKnownType(WellKnownType.Array); } Debug.Assert(type is DefType); return (DefType)type; } } public partial class ReadyToRunCompilerContext : CompilerTypeSystemContext { private ReadyToRunMetadataFieldLayoutAlgorithm _r2rFieldLayoutAlgorithm; private SystemObjectFieldLayoutAlgorithm _systemObjectFieldLayoutAlgorithm; private VectorOfTFieldLayoutAlgorithm _vectorOfTFieldLayoutAlgorithm; private VectorFieldLayoutAlgorithm _vectorFieldLayoutAlgorithm; private Int128FieldLayoutAlgorithm _int128FieldLayoutAlgorithm; public ReadyToRunCompilerContext(TargetDetails details, SharedGenericsMode genericsMode, bool bubbleIncludesCorelib, CompilerTypeSystemContext oldTypeSystemContext = null) : base(details, genericsMode) { _r2rFieldLayoutAlgorithm = new ReadyToRunMetadataFieldLayoutAlgorithm(); _systemObjectFieldLayoutAlgorithm = new SystemObjectFieldLayoutAlgorithm(_r2rFieldLayoutAlgorithm); // Only the Arm64 JIT respects the OS rules for vector type abi currently _vectorFieldLayoutAlgorithm = new VectorFieldLayoutAlgorithm(_r2rFieldLayoutAlgorithm, (details.Architecture == TargetArchitecture.ARM64) ? true : bubbleIncludesCorelib); string matchingVectorType = "Unknown"; if (details.MaximumSimdVectorLength == SimdVectorLength.Vector128Bit) matchingVectorType = "Vector128`1"; else if (details.MaximumSimdVectorLength == SimdVectorLength.Vector256Bit) matchingVectorType = "Vector256`1"; // No architecture has completely stable handling of Vector<T> in the abi (Arm64 may change to SVE) _vectorOfTFieldLayoutAlgorithm = new VectorOfTFieldLayoutAlgorithm(_r2rFieldLayoutAlgorithm, _vectorFieldLayoutAlgorithm, matchingVectorType, bubbleIncludesCorelib); // Int128 and UInt128 should be ABI stable on all currently supported platforms _int128FieldLayoutAlgorithm = new Int128FieldLayoutAlgorithm(_r2rFieldLayoutAlgorithm); if (oldTypeSystemContext != null) { InheritOpenModules(oldTypeSystemContext); } } public override FieldLayoutAlgorithm GetLayoutAlgorithmForType(DefType type) { if (type.IsObject) return _systemObjectFieldLayoutAlgorithm; else if (type == UniversalCanonType) throw new NotImplementedException(); else if (type.IsRuntimeDeterminedType) throw new NotImplementedException(); else if (VectorOfTFieldLayoutAlgorithm.IsVectorOfTType(type)) { return _vectorOfTFieldLayoutAlgorithm; } else if (VectorFieldLayoutAlgorithm.IsVectorType(type)) { return _vectorFieldLayoutAlgorithm; } else if (Int128FieldLayoutAlgorithm.IsIntegerType(type)) { return _int128FieldLayoutAlgorithm; } else { Debug.Assert(_r2rFieldLayoutAlgorithm != null); return _r2rFieldLayoutAlgorithm; } } /// <summary> /// This is a rough equivalent of the CoreCLR runtime method ReadyToRunInfo::GetFieldBaseOffset. /// In contrast to the auto field layout algorithm, this method unconditionally applies alignment /// between base and derived class (even when they reside in the same version bubble). /// </summary> public LayoutInt CalculateFieldBaseOffset(MetadataType type) => _r2rFieldLayoutAlgorithm.CalculateFieldBaseOffset(type, type.RequiresAlign8(), requiresAlignedBase: true); public void SetCompilationGroup(ReadyToRunCompilationModuleGroupBase compilationModuleGroup) { _r2rFieldLayoutAlgorithm.SetCompilationGroup(compilationModuleGroup); } /// <summary> /// Prevent any synthetic methods being added to types in the base CompilerTypeSystemContext /// </summary> /// <param name="type"></param> /// <returns></returns> protected override IEnumerable<MethodDesc> GetAllMethods(TypeDesc type) { return type.GetMethods(); } protected override bool ComputeHasGCStaticBase(FieldDesc field) { Debug.Assert(field.IsStatic); TypeDesc fieldType = field.FieldType; if (fieldType.IsValueType) { return !fieldType.IsPrimitive && !fieldType.IsEnum; // In CoreCLR, all structs are implicitly boxed i.e. stored as GC pointers } else { return fieldType.IsGCPointer; } } /// <summary> /// CoreCLR has no Array`1 type to hang the various generic interfaces off. /// Return nothing at compile time so the runtime figures it out. /// </summary> protected override RuntimeInterfacesAlgorithm GetRuntimeInterfacesAlgorithmForNonPointerArrayType(ArrayType type) { return BaseTypeRuntimeInterfacesAlgorithm.Instance; } } internal class VectorOfTFieldLayoutAlgorithm : FieldLayoutAlgorithm { private FieldLayoutAlgorithm _fallbackAlgorithm; private FieldLayoutAlgorithm _vectorFallbackAlgorithm; private string _similarVectorName; private DefType _similarVectorOpenType; private bool _vectorAbiIsStable; public VectorOfTFieldLayoutAlgorithm(FieldLayoutAlgorithm fallbackAlgorithm, FieldLayoutAlgorithm vectorFallbackAlgorithm, string similarVector, bool vectorAbiIsStable = true) { _fallbackAlgorithm = fallbackAlgorithm; _vectorFallbackAlgorithm = vectorFallbackAlgorithm; _similarVectorName = similarVector; _vectorAbiIsStable = vectorAbiIsStable; } private DefType GetSimilarVector(DefType vectorOfTType) { if (_similarVectorOpenType == null) { if (_similarVectorName == "Unknown") return null; _similarVectorOpenType = ((MetadataType)vectorOfTType.GetTypeDefinition()).Module.GetType("System.Runtime.Intrinsics", _similarVectorName); } return ((MetadataType)_similarVectorOpenType).MakeInstantiatedType(vectorOfTType.Instantiation); } public override bool ComputeContainsGCPointers(DefType type) { return false; } public override bool ComputeIsUnsafeValueType(DefType type) { return false; } public override ComputedInstanceFieldLayout ComputeInstanceLayout(DefType type, InstanceLayoutKind layoutKind) { DefType similarSpecifiedVector = GetSimilarVector(type); if (similarSpecifiedVector == null) { List<FieldAndOffset> fieldsAndOffsets = new List<FieldAndOffset>(); foreach (FieldDesc field in type.GetFields()) { if (!field.IsStatic) { fieldsAndOffsets.Add(new FieldAndOffset(field, LayoutInt.Indeterminate)); } } ComputedInstanceFieldLayout instanceLayout = new ComputedInstanceFieldLayout() { FieldSize = LayoutInt.Indeterminate, FieldAlignment = LayoutInt.Indeterminate, ByteCountUnaligned = LayoutInt.Indeterminate, ByteCountAlignment = LayoutInt.Indeterminate, Offsets = fieldsAndOffsets.ToArray(), LayoutAbiStable = false, }; return instanceLayout; } else { ComputedInstanceFieldLayout layoutFromMetadata = _fallbackAlgorithm.ComputeInstanceLayout(type, layoutKind); ComputedInstanceFieldLayout layoutFromSimilarIntrinsicVector = _vectorFallbackAlgorithm.ComputeInstanceLayout(similarSpecifiedVector, layoutKind); // TODO, enable this code when we switch Vector<T> to follow the same calling convention as its matching similar intrinsic vector #if MATCHING_HARDWARE_VECTOR return new ComputedInstanceFieldLayout { ByteCountUnaligned = layoutFromSimilarIntrinsicVector.ByteCountUnaligned, ByteCountAlignment = layoutFromSimilarIntrinsicVector.ByteCountAlignment, FieldAlignment = layoutFromSimilarIntrinsicVector.FieldAlignment, FieldSize = layoutFromSimilarIntrinsicVector.FieldSize, Offsets = layoutFromMetadata.Offsets, LayoutAbiStable = _vectorAbiIsStable, }; #else return new ComputedInstanceFieldLayout { ByteCountUnaligned = layoutFromSimilarIntrinsicVector.ByteCountUnaligned, ByteCountAlignment = layoutFromMetadata.ByteCountAlignment, FieldAlignment = layoutFromMetadata.FieldAlignment, FieldSize = layoutFromSimilarIntrinsicVector.FieldSize, Offsets = layoutFromMetadata.Offsets, LayoutAbiStable = _vectorAbiIsStable, }; #endif } } public override ComputedStaticFieldLayout ComputeStaticFieldLayout(DefType type, StaticLayoutKind layoutKind) { return _fallbackAlgorithm.ComputeStaticFieldLayout(type, layoutKind); } public override ValueTypeShapeCharacteristics ComputeValueTypeShapeCharacteristics(DefType type) { if (type.Context.Target.Architecture == TargetArchitecture.ARM64) { return type.InstanceFieldSize.AsInt switch { 16 => ValueTypeShapeCharacteristics.Vector128Aggregate, _ => ValueTypeShapeCharacteristics.None }; } return ValueTypeShapeCharacteristics.None; } public static bool IsVectorOfTType(DefType type) { return type.IsIntrinsic && type.Namespace == "System.Numerics" && type.Name == "Vector`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.Collections.Generic; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace ILCompiler { partial class CompilerTypeSystemContext { public CompilerTypeSystemContext(TargetDetails details, SharedGenericsMode genericsMode) : base(details) { _genericsMode = genericsMode; } internal DefType GetClosestDefType(TypeDesc type) { if (type.IsArray) { return GetWellKnownType(WellKnownType.Array); } Debug.Assert(type is DefType); return (DefType)type; } } public partial class ReadyToRunCompilerContext : CompilerTypeSystemContext { private ReadyToRunMetadataFieldLayoutAlgorithm _r2rFieldLayoutAlgorithm; private SystemObjectFieldLayoutAlgorithm _systemObjectFieldLayoutAlgorithm; private VectorOfTFieldLayoutAlgorithm _vectorOfTFieldLayoutAlgorithm; private VectorFieldLayoutAlgorithm _vectorFieldLayoutAlgorithm; private Int128FieldLayoutAlgorithm _int128FieldLayoutAlgorithm; public ReadyToRunCompilerContext(TargetDetails details, SharedGenericsMode genericsMode, bool bubbleIncludesCorelib, CompilerTypeSystemContext oldTypeSystemContext = null) : base(details, genericsMode) { _r2rFieldLayoutAlgorithm = new ReadyToRunMetadataFieldLayoutAlgorithm(); _systemObjectFieldLayoutAlgorithm = new SystemObjectFieldLayoutAlgorithm(_r2rFieldLayoutAlgorithm); // Only the Arm64 JIT respects the OS rules for vector type abi currently _vectorFieldLayoutAlgorithm = new VectorFieldLayoutAlgorithm(_r2rFieldLayoutAlgorithm, (details.Architecture == TargetArchitecture.ARM64) ? true : bubbleIncludesCorelib); string matchingVectorType = "Unknown"; if (details.MaximumSimdVectorLength == SimdVectorLength.Vector128Bit) matchingVectorType = "Vector128`1"; else if (details.MaximumSimdVectorLength == SimdVectorLength.Vector256Bit) matchingVectorType = "Vector256`1"; // No architecture has completely stable handling of Vector<T> in the abi (Arm64 may change to SVE) _vectorOfTFieldLayoutAlgorithm = new VectorOfTFieldLayoutAlgorithm(_r2rFieldLayoutAlgorithm, _vectorFieldLayoutAlgorithm, matchingVectorType, bubbleIncludesCorelib); // Int128 and UInt128 should be ABI stable on all currently supported platforms _int128FieldLayoutAlgorithm = new Int128FieldLayoutAlgorithm(_r2rFieldLayoutAlgorithm); if (oldTypeSystemContext != null) { InheritOpenModules(oldTypeSystemContext); } } public override FieldLayoutAlgorithm GetLayoutAlgorithmForType(DefType type) { if (type.IsObject) return _systemObjectFieldLayoutAlgorithm; else if (type == UniversalCanonType) throw new NotImplementedException(); else if (type.IsRuntimeDeterminedType) throw new NotImplementedException(); else if (VectorOfTFieldLayoutAlgorithm.IsVectorOfTType(type)) { return _vectorOfTFieldLayoutAlgorithm; } else if (VectorFieldLayoutAlgorithm.IsVectorType(type)) { return _vectorFieldLayoutAlgorithm; } else if (Int128FieldLayoutAlgorithm.IsIntegerType(type)) { return _int128FieldLayoutAlgorithm; } else { Debug.Assert(_r2rFieldLayoutAlgorithm != null); return _r2rFieldLayoutAlgorithm; } } /// <summary> /// This is a rough equivalent of the CoreCLR runtime method ReadyToRunInfo::GetFieldBaseOffset. /// In contrast to the auto field layout algorithm, this method unconditionally applies alignment /// between base and derived class (even when they reside in the same version bubble). /// </summary> public LayoutInt CalculateFieldBaseOffset(MetadataType type) => _r2rFieldLayoutAlgorithm.CalculateFieldBaseOffset(type, type.RequiresAlign8(), requiresAlignedBase: true); public void SetCompilationGroup(ReadyToRunCompilationModuleGroupBase compilationModuleGroup) { _r2rFieldLayoutAlgorithm.SetCompilationGroup(compilationModuleGroup); } /// <summary> /// Prevent any synthetic methods being added to types in the base CompilerTypeSystemContext /// </summary> /// <param name="type"></param> /// <returns></returns> protected override IEnumerable<MethodDesc> GetAllMethods(TypeDesc type) { return type.GetMethods(); } protected override bool ComputeHasGCStaticBase(FieldDesc field) { Debug.Assert(field.IsStatic); TypeDesc fieldType = field.FieldType; if (fieldType.IsValueType) { return !fieldType.IsPrimitive && !fieldType.IsEnum; // In CoreCLR, all structs are implicitly boxed i.e. stored as GC pointers } else { return fieldType.IsGCPointer; } } /// <summary> /// CoreCLR has no Array`1 type to hang the various generic interfaces off. /// Return nothing at compile time so the runtime figures it out. /// </summary> protected override RuntimeInterfacesAlgorithm GetRuntimeInterfacesAlgorithmForNonPointerArrayType(ArrayType type) { return BaseTypeRuntimeInterfacesAlgorithm.Instance; } } internal class VectorOfTFieldLayoutAlgorithm : FieldLayoutAlgorithm { private FieldLayoutAlgorithm _fallbackAlgorithm; private FieldLayoutAlgorithm _vectorFallbackAlgorithm; private string _similarVectorName; private DefType _similarVectorOpenType; private bool _vectorAbiIsStable; public VectorOfTFieldLayoutAlgorithm(FieldLayoutAlgorithm fallbackAlgorithm, FieldLayoutAlgorithm vectorFallbackAlgorithm, string similarVector, bool vectorAbiIsStable = true) { _fallbackAlgorithm = fallbackAlgorithm; _vectorFallbackAlgorithm = vectorFallbackAlgorithm; _similarVectorName = similarVector; _vectorAbiIsStable = vectorAbiIsStable; } private DefType GetSimilarVector(DefType vectorOfTType) { if (_similarVectorOpenType == null) { if (_similarVectorName == "Unknown") return null; _similarVectorOpenType = ((MetadataType)vectorOfTType.GetTypeDefinition()).Module.GetType("System.Runtime.Intrinsics", _similarVectorName); } return ((MetadataType)_similarVectorOpenType).MakeInstantiatedType(vectorOfTType.Instantiation); } public override bool ComputeContainsGCPointers(DefType type) { return false; } public override bool ComputeIsUnsafeValueType(DefType type) { return false; } public override ComputedInstanceFieldLayout ComputeInstanceLayout(DefType type, InstanceLayoutKind layoutKind) { DefType similarSpecifiedVector = GetSimilarVector(type); if (similarSpecifiedVector == null) { List<FieldAndOffset> fieldsAndOffsets = new List<FieldAndOffset>(); foreach (FieldDesc field in type.GetFields()) { if (!field.IsStatic) { fieldsAndOffsets.Add(new FieldAndOffset(field, LayoutInt.Indeterminate)); } } ComputedInstanceFieldLayout instanceLayout = new ComputedInstanceFieldLayout() { FieldSize = LayoutInt.Indeterminate, FieldAlignment = LayoutInt.Indeterminate, ByteCountUnaligned = LayoutInt.Indeterminate, ByteCountAlignment = LayoutInt.Indeterminate, Offsets = fieldsAndOffsets.ToArray(), LayoutAbiStable = false, }; return instanceLayout; } else { ComputedInstanceFieldLayout layoutFromMetadata = _fallbackAlgorithm.ComputeInstanceLayout(type, layoutKind); ComputedInstanceFieldLayout layoutFromSimilarIntrinsicVector = _vectorFallbackAlgorithm.ComputeInstanceLayout(similarSpecifiedVector, layoutKind); // TODO, enable this code when we switch Vector<T> to follow the same calling convention as its matching similar intrinsic vector #if MATCHING_HARDWARE_VECTOR return new ComputedInstanceFieldLayout { ByteCountUnaligned = layoutFromSimilarIntrinsicVector.ByteCountUnaligned, ByteCountAlignment = layoutFromSimilarIntrinsicVector.ByteCountAlignment, FieldAlignment = layoutFromSimilarIntrinsicVector.FieldAlignment, FieldSize = layoutFromSimilarIntrinsicVector.FieldSize, Offsets = layoutFromMetadata.Offsets, LayoutAbiStable = _vectorAbiIsStable, }; #else return new ComputedInstanceFieldLayout { ByteCountUnaligned = layoutFromSimilarIntrinsicVector.ByteCountUnaligned, ByteCountAlignment = layoutFromMetadata.ByteCountAlignment, FieldAlignment = layoutFromMetadata.FieldAlignment, FieldSize = layoutFromSimilarIntrinsicVector.FieldSize, Offsets = layoutFromMetadata.Offsets, LayoutAbiStable = _vectorAbiIsStable, }; #endif } } public override ComputedStaticFieldLayout ComputeStaticFieldLayout(DefType type, StaticLayoutKind layoutKind) { return _fallbackAlgorithm.ComputeStaticFieldLayout(type, layoutKind); } public override ValueTypeShapeCharacteristics ComputeValueTypeShapeCharacteristics(DefType type) { if (type.Context.Target.Architecture == TargetArchitecture.ARM64) { return type.InstanceFieldSize.AsInt switch { 16 => ValueTypeShapeCharacteristics.Vector128Aggregate, _ => ValueTypeShapeCharacteristics.None }; } return ValueTypeShapeCharacteristics.None; } public static bool IsVectorOfTType(DefType type) { return type.IsIntrinsic && type.Namespace == "System.Numerics" && type.Name == "Vector`1"; } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicNFA.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #if DEBUG using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Represents the exploration of a symbolic regex as a symbolic NFA</summary> internal sealed class SymbolicNFA<TSet> where TSet : IComparable<TSet>, IEquatable<TSet> { private readonly ISolver<TSet> _solver; private readonly Transition[] _transitionFunction; private readonly SymbolicRegexNode<TSet>[] _finalCondition; private readonly HashSet<int> _unexplored; private readonly SymbolicRegexNode<TSet>[] _nodes; private const int DeadendState = -1; private const int UnexploredState = -2; /// <summary>If true then some states have not been explored</summary> public bool IsIncomplete => _unexplored.Count > 0; private SymbolicNFA(ISolver<TSet> solver, Transition[] transitionFunction, HashSet<int> unexplored, SymbolicRegexNode<TSet>[] nodes) { Debug.Assert(transitionFunction.Length > 0 && nodes.Length == transitionFunction.Length); _solver = solver; _transitionFunction = transitionFunction; _finalCondition = new SymbolicRegexNode<TSet>[nodes.Length]; for (int i = 0; i < nodes.Length; i++) { _finalCondition[i] = nodes[i].ExtractNullabilityTest(); } _unexplored = unexplored; _nodes = nodes; } /// <summary>Total number of states, 0 is the initial state, states are numbered from 0 to StateCount-1</summary> public int StateCount => _transitionFunction.Length; /// <summary>If true then the state has not been explored</summary> public bool IsUnexplored(int state) => _transitionFunction[state]._leaf == UnexploredState; /// <summary>If true then the state has no outgoing transitions</summary> public bool IsDeadend(int state) => _transitionFunction[state]._leaf == DeadendState; /// <summary>If true then the state involves lazy loops or has no loops</summary> public bool IsLazy(int state) => _nodes[state].IsLazy; /// <summary>Returns true if the state is nullable in the given context</summary> public bool IsFinal(int state, uint context) => _finalCondition[state].IsNullableFor(context); /// <summary>Returns true if the state is nullable for some context</summary> public bool CanBeNullable(int state) => _finalCondition[state].CanBeNullable; /// <summary>Returns true if the state is nullable for all contexts</summary> public bool IsNullable(int state) => _finalCondition[state].IsNullable; /// <summary>Gets the underlying node of the state</summary> public SymbolicRegexNode<TSet> GetNode(int state) => _nodes[state]; /// <summary>Enumerates all target states from the given source state</summary> /// <param name="sourceState">must be a an integer between 0 and StateCount-1</param> /// <param name="input">must be a value that acts as a minterm for the transitions emanating from the source state</param> /// <param name="context">reflects the immediate surrounding of the input and is used to determine nullability of anchors</param> public IEnumerable<int> EnumerateTargetStates(int sourceState, TSet input, uint context) { Debug.Assert(sourceState >= 0 && sourceState < _transitionFunction.Length); // First operate in a mode assuming no Union happens by finding the target leaf state if one exists Transition transition = _transitionFunction[sourceState]; while (transition._kind != TransitionRegexKind.Union) { switch (transition._kind) { case TransitionRegexKind.Leaf: // deadend and unexplored are negative if (transition._leaf >= 0) { Debug.Assert(transition._leaf < _transitionFunction.Length); yield return transition._leaf; } // The single target (or no target) state was found, so exit the whole enumeration yield break; case TransitionRegexKind.Conditional: Debug.Assert(transition._test is not null && transition._first is not null && transition._second is not null); // Branch according to the input condition in relation to the test condition if (!_solver.IsEmpty(_solver.And(input, transition._test))) { // in a conditional transition input must be exclusive Debug.Assert(_solver.IsEmpty(_solver.And(input, _solver.Not(transition._test)))); transition = transition._first; } else { transition = transition._second; } break; default: Debug.Assert(transition._kind == TransitionRegexKind.Lookaround && transition._look is not null && transition._first is not null && transition._second is not null); // Branch according to nullability of the lookaround condition in the given context transition = transition._look.IsNullableFor(context) ? transition._first : transition._second; break; } } // Continue operating in a mode where several target states can be yielded Debug.Assert(transition._first is not null && transition._second is not null); Stack<Transition> todo = new(); todo.Push(transition._second); todo.Push(transition._first); while (todo.TryPop(out _)) { switch (transition._kind) { case TransitionRegexKind.Leaf: // dead-end if (transition._leaf >= 0) { Debug.Assert(transition._leaf < _transitionFunction.Length); yield return transition._leaf; } break; case TransitionRegexKind.Conditional: Debug.Assert(transition._test is not null && transition._first is not null && transition._second is not null); // Branch according to the input condition in relation to the test condition if (!_solver.IsEmpty(_solver.And(input, transition._test))) { // in a conditional transition input must be exclusive Debug.Assert(_solver.IsEmpty(_solver.And(input, _solver.Not(transition._test)))); todo.Push(transition._first); } else { todo.Push(transition._second); } break; case TransitionRegexKind.Lookaround: Debug.Assert(transition._look is not null && transition._first is not null && transition._second is not null); // Branch according to nullability of the lookaround condition in the given context todo.Push(transition._look.IsNullableFor(context) ? transition._first : transition._second); break; default: Debug.Assert(transition._kind == TransitionRegexKind.Union && transition._first is not null && transition._second is not null); todo.Push(transition._second); todo.Push(transition._first); break; } } } public IEnumerable<(TSet, SymbolicRegexNode<TSet>?, int)> EnumeratePaths(int sourceState) => _transitionFunction[sourceState].EnumeratePaths(_solver, _solver.Full); public static SymbolicNFA<TSet> Explore(SymbolicRegexNode<TSet> root, int bound) { (Dictionary<TransitionRegex<TSet>, Transition> cache, Dictionary<SymbolicRegexNode<TSet>, int> statemap, List<SymbolicRegexNode<TSet>> nodes, Stack<int> front) workState = (new(), new(), new(), new()); workState.nodes.Add(root); workState.statemap[root] = 0; workState.front.Push(0); Dictionary<int, Transition> transitions = new(); Stack<int> front = new(); while (workState.front.Count > 0) { Debug.Assert(front.Count == 0); // Work Breadth-First in layers, swap front with workState.front Stack<int> tmp = front; front = workState.front; workState.front = tmp; // Process all the states in front first // Any new states detected in Convert are added to workState.front while (front.Count > 0 && (bound <= 0 || workState.nodes.Count < bound)) { int q = front.Pop(); // If q was on the front it must be associated with a node but not have a transition yet Debug.Assert(q >= 0 && q < workState.nodes.Count && !transitions.ContainsKey(q)); transitions[q] = Convert(workState.nodes[q].CreateDerivative(), workState); } if (front.Count > 0) { // The state bound was reached without completing the exploration so exit the loop break; } } SymbolicRegexNode<TSet>[] nodes_array = workState.nodes.ToArray(); // All states are numbered from 0 to nodes.Count-1 Transition[] transition_array = new Transition[nodes_array.Length]; foreach (KeyValuePair<int, SymbolicNFA<TSet>.Transition> entry in transitions) { transition_array[entry.Key] = entry.Value; } HashSet<int> unexplored = new(front); unexplored.UnionWith(workState.front); foreach (int q in unexplored) { transition_array[q] = Transition.s_unexplored; } // At this point no entry can be null in the transition array Debug.Assert(Array.TrueForAll(transition_array, tr => tr is not null)); var nfa = new SymbolicNFA<TSet>(root._builder._solver, transition_array, unexplored, nodes_array); return nfa; } private static Transition Convert(TransitionRegex<TSet> tregex, (Dictionary<TransitionRegex<TSet>, Transition> cache, Dictionary<SymbolicRegexNode<TSet>, int> statemap, List<SymbolicRegexNode<TSet>> nodes, Stack<int> front) args) { Transition? transition; if (args.cache.TryGetValue(tregex, out transition)) { return transition; } Stack<(TransitionRegex<TSet>, bool)> work = new(); work.Push((tregex, false)); while (work.TryPop(out (TransitionRegex<TSet>, bool) top)) { TransitionRegex<TSet> tr = top.Item1; bool wasPushedSecondTime = top.Item2; if (wasPushedSecondTime) { Debug.Assert(tr._kind != TransitionRegexKind.Leaf && tr._first is not null && tr._second is not null); transition = new Transition(kind: tr._kind, test: tr._test, look: tr._node, first: args.cache[tr._first], second: args.cache[tr._second]); args.cache[tr] = transition; } else { switch (tr._kind) { case TransitionRegexKind.Leaf: Debug.Assert(tr._node is not null); if (tr._node.IsNothing) { args.cache[tr] = Transition.s_deadend; } else { int state; if (!args.statemap.TryGetValue(tr._node, out state)) { state = args.nodes.Count; args.nodes.Add(tr._node); args.statemap[tr._node] = state; args.front.Push(state); } transition = new Transition(kind: TransitionRegexKind.Leaf, leaf: state); args.cache[tr] = transition; } break; default: Debug.Assert(tr._first is not null && tr._second is not null); // Push the tr for the second time work.Push((tr, true)); // Push the branches also, unless they have been computed already if (!args.cache.ContainsKey(tr._second)) { work.Push((tr._second, false)); } if (!args.cache.ContainsKey(tr._first)) { work.Push((tr._first, false)); } break; } } } return args.cache[tregex]; } /// <summary>Representation of transitions inside the parent class</summary> private sealed class Transition { public readonly TransitionRegexKind _kind; public readonly int _leaf; public readonly TSet? _test; public readonly SymbolicRegexNode<TSet>? _look; public readonly Transition? _first; public readonly Transition? _second; public static readonly Transition s_deadend = new Transition(TransitionRegexKind.Leaf, leaf: DeadendState); public static readonly Transition s_unexplored = new Transition(TransitionRegexKind.Leaf, leaf: UnexploredState); internal Transition(TransitionRegexKind kind, int leaf = 0, TSet? test = default(TSet), SymbolicRegexNode<TSet>? look = null, Transition? first = null, Transition? second = null) { _kind = kind; _leaf = leaf; _test = test; _look = look; _first = first; _second = second; } /// <summary>Enumerates all the paths in this transition excluding paths to dead-ends (and unexplored states if any)</summary> internal IEnumerable<(TSet, SymbolicRegexNode<TSet>?, int)> EnumeratePaths(ISolver<TSet> solver, TSet pathCondition) { switch (_kind) { case TransitionRegexKind.Leaf: // Omit any path that leads to a deadend or is unexplored if (_leaf >= 0) { yield return (pathCondition, null, _leaf); } break; case TransitionRegexKind.Union: Debug.Assert(_first is not null && _second is not null); foreach ((TSet, SymbolicRegexNode<TSet>?, int) path in _first.EnumeratePaths(solver, pathCondition)) { yield return path; } foreach ((TSet, SymbolicRegexNode<TSet>?, int) path in _second.EnumeratePaths(solver, pathCondition)) { yield return path; } break; case TransitionRegexKind.Conditional: Debug.Assert(_test is not null && _first is not null && _second is not null); foreach ((TSet, SymbolicRegexNode<TSet>?, int) path in _first.EnumeratePaths(solver, solver.And(pathCondition, _test))) { yield return path; } foreach ((TSet, SymbolicRegexNode<TSet>?, int) path in _second.EnumeratePaths(solver, solver.And(pathCondition, solver.Not(_test)))) { yield return path; } break; default: Debug.Assert(_kind is TransitionRegexKind.Lookaround && _look is not null && _first is not null && _second is not null); foreach ((TSet, SymbolicRegexNode<TSet>?, int) path in _first.EnumeratePaths(solver, pathCondition)) { SymbolicRegexNode<TSet> nullabilityTest = path.Item2 is null ? _look : _look._builder.And(path.Item2, _look); yield return (path.Item1, nullabilityTest, path.Item3); } foreach ((TSet, SymbolicRegexNode<TSet>?, int) path in _second.EnumeratePaths(solver, pathCondition)) { // Complement the nullability test SymbolicRegexNode<TSet> nullabilityTest = path.Item2 is null ? _look._builder.Not(_look) : _look._builder.And(path.Item2, _look._builder.Not(_look)); yield return (path.Item1, nullabilityTest, path.Item3); } break; } } } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #if DEBUG using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Represents the exploration of a symbolic regex as a symbolic NFA</summary> internal sealed class SymbolicNFA<TSet> where TSet : IComparable<TSet>, IEquatable<TSet> { private readonly ISolver<TSet> _solver; private readonly Transition[] _transitionFunction; private readonly SymbolicRegexNode<TSet>[] _finalCondition; private readonly HashSet<int> _unexplored; private readonly SymbolicRegexNode<TSet>[] _nodes; private const int DeadendState = -1; private const int UnexploredState = -2; /// <summary>If true then some states have not been explored</summary> public bool IsIncomplete => _unexplored.Count > 0; private SymbolicNFA(ISolver<TSet> solver, Transition[] transitionFunction, HashSet<int> unexplored, SymbolicRegexNode<TSet>[] nodes) { Debug.Assert(transitionFunction.Length > 0 && nodes.Length == transitionFunction.Length); _solver = solver; _transitionFunction = transitionFunction; _finalCondition = new SymbolicRegexNode<TSet>[nodes.Length]; for (int i = 0; i < nodes.Length; i++) { _finalCondition[i] = nodes[i].ExtractNullabilityTest(); } _unexplored = unexplored; _nodes = nodes; } /// <summary>Total number of states, 0 is the initial state, states are numbered from 0 to StateCount-1</summary> public int StateCount => _transitionFunction.Length; /// <summary>If true then the state has not been explored</summary> public bool IsUnexplored(int state) => _transitionFunction[state]._leaf == UnexploredState; /// <summary>If true then the state has no outgoing transitions</summary> public bool IsDeadend(int state) => _transitionFunction[state]._leaf == DeadendState; /// <summary>If true then the state involves lazy loops or has no loops</summary> public bool IsLazy(int state) => _nodes[state].IsLazy; /// <summary>Returns true if the state is nullable in the given context</summary> public bool IsFinal(int state, uint context) => _finalCondition[state].IsNullableFor(context); /// <summary>Returns true if the state is nullable for some context</summary> public bool CanBeNullable(int state) => _finalCondition[state].CanBeNullable; /// <summary>Returns true if the state is nullable for all contexts</summary> public bool IsNullable(int state) => _finalCondition[state].IsNullable; /// <summary>Gets the underlying node of the state</summary> public SymbolicRegexNode<TSet> GetNode(int state) => _nodes[state]; /// <summary>Enumerates all target states from the given source state</summary> /// <param name="sourceState">must be a an integer between 0 and StateCount-1</param> /// <param name="input">must be a value that acts as a minterm for the transitions emanating from the source state</param> /// <param name="context">reflects the immediate surrounding of the input and is used to determine nullability of anchors</param> public IEnumerable<int> EnumerateTargetStates(int sourceState, TSet input, uint context) { Debug.Assert(sourceState >= 0 && sourceState < _transitionFunction.Length); // First operate in a mode assuming no Union happens by finding the target leaf state if one exists Transition transition = _transitionFunction[sourceState]; while (transition._kind != TransitionRegexKind.Union) { switch (transition._kind) { case TransitionRegexKind.Leaf: // deadend and unexplored are negative if (transition._leaf >= 0) { Debug.Assert(transition._leaf < _transitionFunction.Length); yield return transition._leaf; } // The single target (or no target) state was found, so exit the whole enumeration yield break; case TransitionRegexKind.Conditional: Debug.Assert(transition._test is not null && transition._first is not null && transition._second is not null); // Branch according to the input condition in relation to the test condition if (!_solver.IsEmpty(_solver.And(input, transition._test))) { // in a conditional transition input must be exclusive Debug.Assert(_solver.IsEmpty(_solver.And(input, _solver.Not(transition._test)))); transition = transition._first; } else { transition = transition._second; } break; default: Debug.Assert(transition._kind == TransitionRegexKind.Lookaround && transition._look is not null && transition._first is not null && transition._second is not null); // Branch according to nullability of the lookaround condition in the given context transition = transition._look.IsNullableFor(context) ? transition._first : transition._second; break; } } // Continue operating in a mode where several target states can be yielded Debug.Assert(transition._first is not null && transition._second is not null); Stack<Transition> todo = new(); todo.Push(transition._second); todo.Push(transition._first); while (todo.TryPop(out _)) { switch (transition._kind) { case TransitionRegexKind.Leaf: // dead-end if (transition._leaf >= 0) { Debug.Assert(transition._leaf < _transitionFunction.Length); yield return transition._leaf; } break; case TransitionRegexKind.Conditional: Debug.Assert(transition._test is not null && transition._first is not null && transition._second is not null); // Branch according to the input condition in relation to the test condition if (!_solver.IsEmpty(_solver.And(input, transition._test))) { // in a conditional transition input must be exclusive Debug.Assert(_solver.IsEmpty(_solver.And(input, _solver.Not(transition._test)))); todo.Push(transition._first); } else { todo.Push(transition._second); } break; case TransitionRegexKind.Lookaround: Debug.Assert(transition._look is not null && transition._first is not null && transition._second is not null); // Branch according to nullability of the lookaround condition in the given context todo.Push(transition._look.IsNullableFor(context) ? transition._first : transition._second); break; default: Debug.Assert(transition._kind == TransitionRegexKind.Union && transition._first is not null && transition._second is not null); todo.Push(transition._second); todo.Push(transition._first); break; } } } public IEnumerable<(TSet, SymbolicRegexNode<TSet>?, int)> EnumeratePaths(int sourceState) => _transitionFunction[sourceState].EnumeratePaths(_solver, _solver.Full); public static SymbolicNFA<TSet> Explore(SymbolicRegexNode<TSet> root, int bound) { (Dictionary<TransitionRegex<TSet>, Transition> cache, Dictionary<SymbolicRegexNode<TSet>, int> statemap, List<SymbolicRegexNode<TSet>> nodes, Stack<int> front) workState = (new(), new(), new(), new()); workState.nodes.Add(root); workState.statemap[root] = 0; workState.front.Push(0); Dictionary<int, Transition> transitions = new(); Stack<int> front = new(); while (workState.front.Count > 0) { Debug.Assert(front.Count == 0); // Work Breadth-First in layers, swap front with workState.front Stack<int> tmp = front; front = workState.front; workState.front = tmp; // Process all the states in front first // Any new states detected in Convert are added to workState.front while (front.Count > 0 && (bound <= 0 || workState.nodes.Count < bound)) { int q = front.Pop(); // If q was on the front it must be associated with a node but not have a transition yet Debug.Assert(q >= 0 && q < workState.nodes.Count && !transitions.ContainsKey(q)); transitions[q] = Convert(workState.nodes[q].CreateDerivative(), workState); } if (front.Count > 0) { // The state bound was reached without completing the exploration so exit the loop break; } } SymbolicRegexNode<TSet>[] nodes_array = workState.nodes.ToArray(); // All states are numbered from 0 to nodes.Count-1 Transition[] transition_array = new Transition[nodes_array.Length]; foreach (KeyValuePair<int, SymbolicNFA<TSet>.Transition> entry in transitions) { transition_array[entry.Key] = entry.Value; } HashSet<int> unexplored = new(front); unexplored.UnionWith(workState.front); foreach (int q in unexplored) { transition_array[q] = Transition.s_unexplored; } // At this point no entry can be null in the transition array Debug.Assert(Array.TrueForAll(transition_array, tr => tr is not null)); var nfa = new SymbolicNFA<TSet>(root._builder._solver, transition_array, unexplored, nodes_array); return nfa; } private static Transition Convert(TransitionRegex<TSet> tregex, (Dictionary<TransitionRegex<TSet>, Transition> cache, Dictionary<SymbolicRegexNode<TSet>, int> statemap, List<SymbolicRegexNode<TSet>> nodes, Stack<int> front) args) { Transition? transition; if (args.cache.TryGetValue(tregex, out transition)) { return transition; } Stack<(TransitionRegex<TSet>, bool)> work = new(); work.Push((tregex, false)); while (work.TryPop(out (TransitionRegex<TSet>, bool) top)) { TransitionRegex<TSet> tr = top.Item1; bool wasPushedSecondTime = top.Item2; if (wasPushedSecondTime) { Debug.Assert(tr._kind != TransitionRegexKind.Leaf && tr._first is not null && tr._second is not null); transition = new Transition(kind: tr._kind, test: tr._test, look: tr._node, first: args.cache[tr._first], second: args.cache[tr._second]); args.cache[tr] = transition; } else { switch (tr._kind) { case TransitionRegexKind.Leaf: Debug.Assert(tr._node is not null); if (tr._node.IsNothing) { args.cache[tr] = Transition.s_deadend; } else { int state; if (!args.statemap.TryGetValue(tr._node, out state)) { state = args.nodes.Count; args.nodes.Add(tr._node); args.statemap[tr._node] = state; args.front.Push(state); } transition = new Transition(kind: TransitionRegexKind.Leaf, leaf: state); args.cache[tr] = transition; } break; default: Debug.Assert(tr._first is not null && tr._second is not null); // Push the tr for the second time work.Push((tr, true)); // Push the branches also, unless they have been computed already if (!args.cache.ContainsKey(tr._second)) { work.Push((tr._second, false)); } if (!args.cache.ContainsKey(tr._first)) { work.Push((tr._first, false)); } break; } } } return args.cache[tregex]; } /// <summary>Representation of transitions inside the parent class</summary> private sealed class Transition { public readonly TransitionRegexKind _kind; public readonly int _leaf; public readonly TSet? _test; public readonly SymbolicRegexNode<TSet>? _look; public readonly Transition? _first; public readonly Transition? _second; public static readonly Transition s_deadend = new Transition(TransitionRegexKind.Leaf, leaf: DeadendState); public static readonly Transition s_unexplored = new Transition(TransitionRegexKind.Leaf, leaf: UnexploredState); internal Transition(TransitionRegexKind kind, int leaf = 0, TSet? test = default(TSet), SymbolicRegexNode<TSet>? look = null, Transition? first = null, Transition? second = null) { _kind = kind; _leaf = leaf; _test = test; _look = look; _first = first; _second = second; } /// <summary>Enumerates all the paths in this transition excluding paths to dead-ends (and unexplored states if any)</summary> internal IEnumerable<(TSet, SymbolicRegexNode<TSet>?, int)> EnumeratePaths(ISolver<TSet> solver, TSet pathCondition) { switch (_kind) { case TransitionRegexKind.Leaf: // Omit any path that leads to a deadend or is unexplored if (_leaf >= 0) { yield return (pathCondition, null, _leaf); } break; case TransitionRegexKind.Union: Debug.Assert(_first is not null && _second is not null); foreach ((TSet, SymbolicRegexNode<TSet>?, int) path in _first.EnumeratePaths(solver, pathCondition)) { yield return path; } foreach ((TSet, SymbolicRegexNode<TSet>?, int) path in _second.EnumeratePaths(solver, pathCondition)) { yield return path; } break; case TransitionRegexKind.Conditional: Debug.Assert(_test is not null && _first is not null && _second is not null); foreach ((TSet, SymbolicRegexNode<TSet>?, int) path in _first.EnumeratePaths(solver, solver.And(pathCondition, _test))) { yield return path; } foreach ((TSet, SymbolicRegexNode<TSet>?, int) path in _second.EnumeratePaths(solver, solver.And(pathCondition, solver.Not(_test)))) { yield return path; } break; default: Debug.Assert(_kind is TransitionRegexKind.Lookaround && _look is not null && _first is not null && _second is not null); foreach ((TSet, SymbolicRegexNode<TSet>?, int) path in _first.EnumeratePaths(solver, pathCondition)) { SymbolicRegexNode<TSet> nullabilityTest = path.Item2 is null ? _look : _look._builder.And(path.Item2, _look); yield return (path.Item1, nullabilityTest, path.Item3); } foreach ((TSet, SymbolicRegexNode<TSet>?, int) path in _second.EnumeratePaths(solver, pathCondition)) { // Complement the nullability test SymbolicRegexNode<TSet> nullabilityTest = path.Item2 is null ? _look._builder.Not(_look) : _look._builder.And(path.Item2, _look._builder.Not(_look)); yield return (path.Item1, nullabilityTest, path.Item3); } break; } } } } } #endif
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/Regression/JitBlue/Runtime_45090/Runtime_45090.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <DebugType>None</DebugType> <Optimize>True</Optimize> <AllowUnsafeBlocks>True</AllowUnsafeBlocks> <CLRTestBatchPreCommands><![CDATA[ $(CLRTestBatchPreCommands) set COMPlus_GCStress=0xC ]]></CLRTestBatchPreCommands> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <DebugType>None</DebugType> <Optimize>True</Optimize> <AllowUnsafeBlocks>True</AllowUnsafeBlocks> <CLRTestBatchPreCommands><![CDATA[ $(CLRTestBatchPreCommands) set COMPlus_GCStress=0xC ]]></CLRTestBatchPreCommands> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/Generics/Locals/instance_equalnull_class01.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 ValX0 { } public struct ValY0 { } public struct ValX1<T> { } public struct ValY1<T> { } public struct ValX2<T, U> { } public struct ValY2<T, U> { } public struct ValX3<T, U, V> { } public struct ValY3<T, U, V> { } public class RefX0 { } public class RefY0 { } public class RefX1<T> { } public class RefY1<T> { } public class RefX2<T, U> { } public class RefY2<T, U> { } public class RefX3<T, U, V> { } public class RefY3<T, U, V> { } public class Gen<T> { public bool EqualNull(T t) { T Fld1 = t; return ((object)Fld1 == null); } } public class Test_instance_equalnull_class01 { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { int _int = 0; Eval(false == new Gen<int>().EqualNull(_int)); double _double = 0; Eval(false == new Gen<double>().EqualNull(_double)); Guid _Guid = new Guid(); Eval(false == new Gen<Guid>().EqualNull(_Guid)); string _string = "string"; Eval(false == new Gen<string>().EqualNull(_string)); Eval(true == new Gen<string>().EqualNull(null)); object _object = new object(); Eval(false == new Gen<object>().EqualNull(_string)); Eval(true == new Gen<object>().EqualNull(null)); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; public struct ValX0 { } public struct ValY0 { } public struct ValX1<T> { } public struct ValY1<T> { } public struct ValX2<T, U> { } public struct ValY2<T, U> { } public struct ValX3<T, U, V> { } public struct ValY3<T, U, V> { } public class RefX0 { } public class RefY0 { } public class RefX1<T> { } public class RefY1<T> { } public class RefX2<T, U> { } public class RefY2<T, U> { } public class RefX3<T, U, V> { } public class RefY3<T, U, V> { } public class Gen<T> { public bool EqualNull(T t) { T Fld1 = t; return ((object)Fld1 == null); } } public class Test_instance_equalnull_class01 { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { int _int = 0; Eval(false == new Gen<int>().EqualNull(_int)); double _double = 0; Eval(false == new Gen<double>().EqualNull(_double)); Guid _Guid = new Guid(); Eval(false == new Gen<Guid>().EqualNull(_Guid)); string _string = "string"; Eval(false == new Gen<string>().EqualNull(_string)); Eval(true == new Gen<string>().EqualNull(null)); object _object = new object(); Eval(false == new Gen<object>().EqualNull(_string)); Eval(true == new Gen<object>().EqualNull(null)); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Linq.Parallel/tests/QueryOperators/SelectSelectManyTests.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.Concurrent; using System.Collections.Generic; using Xunit; namespace System.Linq.Parallel.Tests { public static class SelectSelectManyTests { [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Select_Unordered(int count) { IntegerRangeSet seen = new IntegerRangeSet(0, count); foreach (var p in UnorderedSources.Default(count).Select(x => KeyValuePair.Create(x, x * x))) { seen.Add(p.Key); Assert.Equal(p.Key * p.Key, p.Value); } seen.AssertComplete(); } [Fact] [OuterLoop] public static void Select_Unordered_Longrunning() { Select_Unordered(Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))] public static void Select(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int seen = 0; foreach (var p in query.Select(x => KeyValuePair.Create(x, x * x))) { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key * p.Key, p.Value); } Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), new[] { 1024 * 4 }, MemberType = typeof(Sources))] public static void Select_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select(labeled, count); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Select_Unordered_NotPipelined(int count) { IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.All(UnorderedSources.Default(count).Select(x => KeyValuePair.Create(x, x * x)).ToList(), p => { seen.Add(p.Key); Assert.Equal(p.Key * p.Key, p.Value); }); seen.AssertComplete(); } [Fact] [OuterLoop] public static void Select_Unordered_NotPipelined_Longrunning() { Select_Unordered_NotPipelined(Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))] public static void Select_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int seen = 0; Assert.All(query.Select(x => KeyValuePair.Create(x, x * x)).ToList(), p => { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key * p.Key, p.Value); }); Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), new[] { 1024 * 4 }, MemberType = typeof(Sources))] public static void Select_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select_NotPipelined(labeled, count); } // Uses an element's index to calculate an output value. If order preservation isn't // working, this would PROBABLY fail. Unfortunately, this isn't deterministic. But choosing // larger input sizes increases the probability that it will. [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Select_Indexed_Unordered(int count) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(0, count); foreach (var p in UnorderedSources.Default(count).Select((x, index) => KeyValuePair.Create(x, index))) { seen.Add(p.Key); Assert.Equal(p.Key, p.Value); } seen.AssertComplete(); } [Fact] [OuterLoop] public static void Select_Indexed_Unordered_Longrunning() { Select_Indexed_Unordered(Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))] public static void Select_Indexed(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int seen = 0; foreach (var p in query.Select((x, index) => KeyValuePair.Create(x, index))) { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key, p.Value); } Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), new[] { 1024 * 4 }, MemberType = typeof(Sources))] public static void Select_Indexed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select_Indexed(labeled, count); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Select_Indexed_Unordered_NotPipelined(int count) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.All(UnorderedSources.Default(count).Select((x, index) => KeyValuePair.Create(x, index)).ToList(), p => { seen.Add(p.Key); Assert.Equal(p.Key, p.Value); }); seen.AssertComplete(); } [Fact] [OuterLoop] public static void Select_Indexed_Unordered_NotPipelined_Longrunning() { Select_Indexed_Unordered_NotPipelined(Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))] public static void Select_Indexed_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int seen = 0; Assert.All(query.Select((x, index) => KeyValuePair.Create(x, index)).ToList(), p => { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key, p.Value); }); Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), new[] { 1024 * 4 }, MemberType = typeof(Sources))] public static void Select_Indexed_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select_Indexed_NotPipelined(labeled, count); } [Fact] public static void Select_ArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).Select(x => x)); AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).Select((x, index) => x)); AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Empty<bool>().Select((Func<bool, bool>)null)); AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Empty<bool>().Select((Func<bool, int, bool>)null)); } [Theory] [InlineData(true, true)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(false, false)] public static void Select_OrderablePartitionerWithOutOfOrderInputs_AsOrdered_CorrectOrder(bool keysOrderedInEachPartition, bool keysNormalized) { var range = new RangeOrderablePartitioner(0, 1024, keysOrderedInEachPartition, keysNormalized); int next = 0; foreach (int i in range.AsParallel().AsOrdered().Select(i => i)) { Assert.Equal(next++, i); } } // // SelectMany // // [Regression Test] // An issue occurred because the QuerySettings structure was not being deep-cloned during // query-opening. As a result, the concurrent inner-enumerators (for the RHS operators) // that occur in SelectMany were sharing CancellationState that they should not have. // The result was that enumerators could falsely believe they had been canceled when // another inner-enumerator was disposed. // // Note: the failure was intermittent. this test would fail about 1 in 2 times on mikelid1 (4-core). public static IEnumerable<object[]> SelectManyUnorderedData(int[] counts) { foreach (int count in counts.DefaultIfEmpty(Sources.OuterLoopCount / 64)) { foreach (Labeled<Func<int, int, IEnumerable<int>>> expander in Expanders()) { foreach (int expandCount in new[] { 0, 1, 2, 8 }) { yield return new object[] { count, expander, expandCount }; } } } } public static IEnumerable<object[]> SelectManyData(int[] counts) { foreach (object[] results in Sources.Ranges(counts.DefaultIfEmpty(Sources.OuterLoopCount / 64))) { foreach (Labeled<Func<int, int, IEnumerable<int>>> expander in Expanders()) { foreach (int count in new[] { 0, 1, 2, 8 }) { yield return new object[] { results[0], results[1], expander, count }; } } } } public static IEnumerable<Labeled<Func<int, int, IEnumerable<int>>>> Expanders() { yield return Labeled.Label("Array", (Func<int, int, IEnumerable<int>>)((start, count) => Enumerable.Range(start * count, count).ToArray())); yield return Labeled.Label("Enumerable.Range", (Func<int, int, IEnumerable<int>>)((start, count) => Enumerable.Range(start * count, count))); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Unordered(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); foreach (int i in UnorderedSources.Default(count).SelectMany(x => expand(x, expansion))) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Unordered_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Unordered(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; foreach (int i in query.SelectMany(x => expand(x, expansion))) { Assert.Equal(seen++, i); } Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Unordered_NotPipelined(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); Assert.All(UnorderedSources.Default(count).SelectMany(x => expand(x, expansion)).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Unordered_NotPipelined_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Unordered_NotPipelined(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; Assert.All(query.SelectMany(x => expand(x, expansion)).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_NotPipelined(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Unordered_ResultSelector(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); foreach (var p in UnorderedSources.Default(count).SelectMany(x => expand(x, expansion), (original, expanded) => KeyValuePair.Create(original, expanded))) { seen.Add(p.Value); Assert.Equal(p.Key, p.Value / expansion); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Unordered_ResultSelector_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Unordered_ResultSelector(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Unordered_ResultSelector_NotPipelined(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); Assert.All(UnorderedSources.Default(count).SelectMany(x => expand(x, expansion), (original, expanded) => KeyValuePair.Create(original, expanded)).ToList(), p => { seen.Add(p.Value); Assert.Equal(p.Key, p.Value / expansion); }); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Unordered_ResultSelector_NotPipelined_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Unordered_ResultSelector_NotPipelined(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_ResultSelector(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; foreach (var p in query.SelectMany(x => expand(x, expansion), (original, expanded) => KeyValuePair.Create(original, expanded))) { Assert.Equal(seen++, p.Value); Assert.Equal(p.Key, p.Value / expansion); } Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_ResultSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_ResultSelector(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_ResultSelector_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; Assert.All(query.SelectMany(x => expand(x, expansion), (original, expanded) => KeyValuePair.Create(original, expanded)).ToList(), p => { Assert.Equal(seen++, p.Value); Assert.Equal(p.Key, p.Value / expansion); }); Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_ResultSelector_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_ResultSelector_NotPipelined(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_Unordered(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); foreach (var pIndex in UnorderedSources.Default(count).SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)))) { seen.Add(pIndex.Value); Assert.Equal(pIndex.Key, pIndex.Value / expansion); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_Unordered_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_Unordered(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_Unordered_NotPipelined(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); Assert.All(UnorderedSources.Default(count).SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y))).ToList(), pIndex => { seen.Add(pIndex.Value); Assert.Equal(pIndex.Key, pIndex.Value / expansion); }); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_Unordered_NotPipelined_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_Unordered_NotPipelined(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; foreach (var pIndex in query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)))) { Assert.Equal(seen++, pIndex.Value); Assert.Equal(pIndex.Key, pIndex.Value / expansion); } Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; Assert.All(query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y))).ToList(), pIndex => { Assert.Equal(seen++, pIndex.Value); Assert.Equal(pIndex.Key, pIndex.Value / expansion); }); Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_NotPipelined(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_Unordered_ResultSelector(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); foreach (var pOuter in UnorderedSources.Default(count).SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)), (original, expanded) => KeyValuePair.Create(original, expanded))) { var pInner = pOuter.Value; Assert.Equal(pOuter.Key, pInner.Key); seen.Add(pInner.Value); Assert.Equal(pOuter.Key, pInner.Value / expansion); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_Unordered_ResultSelector_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_Unordered_ResultSelector(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_Unordered_ResultSelector_NotPipelined(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); Assert.All(UnorderedSources.Default(count).SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)), (original, expanded) => KeyValuePair.Create(original, expanded)).ToList(), pOuter => { var pInner = pOuter.Value; Assert.Equal(pOuter.Key, pInner.Key); seen.Add(pInner.Value); Assert.Equal(pOuter.Key, pInner.Value / expansion); }); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_Unordered_ResultSelector_NotPipelined_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_Unordered_ResultSelector_NotPipelined(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_ResultSelector(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; foreach (var pOuter in query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)), (original, expanded) => KeyValuePair.Create(original, expanded))) { var pInner = pOuter.Value; Assert.Equal(pOuter.Key, pInner.Key); Assert.Equal(seen++, pInner.Value); Assert.Equal(pOuter.Key, pInner.Value / expansion); } Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_ResultSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_ResultSelector(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_ResultSelector_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; Assert.All(query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)), (original, expanded) => KeyValuePair.Create(original, expanded)).ToList(), pOuter => { var pInner = pOuter.Value; Assert.Equal(pOuter.Key, pInner.Key); Assert.Equal(seen++, pInner.Value); Assert.Equal(pOuter.Key, pInner.Value / expansion); }); Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_ResultSelector_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_ResultSelector_NotPipelined(labeled, count, expander, expansion); } [Fact] public static void SelectMany_ArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).SelectMany(x => new[] { x })); AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).SelectMany((x, index) => new[] { x })); AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Empty<bool>().SelectMany((Func<bool, IEnumerable<bool>>)null)); AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Empty<bool>().SelectMany((Func<bool, int, IEnumerable<bool>>)null)); AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).SelectMany(x => new[] { x }, (x, y) => x)); AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).SelectMany((x, index) => new[] { x }, (x, y) => x)); AssertExtensions.Throws<ArgumentNullException>("collectionSelector", () => ParallelEnumerable.Empty<bool>().SelectMany((Func<bool, IEnumerable<bool>>)null, (x, y) => x)); AssertExtensions.Throws<ArgumentNullException>("collectionSelector", () => ParallelEnumerable.Empty<bool>().SelectMany((Func<bool, int, IEnumerable<bool>>)null, (x, y) => x)); AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => ParallelEnumerable.Empty<bool>().SelectMany(x => new[] { x }, (Func<bool, bool, bool>)null)); AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => ParallelEnumerable.Empty<bool>().SelectMany((x, index) => new[] { x }, (Func<bool, bool, bool>)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.Concurrent; using System.Collections.Generic; using Xunit; namespace System.Linq.Parallel.Tests { public static class SelectSelectManyTests { [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Select_Unordered(int count) { IntegerRangeSet seen = new IntegerRangeSet(0, count); foreach (var p in UnorderedSources.Default(count).Select(x => KeyValuePair.Create(x, x * x))) { seen.Add(p.Key); Assert.Equal(p.Key * p.Key, p.Value); } seen.AssertComplete(); } [Fact] [OuterLoop] public static void Select_Unordered_Longrunning() { Select_Unordered(Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))] public static void Select(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int seen = 0; foreach (var p in query.Select(x => KeyValuePair.Create(x, x * x))) { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key * p.Key, p.Value); } Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), new[] { 1024 * 4 }, MemberType = typeof(Sources))] public static void Select_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select(labeled, count); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Select_Unordered_NotPipelined(int count) { IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.All(UnorderedSources.Default(count).Select(x => KeyValuePair.Create(x, x * x)).ToList(), p => { seen.Add(p.Key); Assert.Equal(p.Key * p.Key, p.Value); }); seen.AssertComplete(); } [Fact] [OuterLoop] public static void Select_Unordered_NotPipelined_Longrunning() { Select_Unordered_NotPipelined(Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))] public static void Select_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int seen = 0; Assert.All(query.Select(x => KeyValuePair.Create(x, x * x)).ToList(), p => { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key * p.Key, p.Value); }); Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), new[] { 1024 * 4 }, MemberType = typeof(Sources))] public static void Select_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select_NotPipelined(labeled, count); } // Uses an element's index to calculate an output value. If order preservation isn't // working, this would PROBABLY fail. Unfortunately, this isn't deterministic. But choosing // larger input sizes increases the probability that it will. [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Select_Indexed_Unordered(int count) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(0, count); foreach (var p in UnorderedSources.Default(count).Select((x, index) => KeyValuePair.Create(x, index))) { seen.Add(p.Key); Assert.Equal(p.Key, p.Value); } seen.AssertComplete(); } [Fact] [OuterLoop] public static void Select_Indexed_Unordered_Longrunning() { Select_Indexed_Unordered(Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))] public static void Select_Indexed(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int seen = 0; foreach (var p in query.Select((x, index) => KeyValuePair.Create(x, index))) { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key, p.Value); } Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), new[] { 1024 * 4 }, MemberType = typeof(Sources))] public static void Select_Indexed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select_Indexed(labeled, count); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Select_Indexed_Unordered_NotPipelined(int count) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.All(UnorderedSources.Default(count).Select((x, index) => KeyValuePair.Create(x, index)).ToList(), p => { seen.Add(p.Key); Assert.Equal(p.Key, p.Value); }); seen.AssertComplete(); } [Fact] [OuterLoop] public static void Select_Indexed_Unordered_NotPipelined_Longrunning() { Select_Indexed_Unordered_NotPipelined(Sources.OuterLoopCount / 64); } [Theory] [MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))] public static void Select_Indexed_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int seen = 0; Assert.All(query.Select((x, index) => KeyValuePair.Create(x, index)).ToList(), p => { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key, p.Value); }); Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), new[] { 1024 * 4 }, MemberType = typeof(Sources))] public static void Select_Indexed_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select_Indexed_NotPipelined(labeled, count); } [Fact] public static void Select_ArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).Select(x => x)); AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).Select((x, index) => x)); AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Empty<bool>().Select((Func<bool, bool>)null)); AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Empty<bool>().Select((Func<bool, int, bool>)null)); } [Theory] [InlineData(true, true)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(false, false)] public static void Select_OrderablePartitionerWithOutOfOrderInputs_AsOrdered_CorrectOrder(bool keysOrderedInEachPartition, bool keysNormalized) { var range = new RangeOrderablePartitioner(0, 1024, keysOrderedInEachPartition, keysNormalized); int next = 0; foreach (int i in range.AsParallel().AsOrdered().Select(i => i)) { Assert.Equal(next++, i); } } // // SelectMany // // [Regression Test] // An issue occurred because the QuerySettings structure was not being deep-cloned during // query-opening. As a result, the concurrent inner-enumerators (for the RHS operators) // that occur in SelectMany were sharing CancellationState that they should not have. // The result was that enumerators could falsely believe they had been canceled when // another inner-enumerator was disposed. // // Note: the failure was intermittent. this test would fail about 1 in 2 times on mikelid1 (4-core). public static IEnumerable<object[]> SelectManyUnorderedData(int[] counts) { foreach (int count in counts.DefaultIfEmpty(Sources.OuterLoopCount / 64)) { foreach (Labeled<Func<int, int, IEnumerable<int>>> expander in Expanders()) { foreach (int expandCount in new[] { 0, 1, 2, 8 }) { yield return new object[] { count, expander, expandCount }; } } } } public static IEnumerable<object[]> SelectManyData(int[] counts) { foreach (object[] results in Sources.Ranges(counts.DefaultIfEmpty(Sources.OuterLoopCount / 64))) { foreach (Labeled<Func<int, int, IEnumerable<int>>> expander in Expanders()) { foreach (int count in new[] { 0, 1, 2, 8 }) { yield return new object[] { results[0], results[1], expander, count }; } } } } public static IEnumerable<Labeled<Func<int, int, IEnumerable<int>>>> Expanders() { yield return Labeled.Label("Array", (Func<int, int, IEnumerable<int>>)((start, count) => Enumerable.Range(start * count, count).ToArray())); yield return Labeled.Label("Enumerable.Range", (Func<int, int, IEnumerable<int>>)((start, count) => Enumerable.Range(start * count, count))); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Unordered(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); foreach (int i in UnorderedSources.Default(count).SelectMany(x => expand(x, expansion))) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Unordered_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Unordered(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; foreach (int i in query.SelectMany(x => expand(x, expansion))) { Assert.Equal(seen++, i); } Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Unordered_NotPipelined(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); Assert.All(UnorderedSources.Default(count).SelectMany(x => expand(x, expansion)).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Unordered_NotPipelined_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Unordered_NotPipelined(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; Assert.All(query.SelectMany(x => expand(x, expansion)).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_NotPipelined(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Unordered_ResultSelector(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); foreach (var p in UnorderedSources.Default(count).SelectMany(x => expand(x, expansion), (original, expanded) => KeyValuePair.Create(original, expanded))) { seen.Add(p.Value); Assert.Equal(p.Key, p.Value / expansion); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Unordered_ResultSelector_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Unordered_ResultSelector(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Unordered_ResultSelector_NotPipelined(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); Assert.All(UnorderedSources.Default(count).SelectMany(x => expand(x, expansion), (original, expanded) => KeyValuePair.Create(original, expanded)).ToList(), p => { seen.Add(p.Value); Assert.Equal(p.Key, p.Value / expansion); }); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Unordered_ResultSelector_NotPipelined_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Unordered_ResultSelector_NotPipelined(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_ResultSelector(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; foreach (var p in query.SelectMany(x => expand(x, expansion), (original, expanded) => KeyValuePair.Create(original, expanded))) { Assert.Equal(seen++, p.Value); Assert.Equal(p.Key, p.Value / expansion); } Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_ResultSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_ResultSelector(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_ResultSelector_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; Assert.All(query.SelectMany(x => expand(x, expansion), (original, expanded) => KeyValuePair.Create(original, expanded)).ToList(), p => { Assert.Equal(seen++, p.Value); Assert.Equal(p.Key, p.Value / expansion); }); Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_ResultSelector_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_ResultSelector_NotPipelined(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_Unordered(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); foreach (var pIndex in UnorderedSources.Default(count).SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)))) { seen.Add(pIndex.Value); Assert.Equal(pIndex.Key, pIndex.Value / expansion); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_Unordered_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_Unordered(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_Unordered_NotPipelined(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); Assert.All(UnorderedSources.Default(count).SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y))).ToList(), pIndex => { seen.Add(pIndex.Value); Assert.Equal(pIndex.Key, pIndex.Value / expansion); }); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_Unordered_NotPipelined_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_Unordered_NotPipelined(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; foreach (var pIndex in query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)))) { Assert.Equal(seen++, pIndex.Value); Assert.Equal(pIndex.Key, pIndex.Value / expansion); } Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; Assert.All(query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y))).ToList(), pIndex => { Assert.Equal(seen++, pIndex.Value); Assert.Equal(pIndex.Key, pIndex.Value / expansion); }); Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_NotPipelined(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_Unordered_ResultSelector(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); foreach (var pOuter in UnorderedSources.Default(count).SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)), (original, expanded) => KeyValuePair.Create(original, expanded))) { var pInner = pOuter.Value; Assert.Equal(pOuter.Key, pInner.Key); seen.Add(pInner.Value); Assert.Equal(pOuter.Key, pInner.Value / expansion); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_Unordered_ResultSelector_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_Unordered_ResultSelector(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_Unordered_ResultSelector_NotPipelined(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); Assert.All(UnorderedSources.Default(count).SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)), (original, expanded) => KeyValuePair.Create(original, expanded)).ToList(), pOuter => { var pInner = pOuter.Value; Assert.Equal(pOuter.Key, pInner.Key); seen.Add(pInner.Value); Assert.Equal(pOuter.Key, pInner.Value / expansion); }); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_Unordered_ResultSelector_NotPipelined_Longrunning(int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_Unordered_ResultSelector_NotPipelined(count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_ResultSelector(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; foreach (var pOuter in query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)), (original, expanded) => KeyValuePair.Create(original, expanded))) { var pInner = pOuter.Value; Assert.Equal(pOuter.Key, pInner.Key); Assert.Equal(seen++, pInner.Value); Assert.Equal(pOuter.Key, pInner.Value / expansion); } Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_ResultSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_ResultSelector(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_ResultSelector_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; Assert.All(query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)), (original, expanded) => KeyValuePair.Create(original, expanded)).ToList(), pOuter => { var pInner = pOuter.Value; Assert.Equal(pOuter.Key, pInner.Key); Assert.Equal(seen++, pInner.Value); Assert.Equal(pOuter.Key, pInner.Value / expansion); }); Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new int[] { /* Sources.OuterLoopCount */ })] public static void SelectMany_Indexed_ResultSelector_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_ResultSelector_NotPipelined(labeled, count, expander, expansion); } [Fact] public static void SelectMany_ArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).SelectMany(x => new[] { x })); AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).SelectMany((x, index) => new[] { x })); AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Empty<bool>().SelectMany((Func<bool, IEnumerable<bool>>)null)); AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Empty<bool>().SelectMany((Func<bool, int, IEnumerable<bool>>)null)); AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).SelectMany(x => new[] { x }, (x, y) => x)); AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<bool>)null).SelectMany((x, index) => new[] { x }, (x, y) => x)); AssertExtensions.Throws<ArgumentNullException>("collectionSelector", () => ParallelEnumerable.Empty<bool>().SelectMany((Func<bool, IEnumerable<bool>>)null, (x, y) => x)); AssertExtensions.Throws<ArgumentNullException>("collectionSelector", () => ParallelEnumerable.Empty<bool>().SelectMany((Func<bool, int, IEnumerable<bool>>)null, (x, y) => x)); AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => ParallelEnumerable.Empty<bool>().SelectMany(x => new[] { x }, (Func<bool, bool, bool>)null)); AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => ParallelEnumerable.Empty<bool>().SelectMany((x, index) => new[] { x }, (Func<bool, bool, bool>)null)); } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Linq.Parallel/tests/Helpers/UnorderedSources.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.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; namespace System.Linq.Parallel.Tests { public static class UnorderedSources { /// <summary> /// Returns a default ParallelQuery source. /// </summary> /// For most instances when dealing with unordered input, the individual source does not matter. /// /// Instead, that is reserved for ordered, where partitioning and dealing with indices has important /// secondary effects. The goal of unordered input, then, is mostly to make sure the query works. /// <param name="count">The count of elements.</param> /// <returns>A ParallelQuery with elements running from 0 to count - 1</returns> public static ParallelQuery<int> Default(int count) { return Default(0, count); } /// <summary> /// Returns a default ParallelQuery source. /// </summary> /// For most instances when dealing with unordered input, the individual source does not matter. /// /// Instead, that is reserved for ordered, where partitioning and dealing with indices has important /// secondary effects. The goal of unordered input, then, is mostly to make sure the query works. /// <param name="start">The starting element.</param> /// <param name="count">The count of elements.</param> /// <returns>A ParallelQuery with elements running from 0 to count - 1</returns> public static ParallelQuery<int> Default(int start, int count) { // Of the underlying types used elsewhere, some have "problems", // in the sense that they may be too-easily indexible. // For instance, Array and List are both trivially range partitionable and indexible. // A parallelized Enumerable.Range is being used (not easily partitionable or indexible), // but at the moment ParallelEnumerable.Range is being used for speed and ease of use. // ParallelEnumerable.Range is not trivially indexible, but is easily range partitioned. return ParallelEnumerable.Range(start, count); } // Get a set of ranges, of each count in `counts`. // The start of each range is determined by passing the count into the `start` predicate. public static IEnumerable<object[]> Ranges(Func<int, int> start, IEnumerable<int> counts) { foreach (int count in counts) { int s = start(count); foreach (Labeled<ParallelQuery<int>> query in LabeledRanges(s, count)) { yield return new object[] { query, count, s }; } } } /// <summary> /// Get a set of ranges, starting at `start`, and running for each count in `counts`. /// </summary> /// <param name="start">The starting element of the range.</param> /// <param name="counts">The sizes of ranges to return.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// the second element is the count, and the third is the start.</returns> public static IEnumerable<object[]> Ranges(int start, IEnumerable<int> counts) { foreach (object[] parms in Ranges(x => start, counts)) yield return parms; } /// <summary> /// Get a set of ranges, starting at 0, and running for each count in `counts`. /// </summary> /// <remarks>This version is a wrapper for use from the MemberData attribute.</remarks> /// <param name="counts">The sizes of ranges to return.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// and the second element is the count</returns> public static IEnumerable<object[]> Ranges(int[] counts) { foreach (object[] parms in Ranges(counts.Cast<int>())) yield return parms; } /// <summary> /// Get a set of ranges, starting at 0, and having OuterLoopCount elements. /// </summary> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// and the second element is the count</returns> public static IEnumerable<object[]> OuterLoopRanges() { foreach (object[] parms in Ranges(new[] { Sources.OuterLoopCount })) yield return parms; } /// <summary> /// Get a set of ranges, starting at `start`, and running for each count in `counts`. /// </summary> /// <remarks>This version is a wrapper for use from the MemberData attribute.</remarks> /// <param name="start">The starting element of the range.</param> /// <param name="counts">The sizes of ranges to return.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// the second element is the count, and the third is the start.</returns> public static IEnumerable<object[]> Ranges(int start, int[] counts) { foreach (object[] parms in Ranges(start, counts.Cast<int>())) yield return parms; } /// <summary> /// Return pairs of ranges, both from 0 to each respective count in `counts`. /// </summary> /// <remarks>This version is a wrapper for use from the MemberData attribute.</remarks> /// <param name="leftCounts">The sizes of left ranges to return.</param> /// <param name="rightCounts">The sizes of right ranges to return.</param> /// <returns>Entries for test data. /// The first element is the left Labeled{ParallelQuery{int}} range, the second element is the left count, /// the third element is the right Labeled{ParallelQuery{int}} range, and the fourth element is the right count, .</returns> public static IEnumerable<object[]> BinaryRanges(int[] leftCounts, int[] rightCounts) { foreach (object[] parms in BinaryRanges(leftCounts.Cast<int>(), rightCounts.Cast<int>())) yield return parms; } /// <summary> /// Get a set of ranges, starting at 0, and running for each count in `counts`. /// </summary> /// <param name="counts">The sizes of ranges to return.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// and the second element is the count</returns> public static IEnumerable<object[]> Ranges(IEnumerable<int> counts) { foreach (object[] parms in Ranges(x => 0, counts)) yield return parms.Take(2).ToArray(); } /// <summary> /// Return pairs of ranges, both from 0 to each respective count in `counts`. /// </summary> /// <param name="leftCounts">The sizes of left ranges to return.</param> /// <param name="rightCounts">The sizes of right ranges to return.</param> /// <returns>Entries for test data. /// The first element is the left Labeled{ParallelQuery{int}} range, the second element is the left count, /// the third element is the right Labeled{ParallelQuery{int}} range, and the fourth element is the right count.</returns> public static IEnumerable<object[]> BinaryRanges(IEnumerable<int> leftCounts, IEnumerable<int> rightCounts) { IEnumerable<object[]> rightRanges = Ranges(rightCounts); foreach (object[] left in Ranges(leftCounts)) { foreach (object[] right in rightRanges) { yield return left.Concat(right).ToArray(); } } } /// <summary> /// Return pairs of ranges, for each respective count in `counts`. /// </summary> /// <param name="leftCounts">The sizes of left ranges to return.</param> /// <param name="rightStart">A predicate to determine the start of the right range, by passing the left and right range size.</param> /// <param name="rightCounts">The sizes of right ranges to return.</param> /// <returns>Entries for test data. /// The first element is the left Labeled{ParallelQuery{int}} range, the second element is the left count, /// the third element is the right Labeled{ParallelQuery{int}} range, the fourth element is the right count, /// and the fifth is the right start.</returns> public static IEnumerable<object[]> BinaryRanges(IEnumerable<int> leftCounts, Func<int, int, int> rightStart, IEnumerable<int> rightCounts) { foreach (object[] left in Ranges(leftCounts)) { foreach (object[] right in Ranges(right => rightStart((int)left[1], right), rightCounts)) { yield return left.Concat(right).ToArray(); } } } /// <summary> /// Get a set of ranges, starting at 0, and running for each count in `counts`. /// </summary> /// <remarks> /// This is useful for things like showing an average (via the use of `x => (double)SumRange(0, x) / x`) /// </remarks> /// <param name="counts">The sizes of ranges to return.</param> /// <param name="modifiers">A set of modifiers to return as additional parameters.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// the second element is the count, and one additional element for each modifier.</returns> public static IEnumerable<object[]> Ranges<T>(IEnumerable<int> counts, Func<int, T> modifiers) { foreach (object[] parms in Ranges(counts)) { int count = (int)parms[1]; yield return parms.Concat(new object[] { modifiers(count) }).ToArray(); } } /// <summary> /// Get a set of ranges, starting at 0, and running for each count in `counts`. /// </summary> /// <remarks> /// This is useful for things like dealing with `Max(predicate)`, /// allowing multiple predicate values for the same source count to be tested. /// The number of variations is equal to the longest modifier enumeration (all others will cycle). /// </remarks> /// <param name="counts">The sizes of ranges to return.</param> /// <param name="modifiers">A set of modifiers to return as additional parameters.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// the second element is the count, and one additional element for each modifier.</returns> public static IEnumerable<object[]> Ranges<T>(IEnumerable<int> counts, Func<int, IEnumerable<T>> modifiers) { foreach (object[] parms in Ranges(counts)) { foreach (T mod in modifiers((int)parms[1])) { yield return parms.Concat(new object[] { mod }).ToArray(); } } } // Return an enumerable which throws on first MoveNext. // Useful for testing promptness of cancellation. public static IEnumerable<object[]> ThrowOnFirstEnumeration() { yield return new object[] { Labeled.Label("ThrowOnFirstEnumeration", Enumerables<int>.ThrowOnEnumeration().AsParallel()), 8 }; } public static IEnumerable<Labeled<ParallelQuery<int>>> LabeledRanges(int start, int count) { yield return Labeled.Label("ParallelEnumerable.Range", ParallelEnumerable.Range(start, count)); yield return Labeled.Label("Enumerable.Range", Enumerable.Range(start, count).AsParallel()); int[] rangeArray = Enumerable.Range(start, count).ToArray(); yield return Labeled.Label("Array", rangeArray.AsParallel()); IList<int> rangeList = rangeArray.ToList(); yield return Labeled.Label("List", rangeList.AsParallel()); yield return Labeled.Label("Partitioner", Partitioner.Create(rangeArray).AsParallel()); // PLINQ doesn't currently have any special code paths for readonly collections. If it ever does, this should be uncommented. // yield return Labeled.Label("ReadOnlyCollection", new ReadOnlyCollection<int>(rangeList).AsParallel()); } } }
// 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.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; namespace System.Linq.Parallel.Tests { public static class UnorderedSources { /// <summary> /// Returns a default ParallelQuery source. /// </summary> /// For most instances when dealing with unordered input, the individual source does not matter. /// /// Instead, that is reserved for ordered, where partitioning and dealing with indices has important /// secondary effects. The goal of unordered input, then, is mostly to make sure the query works. /// <param name="count">The count of elements.</param> /// <returns>A ParallelQuery with elements running from 0 to count - 1</returns> public static ParallelQuery<int> Default(int count) { return Default(0, count); } /// <summary> /// Returns a default ParallelQuery source. /// </summary> /// For most instances when dealing with unordered input, the individual source does not matter. /// /// Instead, that is reserved for ordered, where partitioning and dealing with indices has important /// secondary effects. The goal of unordered input, then, is mostly to make sure the query works. /// <param name="start">The starting element.</param> /// <param name="count">The count of elements.</param> /// <returns>A ParallelQuery with elements running from 0 to count - 1</returns> public static ParallelQuery<int> Default(int start, int count) { // Of the underlying types used elsewhere, some have "problems", // in the sense that they may be too-easily indexible. // For instance, Array and List are both trivially range partitionable and indexible. // A parallelized Enumerable.Range is being used (not easily partitionable or indexible), // but at the moment ParallelEnumerable.Range is being used for speed and ease of use. // ParallelEnumerable.Range is not trivially indexible, but is easily range partitioned. return ParallelEnumerable.Range(start, count); } // Get a set of ranges, of each count in `counts`. // The start of each range is determined by passing the count into the `start` predicate. public static IEnumerable<object[]> Ranges(Func<int, int> start, IEnumerable<int> counts) { foreach (int count in counts) { int s = start(count); foreach (Labeled<ParallelQuery<int>> query in LabeledRanges(s, count)) { yield return new object[] { query, count, s }; } } } /// <summary> /// Get a set of ranges, starting at `start`, and running for each count in `counts`. /// </summary> /// <param name="start">The starting element of the range.</param> /// <param name="counts">The sizes of ranges to return.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// the second element is the count, and the third is the start.</returns> public static IEnumerable<object[]> Ranges(int start, IEnumerable<int> counts) { foreach (object[] parms in Ranges(x => start, counts)) yield return parms; } /// <summary> /// Get a set of ranges, starting at 0, and running for each count in `counts`. /// </summary> /// <remarks>This version is a wrapper for use from the MemberData attribute.</remarks> /// <param name="counts">The sizes of ranges to return.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// and the second element is the count</returns> public static IEnumerable<object[]> Ranges(int[] counts) { foreach (object[] parms in Ranges(counts.Cast<int>())) yield return parms; } /// <summary> /// Get a set of ranges, starting at 0, and having OuterLoopCount elements. /// </summary> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// and the second element is the count</returns> public static IEnumerable<object[]> OuterLoopRanges() { foreach (object[] parms in Ranges(new[] { Sources.OuterLoopCount })) yield return parms; } /// <summary> /// Get a set of ranges, starting at `start`, and running for each count in `counts`. /// </summary> /// <remarks>This version is a wrapper for use from the MemberData attribute.</remarks> /// <param name="start">The starting element of the range.</param> /// <param name="counts">The sizes of ranges to return.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// the second element is the count, and the third is the start.</returns> public static IEnumerable<object[]> Ranges(int start, int[] counts) { foreach (object[] parms in Ranges(start, counts.Cast<int>())) yield return parms; } /// <summary> /// Return pairs of ranges, both from 0 to each respective count in `counts`. /// </summary> /// <remarks>This version is a wrapper for use from the MemberData attribute.</remarks> /// <param name="leftCounts">The sizes of left ranges to return.</param> /// <param name="rightCounts">The sizes of right ranges to return.</param> /// <returns>Entries for test data. /// The first element is the left Labeled{ParallelQuery{int}} range, the second element is the left count, /// the third element is the right Labeled{ParallelQuery{int}} range, and the fourth element is the right count, .</returns> public static IEnumerable<object[]> BinaryRanges(int[] leftCounts, int[] rightCounts) { foreach (object[] parms in BinaryRanges(leftCounts.Cast<int>(), rightCounts.Cast<int>())) yield return parms; } /// <summary> /// Get a set of ranges, starting at 0, and running for each count in `counts`. /// </summary> /// <param name="counts">The sizes of ranges to return.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// and the second element is the count</returns> public static IEnumerable<object[]> Ranges(IEnumerable<int> counts) { foreach (object[] parms in Ranges(x => 0, counts)) yield return parms.Take(2).ToArray(); } /// <summary> /// Return pairs of ranges, both from 0 to each respective count in `counts`. /// </summary> /// <param name="leftCounts">The sizes of left ranges to return.</param> /// <param name="rightCounts">The sizes of right ranges to return.</param> /// <returns>Entries for test data. /// The first element is the left Labeled{ParallelQuery{int}} range, the second element is the left count, /// the third element is the right Labeled{ParallelQuery{int}} range, and the fourth element is the right count.</returns> public static IEnumerable<object[]> BinaryRanges(IEnumerable<int> leftCounts, IEnumerable<int> rightCounts) { IEnumerable<object[]> rightRanges = Ranges(rightCounts); foreach (object[] left in Ranges(leftCounts)) { foreach (object[] right in rightRanges) { yield return left.Concat(right).ToArray(); } } } /// <summary> /// Return pairs of ranges, for each respective count in `counts`. /// </summary> /// <param name="leftCounts">The sizes of left ranges to return.</param> /// <param name="rightStart">A predicate to determine the start of the right range, by passing the left and right range size.</param> /// <param name="rightCounts">The sizes of right ranges to return.</param> /// <returns>Entries for test data. /// The first element is the left Labeled{ParallelQuery{int}} range, the second element is the left count, /// the third element is the right Labeled{ParallelQuery{int}} range, the fourth element is the right count, /// and the fifth is the right start.</returns> public static IEnumerable<object[]> BinaryRanges(IEnumerable<int> leftCounts, Func<int, int, int> rightStart, IEnumerable<int> rightCounts) { foreach (object[] left in Ranges(leftCounts)) { foreach (object[] right in Ranges(right => rightStart((int)left[1], right), rightCounts)) { yield return left.Concat(right).ToArray(); } } } /// <summary> /// Get a set of ranges, starting at 0, and running for each count in `counts`. /// </summary> /// <remarks> /// This is useful for things like showing an average (via the use of `x => (double)SumRange(0, x) / x`) /// </remarks> /// <param name="counts">The sizes of ranges to return.</param> /// <param name="modifiers">A set of modifiers to return as additional parameters.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// the second element is the count, and one additional element for each modifier.</returns> public static IEnumerable<object[]> Ranges<T>(IEnumerable<int> counts, Func<int, T> modifiers) { foreach (object[] parms in Ranges(counts)) { int count = (int)parms[1]; yield return parms.Concat(new object[] { modifiers(count) }).ToArray(); } } /// <summary> /// Get a set of ranges, starting at 0, and running for each count in `counts`. /// </summary> /// <remarks> /// This is useful for things like dealing with `Max(predicate)`, /// allowing multiple predicate values for the same source count to be tested. /// The number of variations is equal to the longest modifier enumeration (all others will cycle). /// </remarks> /// <param name="counts">The sizes of ranges to return.</param> /// <param name="modifiers">A set of modifiers to return as additional parameters.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// the second element is the count, and one additional element for each modifier.</returns> public static IEnumerable<object[]> Ranges<T>(IEnumerable<int> counts, Func<int, IEnumerable<T>> modifiers) { foreach (object[] parms in Ranges(counts)) { foreach (T mod in modifiers((int)parms[1])) { yield return parms.Concat(new object[] { mod }).ToArray(); } } } // Return an enumerable which throws on first MoveNext. // Useful for testing promptness of cancellation. public static IEnumerable<object[]> ThrowOnFirstEnumeration() { yield return new object[] { Labeled.Label("ThrowOnFirstEnumeration", Enumerables<int>.ThrowOnEnumeration().AsParallel()), 8 }; } public static IEnumerable<Labeled<ParallelQuery<int>>> LabeledRanges(int start, int count) { yield return Labeled.Label("ParallelEnumerable.Range", ParallelEnumerable.Range(start, count)); yield return Labeled.Label("Enumerable.Range", Enumerable.Range(start, count).AsParallel()); int[] rangeArray = Enumerable.Range(start, count).ToArray(); yield return Labeled.Label("Array", rangeArray.AsParallel()); IList<int> rangeList = rangeArray.ToList(); yield return Labeled.Label("List", rangeList.AsParallel()); yield return Labeled.Label("Partitioner", Partitioner.Create(rangeArray).AsParallel()); // PLINQ doesn't currently have any special code paths for readonly collections. If it ever does, this should be uncommented. // yield return Labeled.Label("ReadOnlyCollection", new ReadOnlyCollection<int>(rangeList).AsParallel()); } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Security.Permissions/src/System/Transactions/DistributedTransactionPermission.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Security; using System.Security.Permissions; namespace System.Transactions { #if NETCOREAPP [Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] #endif public sealed class DistributedTransactionPermission : CodeAccessPermission, IUnrestrictedPermission { public DistributedTransactionPermission(PermissionState state) { } public override IPermission Copy() { return null; } public override void FromXml(SecurityElement securityElement) { } public override IPermission Intersect(IPermission target) { return null; } public override bool IsSubsetOf(IPermission target) => false; public bool IsUnrestricted() => false; public override SecurityElement ToXml() { return null; } public override IPermission Union(IPermission target) { return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Security; using System.Security.Permissions; namespace System.Transactions { #if NETCOREAPP [Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] #endif public sealed class DistributedTransactionPermission : CodeAccessPermission, IUnrestrictedPermission { public DistributedTransactionPermission(PermissionState state) { } public override IPermission Copy() { return null; } public override void FromXml(SecurityElement securityElement) { } public override IPermission Intersect(IPermission target) { return null; } public override bool IsSubsetOf(IPermission target) => false; public bool IsUnrestricted() => false; public override SecurityElement ToXml() { return null; } public override IPermission Union(IPermission target) { return null; } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/HardwareIntrinsics/X86/Sse1/StoreFence_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup> <DebugType>Embedded</DebugType> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="StoreFence.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup> <DebugType>Embedded</DebugType> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="StoreFence.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/CodeGenBringUpTests/FPDiv_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="FPDiv.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="FPDiv.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBModiferAttributeConverter.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; namespace Microsoft.VisualBasic { internal abstract class VBModifierAttributeConverter : TypeConverter { protected abstract object[] Values { get; } protected abstract string[] Names { get; } protected abstract object DefaultValue { get; } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) => sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string name = value as string; if (name != null) { string[] names = Names; for (int i = 0; i < names.Length; i++) { if (names[i].Equals(name, StringComparison.OrdinalIgnoreCase)) { return Values[i]; } } } return DefaultValue; } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } if (destinationType == typeof(string)) { object[] modifiers = Values; for (int i = 0; i < modifiers.Length; i++) { if (modifiers[i].Equals(value)) { return Names[i]; } } return SR.toStringUnknown; } return base.ConvertTo(context, culture, value, destinationType); } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) => true; public override bool GetStandardValuesSupported(ITypeDescriptorContext context) => true; public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) => new StandardValuesCollection(Values); } }
// 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; namespace Microsoft.VisualBasic { internal abstract class VBModifierAttributeConverter : TypeConverter { protected abstract object[] Values { get; } protected abstract string[] Names { get; } protected abstract object DefaultValue { get; } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) => sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string name = value as string; if (name != null) { string[] names = Names; for (int i = 0; i < names.Length; i++) { if (names[i].Equals(name, StringComparison.OrdinalIgnoreCase)) { return Values[i]; } } } return DefaultValue; } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType is null) { throw new ArgumentNullException(nameof(destinationType)); } if (destinationType == typeof(string)) { object[] modifiers = Values; for (int i = 0; i < modifiers.Length; i++) { if (modifiers[i].Equals(value)) { return Names[i]; } } return SR.toStringUnknown; } return base.ConvertTo(context, culture, value, destinationType); } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) => true; public override bool GetStandardValuesSupported(ITypeDescriptorContext context) => true; public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) => new StandardValuesCollection(Values); } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/Methodical/NaN/r8NaNdiv_cs_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="r8NaNdiv.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="r8NaNdiv.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/LoadAndReplicateToVector128.Byte.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 LoadAndReplicateToVector128_Byte() { var test = new LoadUnaryOpTest__LoadAndReplicateToVector128_Byte(); if (test.IsSupported) { // Validates basic functionality works test.RunBasicScenario_Load(); // Validates calling via reflection works test.RunReflectionScenario_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 LoadUnaryOpTest__LoadAndReplicateToVector128_Byte { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); 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<Byte, 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 static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data = new Byte[Op1ElementCount]; private DataTable _dataTable; public LoadUnaryOpTest__LoadAndReplicateToVector128_Byte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.LoadAndReplicateToVector128( (Byte*)(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LoadAndReplicateToVector128), new Type[] { typeof(Byte*) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(Byte*)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); Succeeded = false; try { RunBasicScenario_Load(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Byte> firstOp, void* result, [CallerMemberName] string method = "") { Byte[] inArray = new Byte[Op1ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Byte[] inArray = new Byte[Op1ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Byte[] firstOp, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (firstOp[0] != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.LoadAndReplicateToVector128)}<Byte>(Vector128<Byte>): {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.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 LoadAndReplicateToVector128_Byte() { var test = new LoadUnaryOpTest__LoadAndReplicateToVector128_Byte(); if (test.IsSupported) { // Validates basic functionality works test.RunBasicScenario_Load(); // Validates calling via reflection works test.RunReflectionScenario_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 LoadUnaryOpTest__LoadAndReplicateToVector128_Byte { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); 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<Byte, 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 static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data = new Byte[Op1ElementCount]; private DataTable _dataTable; public LoadUnaryOpTest__LoadAndReplicateToVector128_Byte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.LoadAndReplicateToVector128( (Byte*)(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LoadAndReplicateToVector128), new Type[] { typeof(Byte*) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(Byte*)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); Succeeded = false; try { RunBasicScenario_Load(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Byte> firstOp, void* result, [CallerMemberName] string method = "") { Byte[] inArray = new Byte[Op1ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Byte[] inArray = new Byte[Op1ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Byte[] firstOp, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (firstOp[0] != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.LoadAndReplicateToVector128)}<Byte>(Vector128<Byte>): {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
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/Loader/classloader/v1/Beta1/Layout/Matrix/cs/L-1-7-3.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="L-1-7-3.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="L-1-7-3D.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="L-1-7-3.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="L-1-7-3D.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeSystemExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Reflection; using System.Collections.Generic; using System.Diagnostics; using Internal.NativeFormat; using Internal.TypeSystem.NativeFormat; #if ECMA_METADATA_SUPPORT using Internal.TypeSystem.Ecma; #endif using Internal.Runtime.Augments; using Internal.Runtime.CompilerServices; using Internal.TypeSystem; using Internal.TypeSystem.NoMetadata; using System.Reflection.Runtime.General; namespace Internal.TypeSystem.NativeFormat { // When SUPPORTS_NATIVE_METADATA_TYPE_LOADING is not set we may see compile errors from using statements. // Add a namespace definition for Internal.TypeSystem.NativeFormat } namespace Internal.Runtime.TypeLoader { internal static class TypeDescExtensions { public static bool CanShareNormalGenericCode(this TypeDesc type) { return (type != type.ConvertToCanonForm(CanonicalFormKind.Specific)); } public static bool IsGeneric(this TypeDesc type) { DefType typeAsDefType = type as DefType; return typeAsDefType != null && typeAsDefType.HasInstantiation; } public static DefType GetClosestDefType(this TypeDesc type) { if (type is DefType) return (DefType)type; else return type.BaseType; } } internal static class MethodDescExtensions { public static bool CanShareNormalGenericCode(this InstantiatedMethod method) { return (method != method.GetCanonMethodTarget(CanonicalFormKind.Specific)); } } internal static class RuntimeHandleExtensions { public static bool IsNull(this RuntimeTypeHandle rtth) { return RuntimeAugments.GetRuntimeTypeHandleRawValue(rtth) == IntPtr.Zero; } public static unsafe bool IsDynamic(this RuntimeFieldHandle rtfh) { IntPtr rtfhValue = *(IntPtr*)&rtfh; return (rtfhValue.ToInt64() & 0x1) == 0x1; } public static unsafe bool IsDynamic(this RuntimeMethodHandle rtfh) { IntPtr rtfhValue = *(IntPtr*)&rtfh; return (rtfhValue.ToInt64() & 0x1) == 0x1; } } public static partial class RuntimeSignatureHelper { public static bool TryCreate(MethodDesc method, out RuntimeSignature methodSignature) { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING MethodDesc typicalMethod = method.GetTypicalMethodDefinition(); if (typicalMethod is TypeSystem.NativeFormat.NativeFormatMethod) { TypeSystem.NativeFormat.NativeFormatMethod nativeFormatMethod = (TypeSystem.NativeFormat.NativeFormatMethod)typicalMethod; methodSignature = RuntimeSignature.CreateFromMethodHandle(nativeFormatMethod.MetadataUnit.RuntimeModule, nativeFormatMethod.Handle.ToInt()); return true; } #if ECMA_METADATA_SUPPORT if (typicalMethod is TypeSystem.Ecma.EcmaMethod) { unsafe { TypeSystem.Ecma.EcmaMethod ecmaMethod = (TypeSystem.Ecma.EcmaMethod)typicalMethod; methodSignature = RuntimeSignature.CreateFromMethodHandle(new IntPtr(ecmaMethod.Module.RuntimeModuleInfo.DynamicModulePtr), System.Reflection.Metadata.Ecma335.MetadataTokens.GetToken(ecmaMethod.Handle)); } return true; } #endif #endif methodSignature = default(RuntimeSignature); return false; } #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING public static MethodDesc ToMethodDesc(this RuntimeMethodHandle rmh, TypeSystemContext typeSystemContext) { RuntimeTypeHandle declaringTypeHandle; MethodNameAndSignature nameAndSignature; RuntimeTypeHandle[] genericMethodArgs; if (!TypeLoaderEnvironment.Instance.TryGetRuntimeMethodHandleComponents(rmh, out declaringTypeHandle, out nameAndSignature, out genericMethodArgs)) { return null; } QMethodDefinition methodHandle; if (!TypeLoaderEnvironment.Instance.TryGetMetadataForTypeMethodNameAndSignature(declaringTypeHandle, nameAndSignature, out methodHandle)) { return null; } TypeDesc declaringType = typeSystemContext.ResolveRuntimeTypeHandle(declaringTypeHandle); TypeDesc declaringTypeDefinition = declaringType.GetTypeDefinition(); MethodDesc typicalMethod = null; if (methodHandle.IsNativeFormatMetadataBased) { var nativeFormatType = (NativeFormatType)declaringTypeDefinition; typicalMethod = nativeFormatType.MetadataUnit.GetMethod(methodHandle.NativeFormatHandle, nativeFormatType); } else if (methodHandle.IsEcmaFormatMetadataBased) { var ecmaFormatType = (EcmaType)declaringTypeDefinition; typicalMethod = ecmaFormatType.EcmaModule.GetMethod(methodHandle.EcmaFormatHandle); } Debug.Assert(typicalMethod != null); MethodDesc methodOnInstantiatedType = typicalMethod; if (declaringType != declaringTypeDefinition) methodOnInstantiatedType = typeSystemContext.GetMethodForInstantiatedType(typicalMethod, (InstantiatedType)declaringType); MethodDesc instantiatedMethod = methodOnInstantiatedType; if (genericMethodArgs != null) { Debug.Assert(genericMethodArgs.Length > 0); Instantiation genericMethodInstantiation = typeSystemContext.ResolveRuntimeTypeHandles(genericMethodArgs); typeSystemContext.GetInstantiatedMethod(methodOnInstantiatedType, genericMethodInstantiation); } return instantiatedMethod; } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Reflection; using System.Collections.Generic; using System.Diagnostics; using Internal.NativeFormat; using Internal.TypeSystem.NativeFormat; #if ECMA_METADATA_SUPPORT using Internal.TypeSystem.Ecma; #endif using Internal.Runtime.Augments; using Internal.Runtime.CompilerServices; using Internal.TypeSystem; using Internal.TypeSystem.NoMetadata; using System.Reflection.Runtime.General; namespace Internal.TypeSystem.NativeFormat { // When SUPPORTS_NATIVE_METADATA_TYPE_LOADING is not set we may see compile errors from using statements. // Add a namespace definition for Internal.TypeSystem.NativeFormat } namespace Internal.Runtime.TypeLoader { internal static class TypeDescExtensions { public static bool CanShareNormalGenericCode(this TypeDesc type) { return (type != type.ConvertToCanonForm(CanonicalFormKind.Specific)); } public static bool IsGeneric(this TypeDesc type) { DefType typeAsDefType = type as DefType; return typeAsDefType != null && typeAsDefType.HasInstantiation; } public static DefType GetClosestDefType(this TypeDesc type) { if (type is DefType) return (DefType)type; else return type.BaseType; } } internal static class MethodDescExtensions { public static bool CanShareNormalGenericCode(this InstantiatedMethod method) { return (method != method.GetCanonMethodTarget(CanonicalFormKind.Specific)); } } internal static class RuntimeHandleExtensions { public static bool IsNull(this RuntimeTypeHandle rtth) { return RuntimeAugments.GetRuntimeTypeHandleRawValue(rtth) == IntPtr.Zero; } public static unsafe bool IsDynamic(this RuntimeFieldHandle rtfh) { IntPtr rtfhValue = *(IntPtr*)&rtfh; return (rtfhValue.ToInt64() & 0x1) == 0x1; } public static unsafe bool IsDynamic(this RuntimeMethodHandle rtfh) { IntPtr rtfhValue = *(IntPtr*)&rtfh; return (rtfhValue.ToInt64() & 0x1) == 0x1; } } public static partial class RuntimeSignatureHelper { public static bool TryCreate(MethodDesc method, out RuntimeSignature methodSignature) { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING MethodDesc typicalMethod = method.GetTypicalMethodDefinition(); if (typicalMethod is TypeSystem.NativeFormat.NativeFormatMethod) { TypeSystem.NativeFormat.NativeFormatMethod nativeFormatMethod = (TypeSystem.NativeFormat.NativeFormatMethod)typicalMethod; methodSignature = RuntimeSignature.CreateFromMethodHandle(nativeFormatMethod.MetadataUnit.RuntimeModule, nativeFormatMethod.Handle.ToInt()); return true; } #if ECMA_METADATA_SUPPORT if (typicalMethod is TypeSystem.Ecma.EcmaMethod) { unsafe { TypeSystem.Ecma.EcmaMethod ecmaMethod = (TypeSystem.Ecma.EcmaMethod)typicalMethod; methodSignature = RuntimeSignature.CreateFromMethodHandle(new IntPtr(ecmaMethod.Module.RuntimeModuleInfo.DynamicModulePtr), System.Reflection.Metadata.Ecma335.MetadataTokens.GetToken(ecmaMethod.Handle)); } return true; } #endif #endif methodSignature = default(RuntimeSignature); return false; } #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING public static MethodDesc ToMethodDesc(this RuntimeMethodHandle rmh, TypeSystemContext typeSystemContext) { RuntimeTypeHandle declaringTypeHandle; MethodNameAndSignature nameAndSignature; RuntimeTypeHandle[] genericMethodArgs; if (!TypeLoaderEnvironment.Instance.TryGetRuntimeMethodHandleComponents(rmh, out declaringTypeHandle, out nameAndSignature, out genericMethodArgs)) { return null; } QMethodDefinition methodHandle; if (!TypeLoaderEnvironment.Instance.TryGetMetadataForTypeMethodNameAndSignature(declaringTypeHandle, nameAndSignature, out methodHandle)) { return null; } TypeDesc declaringType = typeSystemContext.ResolveRuntimeTypeHandle(declaringTypeHandle); TypeDesc declaringTypeDefinition = declaringType.GetTypeDefinition(); MethodDesc typicalMethod = null; if (methodHandle.IsNativeFormatMetadataBased) { var nativeFormatType = (NativeFormatType)declaringTypeDefinition; typicalMethod = nativeFormatType.MetadataUnit.GetMethod(methodHandle.NativeFormatHandle, nativeFormatType); } else if (methodHandle.IsEcmaFormatMetadataBased) { var ecmaFormatType = (EcmaType)declaringTypeDefinition; typicalMethod = ecmaFormatType.EcmaModule.GetMethod(methodHandle.EcmaFormatHandle); } Debug.Assert(typicalMethod != null); MethodDesc methodOnInstantiatedType = typicalMethod; if (declaringType != declaringTypeDefinition) methodOnInstantiatedType = typeSystemContext.GetMethodForInstantiatedType(typicalMethod, (InstantiatedType)declaringType); MethodDesc instantiatedMethod = methodOnInstantiatedType; if (genericMethodArgs != null) { Debug.Assert(genericMethodArgs.Length > 0); Instantiation genericMethodInstantiation = typeSystemContext.ResolveRuntimeTypeHandles(genericMethodArgs); typeSystemContext.GetInstantiatedMethod(methodOnInstantiatedType, genericMethodInstantiation); } return instantiatedMethod; } #endif } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Private.Xml/tests/XmlReader/ReadContentAs/ReadAsFloatTests.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.Xml.Tests { public class FloatTests { [Fact] public static void ReadContentAsFloat1() { var reader = Utils.CreateFragmentReader("<Root> -0<!-- Comment inbetween-->05.145<?a?><![CDATA[6]]> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(-5.1456F, reader.ReadContentAsFloat()); } [Fact] public static void ReadContentAsFloat10() { var reader = Utils.CreateFragmentReader("<Root> 5<![CDATA[6]]>.455555<!-- Comment inbetween--><![CDATA[6]]>44<?a?> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(56.455555644F, reader.ReadContentAs(typeof(float), null)); } [Fact] public static void ReadContentAsFloat11() { var reader = Utils.CreateFragmentReader("<Root> -000123<?a?>45<!-- Comment inbetween--><![CDATA[6]]> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(-123456F, reader.ReadContentAs(typeof(float), null)); } [Fact] public static void ReadContentAsFloat12() { var reader = Utils.CreateFragmentReader("<Root> <![CDATA[9]]>999<!-- Comment inbetween-->9.444<?a?>5<![CDATA[6]]> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(99999.44456F, reader.ReadContentAs(typeof(float), null)); } [Fact] public static void ReadContentAsFloat2() { var reader = Utils.CreateFragmentReader("<Root> <?a?>00<!-- Comment inbetween-->9<![CDATA[9]]>.<![CDATA[9]]>99999</Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(99.999999F, reader.ReadContentAsFloat()); } [Fact] public static void ReadContentAsFloat3() { var reader = Utils.CreateFragmentReader("<Root>-5<![CDATA[6]]>.4<?a?>444<!-- Comment inbetween-->455<![CDATA[6]]> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(-56.44444556F, reader.ReadContentAsFloat()); } [Fact] public static void ReadContentAsFloat4() { var reader = Utils.CreateFragmentReader("<Root> 5<![CDATA[6]]>.455555<!-- Comment inbetween--><![CDATA[6]]>44<?a?> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(56.455555644F, reader.ReadContentAsFloat()); } [Fact] public static void ReadContentAsFloat5() { var reader = Utils.CreateFragmentReader("<Root> -000123<?a?>45<!-- Comment inbetween--><![CDATA[6]]> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(-123456F, reader.ReadContentAsFloat()); } [Fact] public static void ReadContentAsFloat6() { var reader = Utils.CreateFragmentReader("<Root> <![CDATA[9]]>999<!-- Comment inbetween-->9.444<?a?>5<![CDATA[6]]> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(99999.44456F, reader.ReadContentAsFloat()); } [Fact] public static void ReadContentAsFloat7() { var reader = Utils.CreateFragmentReader("<Root> -0<!-- Comment inbetween-->05.145<?a?><![CDATA[6]]> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(-5.1456F, reader.ReadContentAs(typeof(float), null)); } [Fact] public static void ReadContentAsFloat8() { var reader = Utils.CreateFragmentReader("<Root> <?a?>00<!-- Comment inbetween-->9<![CDATA[9]]>.<![CDATA[9]]>99999</Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(99.999999F, reader.ReadContentAs(typeof(float), null)); } [Fact] public static void ReadContentAsFloat9() { var reader = Utils.CreateFragmentReader("<Root>-5<![CDATA[6]]>.4<?a?>444<!-- Comment inbetween-->455<![CDATA[6]]> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(-56.44444556F, reader.ReadContentAs(typeof(float), null)); } } }
// 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.Xml.Tests { public class FloatTests { [Fact] public static void ReadContentAsFloat1() { var reader = Utils.CreateFragmentReader("<Root> -0<!-- Comment inbetween-->05.145<?a?><![CDATA[6]]> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(-5.1456F, reader.ReadContentAsFloat()); } [Fact] public static void ReadContentAsFloat10() { var reader = Utils.CreateFragmentReader("<Root> 5<![CDATA[6]]>.455555<!-- Comment inbetween--><![CDATA[6]]>44<?a?> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(56.455555644F, reader.ReadContentAs(typeof(float), null)); } [Fact] public static void ReadContentAsFloat11() { var reader = Utils.CreateFragmentReader("<Root> -000123<?a?>45<!-- Comment inbetween--><![CDATA[6]]> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(-123456F, reader.ReadContentAs(typeof(float), null)); } [Fact] public static void ReadContentAsFloat12() { var reader = Utils.CreateFragmentReader("<Root> <![CDATA[9]]>999<!-- Comment inbetween-->9.444<?a?>5<![CDATA[6]]> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(99999.44456F, reader.ReadContentAs(typeof(float), null)); } [Fact] public static void ReadContentAsFloat2() { var reader = Utils.CreateFragmentReader("<Root> <?a?>00<!-- Comment inbetween-->9<![CDATA[9]]>.<![CDATA[9]]>99999</Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(99.999999F, reader.ReadContentAsFloat()); } [Fact] public static void ReadContentAsFloat3() { var reader = Utils.CreateFragmentReader("<Root>-5<![CDATA[6]]>.4<?a?>444<!-- Comment inbetween-->455<![CDATA[6]]> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(-56.44444556F, reader.ReadContentAsFloat()); } [Fact] public static void ReadContentAsFloat4() { var reader = Utils.CreateFragmentReader("<Root> 5<![CDATA[6]]>.455555<!-- Comment inbetween--><![CDATA[6]]>44<?a?> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(56.455555644F, reader.ReadContentAsFloat()); } [Fact] public static void ReadContentAsFloat5() { var reader = Utils.CreateFragmentReader("<Root> -000123<?a?>45<!-- Comment inbetween--><![CDATA[6]]> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(-123456F, reader.ReadContentAsFloat()); } [Fact] public static void ReadContentAsFloat6() { var reader = Utils.CreateFragmentReader("<Root> <![CDATA[9]]>999<!-- Comment inbetween-->9.444<?a?>5<![CDATA[6]]> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(99999.44456F, reader.ReadContentAsFloat()); } [Fact] public static void ReadContentAsFloat7() { var reader = Utils.CreateFragmentReader("<Root> -0<!-- Comment inbetween-->05.145<?a?><![CDATA[6]]> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(-5.1456F, reader.ReadContentAs(typeof(float), null)); } [Fact] public static void ReadContentAsFloat8() { var reader = Utils.CreateFragmentReader("<Root> <?a?>00<!-- Comment inbetween-->9<![CDATA[9]]>.<![CDATA[9]]>99999</Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(99.999999F, reader.ReadContentAs(typeof(float), null)); } [Fact] public static void ReadContentAsFloat9() { var reader = Utils.CreateFragmentReader("<Root>-5<![CDATA[6]]>.4<?a?>444<!-- Comment inbetween-->455<![CDATA[6]]> </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Equal(-56.44444556F, reader.ReadContentAs(typeof(float), null)); } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Net.Http/tests/FunctionalTests/SelectedSitesTest.txt
http://facebook.com http://google.com http://youtube.com http://live.com http://yahoo.com http://wikipedia.org http://msn.com http://blogger.com http://microsoft.com http://bing.com http://qq.com http://baidu.com http://ask.com http://wordpress.com http://mozilla.com http://apple.com http://taobao.com http://amazon.com http://twitter.com http://ebay.com http://myspace.com http://ehow.com http://cnet.com http://flickr.com http://aol.com http://google.com.hk http://sohu.com http://yahoo.co.jp http://cnn.com http://bbc.co.uk http://linkedin.com http://craigslist.org http://google.fr http://nytimes.com http://msnbc.com http://skype.com http://mapquest.com http://uol.com.br http://alibaba.com http://paypal.com http://espn.com http://real.com http://hp.com http://dictionary.com http://sourceforge.net http://terra.com.br http://opera.com http://google.es http://walmart.com http://dailymail.co.uk
http://facebook.com http://google.com http://youtube.com http://live.com http://yahoo.com http://wikipedia.org http://msn.com http://blogger.com http://microsoft.com http://bing.com http://qq.com http://baidu.com http://ask.com http://wordpress.com http://mozilla.com http://apple.com http://taobao.com http://amazon.com http://twitter.com http://ebay.com http://myspace.com http://ehow.com http://cnet.com http://flickr.com http://aol.com http://google.com.hk http://sohu.com http://yahoo.co.jp http://cnn.com http://bbc.co.uk http://linkedin.com http://craigslist.org http://google.fr http://nytimes.com http://msnbc.com http://skype.com http://mapquest.com http://uol.com.br http://alibaba.com http://paypal.com http://espn.com http://real.com http://hp.com http://dictionary.com http://sourceforge.net http://terra.com.br http://opera.com http://google.es http://walmart.com http://dailymail.co.uk
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/SwitchExpressionException.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.Runtime.CompilerServices { /// <summary> /// Indicates that a switch expression that was non-exhaustive failed to match its input /// at runtime, e.g. in the C# 8 expression <code>3 switch { 4 => 5 }</code>. /// The exception optionally contains an object representing the unmatched value. /// </summary> [Serializable] [TypeForwardedFrom("System.Runtime.Extensions, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public sealed class SwitchExpressionException : InvalidOperationException { public SwitchExpressionException() : base(SR.Arg_SwitchExpressionException) { } public SwitchExpressionException(Exception? innerException) : base(SR.Arg_SwitchExpressionException, innerException) { } public SwitchExpressionException(object? unmatchedValue) : this() { UnmatchedValue = unmatchedValue; } private SwitchExpressionException(SerializationInfo info, StreamingContext context) : base(info, context) { UnmatchedValue = info.GetValue(nameof(UnmatchedValue), typeof(object)); } public SwitchExpressionException(string? message) : base(message) { } public SwitchExpressionException(string? message, Exception? innerException) : base(message, innerException) { } public object? UnmatchedValue { get; } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue(nameof(UnmatchedValue), UnmatchedValue, typeof(object)); } public override string Message { get { if (UnmatchedValue is null) { return base.Message; } string valueMessage = SR.Format(SR.SwitchExpressionException_UnmatchedValue, UnmatchedValue); return base.Message + Environment.NewLine + valueMessage; } } } }
// 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.Runtime.CompilerServices { /// <summary> /// Indicates that a switch expression that was non-exhaustive failed to match its input /// at runtime, e.g. in the C# 8 expression <code>3 switch { 4 => 5 }</code>. /// The exception optionally contains an object representing the unmatched value. /// </summary> [Serializable] [TypeForwardedFrom("System.Runtime.Extensions, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public sealed class SwitchExpressionException : InvalidOperationException { public SwitchExpressionException() : base(SR.Arg_SwitchExpressionException) { } public SwitchExpressionException(Exception? innerException) : base(SR.Arg_SwitchExpressionException, innerException) { } public SwitchExpressionException(object? unmatchedValue) : this() { UnmatchedValue = unmatchedValue; } private SwitchExpressionException(SerializationInfo info, StreamingContext context) : base(info, context) { UnmatchedValue = info.GetValue(nameof(UnmatchedValue), typeof(object)); } public SwitchExpressionException(string? message) : base(message) { } public SwitchExpressionException(string? message, Exception? innerException) : base(message, innerException) { } public object? UnmatchedValue { get; } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue(nameof(UnmatchedValue), UnmatchedValue, typeof(object)); } public override string Message { get { if (UnmatchedValue is null) { return base.Message; } string valueMessage = SR.Format(SR.SwitchExpressionException_UnmatchedValue, UnmatchedValue); return base.Message + Environment.NewLine + valueMessage; } } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/MultiplyBySelectedScalarWideningLowerAndSubtract.Vector64.UInt16.Vector128.UInt16.7.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector128_UInt16_7() { var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector128_UInt16_7(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector128_UInt16_7 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(UInt32[] inArray1, UInt16[] inArray2, UInt16[] inArray3, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt16, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt32> _fld1; public Vector64<UInt16> _fld2; public Vector128<UInt16> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector128_UInt16_7 testClass) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(_fld1, _fld2, _fld3, 7); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector128_UInt16_7 testClass) { fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector64<UInt16>* pFld2 = &_fld2) fixed (Vector128<UInt16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)), AdvSimd.LoadVector128((UInt16*)(pFld3)), 7 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly byte Imm = 7; private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static UInt16[] _data3 = new UInt16[Op3ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector64<UInt16> _clsVar2; private static Vector128<UInt16> _clsVar3; private Vector128<UInt32> _fld1; private Vector64<UInt16> _fld2; private Vector128<UInt16> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector128_UInt16_7() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); } public SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector128_UInt16_7() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, _data3, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray3Ptr), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray3Ptr)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract), new Type[] { typeof(Vector128<UInt32>), typeof(Vector64<UInt16>), typeof(Vector128<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray3Ptr), (byte)7 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract), new Type[] { typeof(Vector128<UInt32>), typeof(Vector64<UInt16>), typeof(Vector128<UInt16>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray3Ptr)), (byte)7 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( _clsVar1, _clsVar2, _clsVar3, 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector64<UInt16>* pClsVar2 = &_clsVar2) fixed (Vector128<UInt16>* pClsVar3 = &_clsVar3) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(pClsVar1)), AdvSimd.LoadVector64((UInt16*)(pClsVar2)), AdvSimd.LoadVector128((UInt16*)(pClsVar3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray3Ptr); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(op1, op2, op3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray3Ptr)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(op1, op2, op3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector128_UInt16_7(); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(test._fld1, test._fld2, test._fld3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector128_UInt16_7(); fixed (Vector128<UInt32>* pFld1 = &test._fld1) fixed (Vector64<UInt16>* pFld2 = &test._fld2) fixed (Vector128<UInt16>* pFld3 = &test._fld3) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)), AdvSimd.LoadVector128((UInt16*)(pFld3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(_fld1, _fld2, _fld3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector64<UInt16>* pFld2 = &_fld2) fixed (Vector128<UInt16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)), AdvSimd.LoadVector128((UInt16*)(pFld3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(test._fld1, test._fld2, test._fld3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(&test._fld1)), AdvSimd.LoadVector64((UInt16*)(&test._fld2)), AdvSimd.LoadVector128((UInt16*)(&test._fld3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt32> op1, Vector64<UInt16> op2, Vector128<UInt16> op3, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] inArray3 = new UInt16[Op3ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] inArray3 = new UInt16[Op3ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt16[] secondOp, UInt16[] thirdOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.MultiplyWideningAndSubtract(firstOp[i], secondOp[i], thirdOp[Imm]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract)}<UInt32>(Vector128<UInt32>, Vector64<UInt16>, Vector128<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector128_UInt16_7() { var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector128_UInt16_7(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector128_UInt16_7 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(UInt32[] inArray1, UInt16[] inArray2, UInt16[] inArray3, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt16, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt32> _fld1; public Vector64<UInt16> _fld2; public Vector128<UInt16> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector128_UInt16_7 testClass) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(_fld1, _fld2, _fld3, 7); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector128_UInt16_7 testClass) { fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector64<UInt16>* pFld2 = &_fld2) fixed (Vector128<UInt16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)), AdvSimd.LoadVector128((UInt16*)(pFld3)), 7 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly byte Imm = 7; private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static UInt16[] _data3 = new UInt16[Op3ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector64<UInt16> _clsVar2; private static Vector128<UInt16> _clsVar3; private Vector128<UInt32> _fld1; private Vector64<UInt16> _fld2; private Vector128<UInt16> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector128_UInt16_7() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); } public SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector128_UInt16_7() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, _data3, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray3Ptr), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray3Ptr)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract), new Type[] { typeof(Vector128<UInt32>), typeof(Vector64<UInt16>), typeof(Vector128<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray3Ptr), (byte)7 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract), new Type[] { typeof(Vector128<UInt32>), typeof(Vector64<UInt16>), typeof(Vector128<UInt16>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray3Ptr)), (byte)7 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( _clsVar1, _clsVar2, _clsVar3, 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector64<UInt16>* pClsVar2 = &_clsVar2) fixed (Vector128<UInt16>* pClsVar3 = &_clsVar3) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(pClsVar1)), AdvSimd.LoadVector64((UInt16*)(pClsVar2)), AdvSimd.LoadVector128((UInt16*)(pClsVar3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray3Ptr); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(op1, op2, op3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray3Ptr)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(op1, op2, op3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector128_UInt16_7(); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(test._fld1, test._fld2, test._fld3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector128_UInt16_7(); fixed (Vector128<UInt32>* pFld1 = &test._fld1) fixed (Vector64<UInt16>* pFld2 = &test._fld2) fixed (Vector128<UInt16>* pFld3 = &test._fld3) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)), AdvSimd.LoadVector128((UInt16*)(pFld3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(_fld1, _fld2, _fld3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector64<UInt16>* pFld2 = &_fld2) fixed (Vector128<UInt16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)), AdvSimd.LoadVector128((UInt16*)(pFld3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(test._fld1, test._fld2, test._fld3, 7); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(&test._fld1)), AdvSimd.LoadVector64((UInt16*)(&test._fld2)), AdvSimd.LoadVector128((UInt16*)(&test._fld3)), 7 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt32> op1, Vector64<UInt16> op2, Vector128<UInt16> op3, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] inArray3 = new UInt16[Op3ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] inArray3 = new UInt16[Op3ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt16[] secondOp, UInt16[] thirdOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.MultiplyWideningAndSubtract(firstOp[i], secondOp[i], thirdOp[Imm]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract)}<UInt32>(Vector128<UInt32>, Vector64<UInt16>, Vector128<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Linq.Expressions/tests/IndexExpression/SampleClassWithProperties.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.Reflection; namespace System.Linq.Expressions.Tests { internal class SampleClassWithProperties { internal readonly PropertyInfo DefaultIndexer = typeof(List<int>).GetProperty("Item"); internal readonly ConstantExpression[] DefaultArguments = { Expression.Constant(0) }; internal MemberExpression DefaultPropertyExpression => Expression.Property(Expression.Constant(this), typeof(SampleClassWithProperties).GetProperty(nameof(DefaultProperty))); internal IndexExpression DefaultIndexExpression => Expression.MakeIndex( DefaultPropertyExpression, DefaultIndexer, DefaultArguments); public List<int> DefaultProperty { get; set; } public List<int> AlternativeProperty { get; set; } } }
// 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.Reflection; namespace System.Linq.Expressions.Tests { internal class SampleClassWithProperties { internal readonly PropertyInfo DefaultIndexer = typeof(List<int>).GetProperty("Item"); internal readonly ConstantExpression[] DefaultArguments = { Expression.Constant(0) }; internal MemberExpression DefaultPropertyExpression => Expression.Property(Expression.Constant(this), typeof(SampleClassWithProperties).GetProperty(nameof(DefaultProperty))); internal IndexExpression DefaultIndexExpression => Expression.MakeIndex( DefaultPropertyExpression, DefaultIndexer, DefaultArguments); public List<int> DefaultProperty { get; set; } public List<int> AlternativeProperty { get; set; } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/FusedSubtractHalving.Vector128.UInt16.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void FusedSubtractHalving_Vector128_UInt16() { var test = new SimpleBinaryOpTest__FusedSubtractHalving_Vector128_UInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__FusedSubtractHalving_Vector128_UInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public 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(SimpleBinaryOpTest__FusedSubtractHalving_Vector128_UInt16 testClass) { var result = AdvSimd.FusedSubtractHalving(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__FusedSubtractHalving_Vector128_UInt16 testClass) { fixed (Vector128<UInt16>* pFld1 = &_fld1) fixed (Vector128<UInt16>* pFld2 = &_fld2) { var result = AdvSimd.FusedSubtractHalving( AdvSimd.LoadVector128((UInt16*)(pFld1)), AdvSimd.LoadVector128((UInt16*)(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<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = 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 SimpleBinaryOpTest__FusedSubtractHalving_Vector128_UInt16() { 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 SimpleBinaryOpTest__FusedSubtractHalving_Vector128_UInt16() { 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, 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.FusedSubtractHalving( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.FusedSubtractHalving( AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.FusedSubtractHalving), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_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.FusedSubtractHalving), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt16*)(_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.FusedSubtractHalving( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt16>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt16>* pClsVar2 = &_clsVar2) { var result = AdvSimd.FusedSubtractHalving( AdvSimd.LoadVector128((UInt16*)(pClsVar1)), AdvSimd.LoadVector128((UInt16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr); var result = AdvSimd.FusedSubtractHalving(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((UInt16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = AdvSimd.FusedSubtractHalving(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__FusedSubtractHalving_Vector128_UInt16(); var result = AdvSimd.FusedSubtractHalving(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__FusedSubtractHalving_Vector128_UInt16(); fixed (Vector128<UInt16>* pFld1 = &test._fld1) fixed (Vector128<UInt16>* pFld2 = &test._fld2) { var result = AdvSimd.FusedSubtractHalving( AdvSimd.LoadVector128((UInt16*)(pFld1)), AdvSimd.LoadVector128((UInt16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.FusedSubtractHalving(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt16>* pFld1 = &_fld1) fixed (Vector128<UInt16>* pFld2 = &_fld2) { var result = AdvSimd.FusedSubtractHalving( AdvSimd.LoadVector128((UInt16*)(pFld1)), AdvSimd.LoadVector128((UInt16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.FusedSubtractHalving(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.FusedSubtractHalving( AdvSimd.LoadVector128((UInt16*)(&test._fld1)), AdvSimd.LoadVector128((UInt16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt16> op1, Vector128<UInt16> op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); 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(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.FusedSubtractHalving(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.FusedSubtractHalving)}<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: ({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 FusedSubtractHalving_Vector128_UInt16() { var test = new SimpleBinaryOpTest__FusedSubtractHalving_Vector128_UInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__FusedSubtractHalving_Vector128_UInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public 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(SimpleBinaryOpTest__FusedSubtractHalving_Vector128_UInt16 testClass) { var result = AdvSimd.FusedSubtractHalving(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__FusedSubtractHalving_Vector128_UInt16 testClass) { fixed (Vector128<UInt16>* pFld1 = &_fld1) fixed (Vector128<UInt16>* pFld2 = &_fld2) { var result = AdvSimd.FusedSubtractHalving( AdvSimd.LoadVector128((UInt16*)(pFld1)), AdvSimd.LoadVector128((UInt16*)(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<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = 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 SimpleBinaryOpTest__FusedSubtractHalving_Vector128_UInt16() { 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 SimpleBinaryOpTest__FusedSubtractHalving_Vector128_UInt16() { 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, 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.FusedSubtractHalving( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.FusedSubtractHalving( AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.FusedSubtractHalving), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_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.FusedSubtractHalving), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((UInt16*)(_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.FusedSubtractHalving( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt16>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt16>* pClsVar2 = &_clsVar2) { var result = AdvSimd.FusedSubtractHalving( AdvSimd.LoadVector128((UInt16*)(pClsVar1)), AdvSimd.LoadVector128((UInt16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr); var result = AdvSimd.FusedSubtractHalving(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((UInt16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = AdvSimd.FusedSubtractHalving(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__FusedSubtractHalving_Vector128_UInt16(); var result = AdvSimd.FusedSubtractHalving(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__FusedSubtractHalving_Vector128_UInt16(); fixed (Vector128<UInt16>* pFld1 = &test._fld1) fixed (Vector128<UInt16>* pFld2 = &test._fld2) { var result = AdvSimd.FusedSubtractHalving( AdvSimd.LoadVector128((UInt16*)(pFld1)), AdvSimd.LoadVector128((UInt16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.FusedSubtractHalving(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt16>* pFld1 = &_fld1) fixed (Vector128<UInt16>* pFld2 = &_fld2) { var result = AdvSimd.FusedSubtractHalving( AdvSimd.LoadVector128((UInt16*)(pFld1)), AdvSimd.LoadVector128((UInt16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.FusedSubtractHalving(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.FusedSubtractHalving( AdvSimd.LoadVector128((UInt16*)(&test._fld1)), AdvSimd.LoadVector128((UInt16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt16> op1, Vector128<UInt16> op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); 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(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.FusedSubtractHalving(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.FusedSubtractHalving)}<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: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/X86/Sse3.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; namespace System.Runtime.Intrinsics.X86 { /// <summary> /// This class provides access to Intel SSE3 hardware instructions via intrinsics /// </summary> [Intrinsic] [CLSCompliant(false)] public abstract class Sse3 : Sse2 { internal Sse3() { } public static new bool IsSupported { get => IsSupported; } [Intrinsic] public new abstract class X64 : Sse2.X64 { internal X64() { } public static new bool IsSupported { get => IsSupported; } } /// <summary> /// __m128 _mm_addsub_ps (__m128 a, __m128 b) /// ADDSUBPS xmm, xmm/m128 /// </summary> public static Vector128<float> AddSubtract(Vector128<float> left, Vector128<float> right) => AddSubtract(left, right); /// <summary> /// __m128d _mm_addsub_pd (__m128d a, __m128d b) /// ADDSUBPD xmm, xmm/m128 /// </summary> public static Vector128<double> AddSubtract(Vector128<double> left, Vector128<double> right) => AddSubtract(left, right); /// <summary> /// __m128 _mm_hadd_ps (__m128 a, __m128 b) /// HADDPS xmm, xmm/m128 /// </summary> public static Vector128<float> HorizontalAdd(Vector128<float> left, Vector128<float> right) => HorizontalAdd(left, right); /// <summary> /// __m128d _mm_hadd_pd (__m128d a, __m128d b) /// HADDPD xmm, xmm/m128 /// </summary> public static Vector128<double> HorizontalAdd(Vector128<double> left, Vector128<double> right) => HorizontalAdd(left, right); /// <summary> /// __m128 _mm_hsub_ps (__m128 a, __m128 b) /// HSUBPS xmm, xmm/m128 /// </summary> public static Vector128<float> HorizontalSubtract(Vector128<float> left, Vector128<float> right) => HorizontalSubtract(left, right); /// <summary> /// __m128d _mm_hsub_pd (__m128d a, __m128d b) /// HSUBPD xmm, xmm/m128 /// </summary> public static Vector128<double> HorizontalSubtract(Vector128<double> left, Vector128<double> right) => HorizontalSubtract(left, right); /// <summary> /// __m128d _mm_loaddup_pd (double const* mem_addr) /// MOVDDUP xmm, m64 /// </summary> public static unsafe Vector128<double> LoadAndDuplicateToVector128(double* address) => LoadAndDuplicateToVector128(address); /// <summary> /// __m128i _mm_lddqu_si128 (__m128i const* mem_addr) /// LDDQU xmm, m128 /// </summary> public static unsafe Vector128<sbyte> LoadDquVector128(sbyte* address) => LoadDquVector128(address); public static unsafe Vector128<byte> LoadDquVector128(byte* address) => LoadDquVector128(address); public static unsafe Vector128<short> LoadDquVector128(short* address) => LoadDquVector128(address); public static unsafe Vector128<ushort> LoadDquVector128(ushort* address) => LoadDquVector128(address); public static unsafe Vector128<int> LoadDquVector128(int* address) => LoadDquVector128(address); public static unsafe Vector128<uint> LoadDquVector128(uint* address) => LoadDquVector128(address); public static unsafe Vector128<long> LoadDquVector128(long* address) => LoadDquVector128(address); public static unsafe Vector128<ulong> LoadDquVector128(ulong* address) => LoadDquVector128(address); /// <summary> /// __m128d _mm_movedup_pd (__m128d a) /// MOVDDUP xmm, xmm/m64 /// </summary> public static Vector128<double> MoveAndDuplicate(Vector128<double> source) => MoveAndDuplicate(source); /// <summary> /// __m128 _mm_movehdup_ps (__m128 a) /// MOVSHDUP xmm, xmm/m128 /// </summary> public static Vector128<float> MoveHighAndDuplicate(Vector128<float> source) => MoveHighAndDuplicate(source); /// <summary> /// __m128 _mm_moveldup_ps (__m128 a) /// MOVSLDUP xmm, xmm/m128 /// </summary> public static Vector128<float> MoveLowAndDuplicate(Vector128<float> source) => MoveLowAndDuplicate(source); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; namespace System.Runtime.Intrinsics.X86 { /// <summary> /// This class provides access to Intel SSE3 hardware instructions via intrinsics /// </summary> [Intrinsic] [CLSCompliant(false)] public abstract class Sse3 : Sse2 { internal Sse3() { } public static new bool IsSupported { get => IsSupported; } [Intrinsic] public new abstract class X64 : Sse2.X64 { internal X64() { } public static new bool IsSupported { get => IsSupported; } } /// <summary> /// __m128 _mm_addsub_ps (__m128 a, __m128 b) /// ADDSUBPS xmm, xmm/m128 /// </summary> public static Vector128<float> AddSubtract(Vector128<float> left, Vector128<float> right) => AddSubtract(left, right); /// <summary> /// __m128d _mm_addsub_pd (__m128d a, __m128d b) /// ADDSUBPD xmm, xmm/m128 /// </summary> public static Vector128<double> AddSubtract(Vector128<double> left, Vector128<double> right) => AddSubtract(left, right); /// <summary> /// __m128 _mm_hadd_ps (__m128 a, __m128 b) /// HADDPS xmm, xmm/m128 /// </summary> public static Vector128<float> HorizontalAdd(Vector128<float> left, Vector128<float> right) => HorizontalAdd(left, right); /// <summary> /// __m128d _mm_hadd_pd (__m128d a, __m128d b) /// HADDPD xmm, xmm/m128 /// </summary> public static Vector128<double> HorizontalAdd(Vector128<double> left, Vector128<double> right) => HorizontalAdd(left, right); /// <summary> /// __m128 _mm_hsub_ps (__m128 a, __m128 b) /// HSUBPS xmm, xmm/m128 /// </summary> public static Vector128<float> HorizontalSubtract(Vector128<float> left, Vector128<float> right) => HorizontalSubtract(left, right); /// <summary> /// __m128d _mm_hsub_pd (__m128d a, __m128d b) /// HSUBPD xmm, xmm/m128 /// </summary> public static Vector128<double> HorizontalSubtract(Vector128<double> left, Vector128<double> right) => HorizontalSubtract(left, right); /// <summary> /// __m128d _mm_loaddup_pd (double const* mem_addr) /// MOVDDUP xmm, m64 /// </summary> public static unsafe Vector128<double> LoadAndDuplicateToVector128(double* address) => LoadAndDuplicateToVector128(address); /// <summary> /// __m128i _mm_lddqu_si128 (__m128i const* mem_addr) /// LDDQU xmm, m128 /// </summary> public static unsafe Vector128<sbyte> LoadDquVector128(sbyte* address) => LoadDquVector128(address); public static unsafe Vector128<byte> LoadDquVector128(byte* address) => LoadDquVector128(address); public static unsafe Vector128<short> LoadDquVector128(short* address) => LoadDquVector128(address); public static unsafe Vector128<ushort> LoadDquVector128(ushort* address) => LoadDquVector128(address); public static unsafe Vector128<int> LoadDquVector128(int* address) => LoadDquVector128(address); public static unsafe Vector128<uint> LoadDquVector128(uint* address) => LoadDquVector128(address); public static unsafe Vector128<long> LoadDquVector128(long* address) => LoadDquVector128(address); public static unsafe Vector128<ulong> LoadDquVector128(ulong* address) => LoadDquVector128(address); /// <summary> /// __m128d _mm_movedup_pd (__m128d a) /// MOVDDUP xmm, xmm/m64 /// </summary> public static Vector128<double> MoveAndDuplicate(Vector128<double> source) => MoveAndDuplicate(source); /// <summary> /// __m128 _mm_movehdup_ps (__m128 a) /// MOVSHDUP xmm, xmm/m128 /// </summary> public static Vector128<float> MoveHighAndDuplicate(Vector128<float> source) => MoveHighAndDuplicate(source); /// <summary> /// __m128 _mm_moveldup_ps (__m128 a) /// MOVSLDUP xmm, xmm/m128 /// </summary> public static Vector128<float> MoveLowAndDuplicate(Vector128<float> source) => MoveLowAndDuplicate(source); } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/HardwareIntrinsics/General/Vector128/ConditionalSelect.Int32.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void ConditionalSelectInt32() { var test = new VectorTernaryOpTest__ConditionalSelectInt32(); // 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 VectorTernaryOpTest__ConditionalSelectInt32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] inArray3, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int32, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int32> _fld1; public Vector128<Int32> _fld2; public Vector128<Int32> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(VectorTernaryOpTest__ConditionalSelectInt32 testClass) { var result = Vector128.ConditionalSelect(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Int32[] _data3 = new Int32[Op3ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private static Vector128<Int32> _clsVar3; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private Vector128<Int32> _fld3; private DataTable _dataTable; static VectorTernaryOpTest__ConditionalSelectInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public VectorTernaryOpTest__ConditionalSelectInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, _data3, new Int32[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.ConditionalSelect( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector128).GetMethod(nameof(Vector128.ConditionalSelect), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(Vector128<Int32>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.ConditionalSelect), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int32)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.ConditionalSelect( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr); var result = Vector128.ConditionalSelect(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorTernaryOpTest__ConditionalSelectInt32(); var result = Vector128.ConditionalSelect(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.ConditionalSelect(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.ConditionalSelect(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector128<Int32> op1, Vector128<Int32> op2, Vector128<Int32> op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int32[] thirdOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (int)((secondOp[0] & firstOp[0]) | (thirdOp[0] & ~firstOp[0]))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (int)((secondOp[i] & firstOp[i]) | (thirdOp[i] & ~firstOp[i]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.ConditionalSelect)}<Int32>(Vector128<Int32>, Vector128<Int32>, Vector128<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\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 ConditionalSelectInt32() { var test = new VectorTernaryOpTest__ConditionalSelectInt32(); // 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 VectorTernaryOpTest__ConditionalSelectInt32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] inArray3, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int32, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int32> _fld1; public Vector128<Int32> _fld2; public Vector128<Int32> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(VectorTernaryOpTest__ConditionalSelectInt32 testClass) { var result = Vector128.ConditionalSelect(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Int32[] _data3 = new Int32[Op3ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private static Vector128<Int32> _clsVar3; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private Vector128<Int32> _fld3; private DataTable _dataTable; static VectorTernaryOpTest__ConditionalSelectInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public VectorTernaryOpTest__ConditionalSelectInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, _data3, new Int32[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.ConditionalSelect( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector128).GetMethod(nameof(Vector128.ConditionalSelect), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(Vector128<Int32>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.ConditionalSelect), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int32)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.ConditionalSelect( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr); var result = Vector128.ConditionalSelect(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorTernaryOpTest__ConditionalSelectInt32(); var result = Vector128.ConditionalSelect(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.ConditionalSelect(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.ConditionalSelect(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector128<Int32> op1, Vector128<Int32> op2, Vector128<Int32> op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int32[] thirdOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (int)((secondOp[0] & firstOp[0]) | (thirdOp[0] & ~firstOp[0]))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (int)((secondOp[i] & firstOp[i]) | (thirdOp[i] & ~firstOp[i]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.ConditionalSelect)}<Int32>(Vector128<Int32>, Vector128<Int32>, Vector128<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/SIMD/VectorUnused_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="VectorUnused.cs" /> <Compile Include="VectorUtil.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="VectorUnused.cs" /> <Compile Include="VectorUtil.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/Regression/JitBlue/Runtime_56935/Runtime_56935.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; namespace Runtime_56935 { public class Program { static int clsFld; public static int Main() { int zeroVal = 0; // The rhs of the following statement on Arm64 will be transformed into the following tree // // N012 ( 27, 14) [000009] ---X-------- * ADD int $42 // N010 ( 25, 11) [000029] ---X-------- +--* ADD int $40 // N008 ( 23, 8) [000032] ---X-------- | +--* NEG int $41 // N007 ( 22, 7) [000008] ---X-------- | | \--* DIV int $42 // N003 ( 1, 2) [000004] ------------ | | +--* CNS_INT int 1 $42 // N006 ( 1, 2) [000024] ------------ | | \--* COMMA int $42 // N004 ( 0, 0) [000022] ------------ | | +--* NOP void $100 // N005 ( 1, 2) [000023] ------------ | | \--* CNS_INT int 1 $42 // N009 ( 1, 2) [000028] ------------ | \--* CNS_INT int 1 $42 // N011 ( 1, 2) [000003] ------------ \--* CNS_INT int 1 $42 // // Then, during optValnumCSE() the tree is transformed even further by fgMorphCommutative() // // N014 ( 25, 11) [000029] ---X-------- * ADD int $40 // N012 ( 23, 8) [000032] ---X-------- +--* NEG int $41 // N011 ( 22, 7) [000008] ---X-------- | \--* DIV int $42 // N007 ( 1, 2) [000004] ------------ | +--* CNS_INT int 1 $42 // N010 ( 1, 2) [000024] ------------ | \--* COMMA int $42 // N008 ( 0, 0) [000022] ------------ | +--* NOP void $100 // N009 ( 1, 2) [000023] ------------ | \--* CNS_INT int 1 $42 // N013 ( 1, 2) [000028] ------------ \--* CNS_INT int 2 $42 // // The issue is that VN for [000028] has not been updated ($42 corresponds to CnsInt(1)). // As a result, during optVNAssertionPropCurStmt() the whole tree is **incorrecly** folded to // // After constant propagation on [000029]: // N007 ( 1, 2) [000040] ------------ * CNS_INT int 0 $40 clsFld = 1 + (1 % (zeroVal + 1)); return (clsFld == 1) ? 100 : 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.CompilerServices; namespace Runtime_56935 { public class Program { static int clsFld; public static int Main() { int zeroVal = 0; // The rhs of the following statement on Arm64 will be transformed into the following tree // // N012 ( 27, 14) [000009] ---X-------- * ADD int $42 // N010 ( 25, 11) [000029] ---X-------- +--* ADD int $40 // N008 ( 23, 8) [000032] ---X-------- | +--* NEG int $41 // N007 ( 22, 7) [000008] ---X-------- | | \--* DIV int $42 // N003 ( 1, 2) [000004] ------------ | | +--* CNS_INT int 1 $42 // N006 ( 1, 2) [000024] ------------ | | \--* COMMA int $42 // N004 ( 0, 0) [000022] ------------ | | +--* NOP void $100 // N005 ( 1, 2) [000023] ------------ | | \--* CNS_INT int 1 $42 // N009 ( 1, 2) [000028] ------------ | \--* CNS_INT int 1 $42 // N011 ( 1, 2) [000003] ------------ \--* CNS_INT int 1 $42 // // Then, during optValnumCSE() the tree is transformed even further by fgMorphCommutative() // // N014 ( 25, 11) [000029] ---X-------- * ADD int $40 // N012 ( 23, 8) [000032] ---X-------- +--* NEG int $41 // N011 ( 22, 7) [000008] ---X-------- | \--* DIV int $42 // N007 ( 1, 2) [000004] ------------ | +--* CNS_INT int 1 $42 // N010 ( 1, 2) [000024] ------------ | \--* COMMA int $42 // N008 ( 0, 0) [000022] ------------ | +--* NOP void $100 // N009 ( 1, 2) [000023] ------------ | \--* CNS_INT int 1 $42 // N013 ( 1, 2) [000028] ------------ \--* CNS_INT int 2 $42 // // The issue is that VN for [000028] has not been updated ($42 corresponds to CnsInt(1)). // As a result, during optVNAssertionPropCurStmt() the whole tree is **incorrecly** folded to // // After constant propagation on [000029]: // N007 ( 1, 2) [000040] ------------ * CNS_INT int 0 $40 clsFld = 1 + (1 % (zeroVal + 1)); return (clsFld == 1) ? 100 : 0; } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RC2Implementation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using Internal.Cryptography; namespace System.Security.Cryptography { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "We are providing the implementation for RC2, not consuming it.")] internal sealed partial class RC2Implementation : RC2 { private const int BitsPerByte = 8; public override int EffectiveKeySize { get { return KeySizeValue; } set { if (value != KeySizeValue) throw new CryptographicUnexpectedOperationException(SR.Cryptography_RC2_EKSKS2); } } public override ICryptoTransform CreateDecryptor() { return CreateTransform(Key, IV, encrypting: false); } public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV) { return CreateTransform(rgbKey, rgbIV.CloneByteArray(), encrypting: false); } public override ICryptoTransform CreateEncryptor() { return CreateTransform(Key, IV, encrypting: true); } public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV) { return CreateTransform(rgbKey, rgbIV.CloneByteArray(), encrypting: true); } public override void GenerateIV() { IV = RandomNumberGenerator.GetBytes(BlockSize / BitsPerByte); } public sealed override void GenerateKey() { Key = RandomNumberGenerator.GetBytes(KeySize / BitsPerByte); } private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encrypting) { ArgumentNullException.ThrowIfNull(rgbKey); // note: rgbIV is guaranteed to be cloned before this method, so no need to clone it again if (!ValidKeySize(rgbKey.Length)) throw new ArgumentException(SR.Cryptography_InvalidKeySize, nameof(rgbKey)); if (rgbIV != null) { long ivSize = rgbIV.Length * (long)BitsPerByte; if (ivSize != BlockSize) throw new ArgumentException(SR.Cryptography_InvalidIVSize, nameof(rgbIV)); } if (Mode == CipherMode.CFB) { ValidateCFBFeedbackSize(FeedbackSize); } Debug.Assert(EffectiveKeySize == KeySize); return CreateTransformCore(Mode, Padding, rgbKey, rgbIV, BlockSize / BitsPerByte, FeedbackSize / BitsPerByte, GetPaddingSize(), encrypting); } protected override bool TryDecryptEcbCore( ReadOnlySpan<byte> ciphertext, Span<byte> destination, PaddingMode paddingMode, out int bytesWritten) { if (!ValidKeySize(Key.Length)) throw new InvalidOperationException(SR.Cryptography_InvalidKeySize); Debug.Assert(EffectiveKeySize == KeySize); ILiteSymmetricCipher cipher = CreateLiteCipher( CipherMode.ECB, paddingMode, Key, iv: null, blockSize: BlockSize / BitsPerByte, 0, /*feedback size */ paddingSize: BlockSize / BitsPerByte, encrypting: false); using (cipher) { return UniversalCryptoOneShot.OneShotDecrypt(cipher, paddingMode, ciphertext, destination, out bytesWritten); } } protected override bool TryEncryptEcbCore( ReadOnlySpan<byte> plaintext, Span<byte> destination, PaddingMode paddingMode, out int bytesWritten) { if (!ValidKeySize(Key.Length)) throw new InvalidOperationException(SR.Cryptography_InvalidKeySize); Debug.Assert(EffectiveKeySize == KeySize); ILiteSymmetricCipher cipher = CreateLiteCipher( CipherMode.ECB, paddingMode, Key, iv: default, blockSize: BlockSize / BitsPerByte, 0, /*feedback size */ paddingSize: BlockSize / BitsPerByte, encrypting: true); using (cipher) { return UniversalCryptoOneShot.OneShotEncrypt(cipher, paddingMode, plaintext, destination, out bytesWritten); } } protected override bool TryEncryptCbcCore( ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> iv, Span<byte> destination, PaddingMode paddingMode, out int bytesWritten) { if (!ValidKeySize(Key.Length)) throw new InvalidOperationException(SR.Cryptography_InvalidKeySize); Debug.Assert(EffectiveKeySize == KeySize); ILiteSymmetricCipher cipher = CreateLiteCipher( CipherMode.CBC, paddingMode, Key, iv, blockSize: BlockSize / BitsPerByte, 0, /*feedback size */ paddingSize: BlockSize / BitsPerByte, encrypting: true); using (cipher) { return UniversalCryptoOneShot.OneShotEncrypt(cipher, paddingMode, plaintext, destination, out bytesWritten); } } protected override bool TryDecryptCbcCore( ReadOnlySpan<byte> ciphertext, ReadOnlySpan<byte> iv, Span<byte> destination, PaddingMode paddingMode, out int bytesWritten) { if (!ValidKeySize(Key.Length)) throw new InvalidOperationException(SR.Cryptography_InvalidKeySize); Debug.Assert(EffectiveKeySize == KeySize); ILiteSymmetricCipher cipher = CreateLiteCipher( CipherMode.CBC, paddingMode, Key, iv, blockSize: BlockSize / BitsPerByte, 0, /*feedback size */ paddingSize: BlockSize / BitsPerByte, encrypting: false); using (cipher) { return UniversalCryptoOneShot.OneShotDecrypt(cipher, paddingMode, ciphertext, destination, out bytesWritten); } } protected override bool TryDecryptCfbCore( ReadOnlySpan<byte> ciphertext, ReadOnlySpan<byte> iv, Span<byte> destination, PaddingMode paddingMode, int feedbackSizeInBits, out int bytesWritten) { throw new CryptographicException(SR.Format(SR.Cryptography_CipherModeNotSupported, CipherMode.CFB)); } protected override bool TryEncryptCfbCore( ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> iv, Span<byte> destination, PaddingMode paddingMode, int feedbackSizeInBits, out int bytesWritten) { throw new CryptographicException(SR.Format(SR.Cryptography_CipherModeNotSupported, CipherMode.CFB)); } private static void ValidateCFBFeedbackSize(int feedback) { // CFB not supported at all throw new CryptographicException(string.Format(SR.Cryptography_CipherModeFeedbackNotSupported, feedback, CipherMode.CFB)); } private int GetPaddingSize() { return BlockSize / BitsPerByte; } private new bool ValidKeySize(int keySizeBytes) { if (keySizeBytes > (int.MaxValue / BitsPerByte)) { return false; } int keySizeBits = keySizeBytes << 3; return keySizeBits.IsLegalSize(LegalKeySizes); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using Internal.Cryptography; namespace System.Security.Cryptography { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "We are providing the implementation for RC2, not consuming it.")] internal sealed partial class RC2Implementation : RC2 { private const int BitsPerByte = 8; public override int EffectiveKeySize { get { return KeySizeValue; } set { if (value != KeySizeValue) throw new CryptographicUnexpectedOperationException(SR.Cryptography_RC2_EKSKS2); } } public override ICryptoTransform CreateDecryptor() { return CreateTransform(Key, IV, encrypting: false); } public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV) { return CreateTransform(rgbKey, rgbIV.CloneByteArray(), encrypting: false); } public override ICryptoTransform CreateEncryptor() { return CreateTransform(Key, IV, encrypting: true); } public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV) { return CreateTransform(rgbKey, rgbIV.CloneByteArray(), encrypting: true); } public override void GenerateIV() { IV = RandomNumberGenerator.GetBytes(BlockSize / BitsPerByte); } public sealed override void GenerateKey() { Key = RandomNumberGenerator.GetBytes(KeySize / BitsPerByte); } private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encrypting) { ArgumentNullException.ThrowIfNull(rgbKey); // note: rgbIV is guaranteed to be cloned before this method, so no need to clone it again if (!ValidKeySize(rgbKey.Length)) throw new ArgumentException(SR.Cryptography_InvalidKeySize, nameof(rgbKey)); if (rgbIV != null) { long ivSize = rgbIV.Length * (long)BitsPerByte; if (ivSize != BlockSize) throw new ArgumentException(SR.Cryptography_InvalidIVSize, nameof(rgbIV)); } if (Mode == CipherMode.CFB) { ValidateCFBFeedbackSize(FeedbackSize); } Debug.Assert(EffectiveKeySize == KeySize); return CreateTransformCore(Mode, Padding, rgbKey, rgbIV, BlockSize / BitsPerByte, FeedbackSize / BitsPerByte, GetPaddingSize(), encrypting); } protected override bool TryDecryptEcbCore( ReadOnlySpan<byte> ciphertext, Span<byte> destination, PaddingMode paddingMode, out int bytesWritten) { if (!ValidKeySize(Key.Length)) throw new InvalidOperationException(SR.Cryptography_InvalidKeySize); Debug.Assert(EffectiveKeySize == KeySize); ILiteSymmetricCipher cipher = CreateLiteCipher( CipherMode.ECB, paddingMode, Key, iv: null, blockSize: BlockSize / BitsPerByte, 0, /*feedback size */ paddingSize: BlockSize / BitsPerByte, encrypting: false); using (cipher) { return UniversalCryptoOneShot.OneShotDecrypt(cipher, paddingMode, ciphertext, destination, out bytesWritten); } } protected override bool TryEncryptEcbCore( ReadOnlySpan<byte> plaintext, Span<byte> destination, PaddingMode paddingMode, out int bytesWritten) { if (!ValidKeySize(Key.Length)) throw new InvalidOperationException(SR.Cryptography_InvalidKeySize); Debug.Assert(EffectiveKeySize == KeySize); ILiteSymmetricCipher cipher = CreateLiteCipher( CipherMode.ECB, paddingMode, Key, iv: default, blockSize: BlockSize / BitsPerByte, 0, /*feedback size */ paddingSize: BlockSize / BitsPerByte, encrypting: true); using (cipher) { return UniversalCryptoOneShot.OneShotEncrypt(cipher, paddingMode, plaintext, destination, out bytesWritten); } } protected override bool TryEncryptCbcCore( ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> iv, Span<byte> destination, PaddingMode paddingMode, out int bytesWritten) { if (!ValidKeySize(Key.Length)) throw new InvalidOperationException(SR.Cryptography_InvalidKeySize); Debug.Assert(EffectiveKeySize == KeySize); ILiteSymmetricCipher cipher = CreateLiteCipher( CipherMode.CBC, paddingMode, Key, iv, blockSize: BlockSize / BitsPerByte, 0, /*feedback size */ paddingSize: BlockSize / BitsPerByte, encrypting: true); using (cipher) { return UniversalCryptoOneShot.OneShotEncrypt(cipher, paddingMode, plaintext, destination, out bytesWritten); } } protected override bool TryDecryptCbcCore( ReadOnlySpan<byte> ciphertext, ReadOnlySpan<byte> iv, Span<byte> destination, PaddingMode paddingMode, out int bytesWritten) { if (!ValidKeySize(Key.Length)) throw new InvalidOperationException(SR.Cryptography_InvalidKeySize); Debug.Assert(EffectiveKeySize == KeySize); ILiteSymmetricCipher cipher = CreateLiteCipher( CipherMode.CBC, paddingMode, Key, iv, blockSize: BlockSize / BitsPerByte, 0, /*feedback size */ paddingSize: BlockSize / BitsPerByte, encrypting: false); using (cipher) { return UniversalCryptoOneShot.OneShotDecrypt(cipher, paddingMode, ciphertext, destination, out bytesWritten); } } protected override bool TryDecryptCfbCore( ReadOnlySpan<byte> ciphertext, ReadOnlySpan<byte> iv, Span<byte> destination, PaddingMode paddingMode, int feedbackSizeInBits, out int bytesWritten) { throw new CryptographicException(SR.Format(SR.Cryptography_CipherModeNotSupported, CipherMode.CFB)); } protected override bool TryEncryptCfbCore( ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> iv, Span<byte> destination, PaddingMode paddingMode, int feedbackSizeInBits, out int bytesWritten) { throw new CryptographicException(SR.Format(SR.Cryptography_CipherModeNotSupported, CipherMode.CFB)); } private static void ValidateCFBFeedbackSize(int feedback) { // CFB not supported at all throw new CryptographicException(string.Format(SR.Cryptography_CipherModeFeedbackNotSupported, feedback, CipherMode.CFB)); } private int GetPaddingSize() { return BlockSize / BitsPerByte; } private new bool ValidKeySize(int keySizeBytes) { if (keySizeBytes > (int.MaxValue / BitsPerByte)) { return false; } int keySizeBits = keySizeBytes << 3; return keySizeBits.IsLegalSize(LegalKeySizes); } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M10/b06859/b06859.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 { using System; using System.Collections; internal class test { public static void ccc(byte[] bytes) { int[] m_array; int m_length; if (bytes == null) { throw new ArgumentNullException("bytes"); } m_array = new int[(bytes.Length + 3) / 4]; m_length = bytes.Length * 8; int i = 0; int j = 0; while (bytes.Length - j >= 4) { m_array[i++] = (bytes[j] & 0xff) | ((bytes[j + 1] & 0xff) << 8) | ((bytes[j + 2] & 0xff) << 16) | ((bytes[j + 3] & 0xff) << 24); j += 4; } if (bytes.Length - j >= 0) { Console.WriteLine("hhhh"); } } public static int Main(String[] args) { byte[] ub = new byte[0]; ccc(ub); 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 { using System; using System.Collections; internal class test { public static void ccc(byte[] bytes) { int[] m_array; int m_length; if (bytes == null) { throw new ArgumentNullException("bytes"); } m_array = new int[(bytes.Length + 3) / 4]; m_length = bytes.Length * 8; int i = 0; int j = 0; while (bytes.Length - j >= 4) { m_array[i++] = (bytes[j] & 0xff) | ((bytes[j + 1] & 0xff) << 8) | ((bytes[j + 2] & 0xff) << 16) | ((bytes[j + 3] & 0xff) << 24); j += 4; } if (bytes.Length - j >= 0) { Console.WriteLine("hhhh"); } } public static int Main(String[] args) { byte[] ub = new byte[0]; ccc(ub); return 100; } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Memory/tests/Span/ToString.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 Xunit; namespace System.SpanTests { public static partial class SpanTests { [Fact] public static void ToStringInt() { int[] a = { 91, 92, 93 }; var span = new Span<int>(a); Assert.Equal("System.Span<Int32>[3]", span.ToString()); } [Fact] public static void ToStringInt_Empty() { var span = new Span<int>(); Assert.Equal("System.Span<Int32>[0]", span.ToString()); } [Fact] public static unsafe void ToStringChar() { char[] a = { 'a', 'b', 'c' }; var span = new Span<char>(a); Assert.Equal("abc", span.ToString()); string testString = "abcdefg"; ReadOnlySpan<char> readOnlySpan = testString.AsSpan(); fixed (void* ptr = &MemoryMarshal.GetReference(readOnlySpan)) { var temp = new Span<char>(ptr, readOnlySpan.Length); Assert.Equal(testString, temp.ToString()); } } [Fact] public static void ToStringChar_Empty() { var span = new Span<char>(); Assert.Equal("", span.ToString()); } [Fact] public static void ToStringForSpanOfString() { string[] a = { "a", "b", "c" }; var span = new Span<string>(a); Assert.Equal("System.Span<String>[3]", span.ToString()); } [Fact] public static void ToStringSpanOverFullStringDoesNotReturnOriginal() { string original = TestHelpers.BuildString(10, 42); ReadOnlyMemory<char> readOnlyMemory = original.AsMemory(); Memory<char> memory = MemoryMarshal.AsMemory(readOnlyMemory); Span<char> span = memory.Span; string returnedString = span.ToString(); string returnedStringUsingSlice = span.Slice(0, original.Length).ToString(); string subString1 = span.Slice(1).ToString(); string subString2 = span.Slice(0, 2).ToString(); string subString3 = span.Slice(1, 2).ToString(); Assert.Equal(original, returnedString); Assert.Equal(original, returnedStringUsingSlice); Assert.Equal(original.Substring(1), subString1); Assert.Equal(original.Substring(0, 2), subString2); Assert.Equal(original.Substring(1, 2), subString3); Assert.NotSame(original, returnedString); Assert.NotSame(original, returnedStringUsingSlice); Assert.NotSame(original, subString1); Assert.NotSame(original, subString2); Assert.NotSame(original, subString3); Assert.NotSame(subString1, subString2); Assert.NotSame(subString1, subString3); Assert.NotSame(subString2, subString3); } } }
// 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 Xunit; namespace System.SpanTests { public static partial class SpanTests { [Fact] public static void ToStringInt() { int[] a = { 91, 92, 93 }; var span = new Span<int>(a); Assert.Equal("System.Span<Int32>[3]", span.ToString()); } [Fact] public static void ToStringInt_Empty() { var span = new Span<int>(); Assert.Equal("System.Span<Int32>[0]", span.ToString()); } [Fact] public static unsafe void ToStringChar() { char[] a = { 'a', 'b', 'c' }; var span = new Span<char>(a); Assert.Equal("abc", span.ToString()); string testString = "abcdefg"; ReadOnlySpan<char> readOnlySpan = testString.AsSpan(); fixed (void* ptr = &MemoryMarshal.GetReference(readOnlySpan)) { var temp = new Span<char>(ptr, readOnlySpan.Length); Assert.Equal(testString, temp.ToString()); } } [Fact] public static void ToStringChar_Empty() { var span = new Span<char>(); Assert.Equal("", span.ToString()); } [Fact] public static void ToStringForSpanOfString() { string[] a = { "a", "b", "c" }; var span = new Span<string>(a); Assert.Equal("System.Span<String>[3]", span.ToString()); } [Fact] public static void ToStringSpanOverFullStringDoesNotReturnOriginal() { string original = TestHelpers.BuildString(10, 42); ReadOnlyMemory<char> readOnlyMemory = original.AsMemory(); Memory<char> memory = MemoryMarshal.AsMemory(readOnlyMemory); Span<char> span = memory.Span; string returnedString = span.ToString(); string returnedStringUsingSlice = span.Slice(0, original.Length).ToString(); string subString1 = span.Slice(1).ToString(); string subString2 = span.Slice(0, 2).ToString(); string subString3 = span.Slice(1, 2).ToString(); Assert.Equal(original, returnedString); Assert.Equal(original, returnedStringUsingSlice); Assert.Equal(original.Substring(1), subString1); Assert.Equal(original.Substring(0, 2), subString2); Assert.Equal(original.Substring(1, 2), subString3); Assert.NotSame(original, returnedString); Assert.NotSame(original, returnedStringUsingSlice); Assert.NotSame(original, subString1); Assert.NotSame(original, subString2); Assert.NotSame(original, subString3); Assert.NotSame(subString1, subString2); Assert.NotSame(subString1, subString3); Assert.NotSame(subString2, subString3); } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ShiftRightArithmeticRoundedAdd.Vector64.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 ShiftRightArithmeticRoundedAdd_Vector64_SByte_1() { var test = new ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_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 ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_SByte_1 { 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, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); 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(ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_SByte_1 testClass) { var result = AdvSimd.ShiftRightArithmeticRoundedAdd(_fld1, _fld2, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_SByte_1 testClass) { fixed (Vector64<SByte>* pFld1 = &_fld1) fixed (Vector64<SByte>* pFld2 = &_fld2) { var result = AdvSimd.ShiftRightArithmeticRoundedAdd( AdvSimd.LoadVector64((SByte*)(pFld1)), AdvSimd.LoadVector64((SByte*)(pFld2)), 1 ); 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<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static readonly byte Imm = 1; 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 ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_SByte_1() { 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 ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_SByte_1() { 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 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.ShiftRightArithmeticRoundedAdd( Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr), 1 ); 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.ShiftRightArithmeticRoundedAdd( AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)), 1 ); 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.ShiftRightArithmeticRoundedAdd), new Type[] { typeof(Vector64<SByte>), typeof(Vector64<SByte>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(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.ShiftRightArithmeticRoundedAdd), new Type[] { typeof(Vector64<SByte>), typeof(Vector64<SByte>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftRightArithmeticRoundedAdd( _clsVar1, _clsVar2, 1 ); 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.ShiftRightArithmeticRoundedAdd( AdvSimd.LoadVector64((SByte*)(pClsVar1)), AdvSimd.LoadVector64((SByte*)(pClsVar2)), 1 ); 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.ShiftRightArithmeticRoundedAdd(op1, op2, 1); 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.ShiftRightArithmeticRoundedAdd(op1, op2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_SByte_1(); var result = AdvSimd.ShiftRightArithmeticRoundedAdd(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_SByte_1(); fixed (Vector64<SByte>* pFld1 = &test._fld1) fixed (Vector64<SByte>* pFld2 = &test._fld2) { var result = AdvSimd.ShiftRightArithmeticRoundedAdd( AdvSimd.LoadVector64((SByte*)(pFld1)), AdvSimd.LoadVector64((SByte*)(pFld2)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftRightArithmeticRoundedAdd(_fld1, _fld2, 1); 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.ShiftRightArithmeticRoundedAdd( AdvSimd.LoadVector64((SByte*)(pFld1)), AdvSimd.LoadVector64((SByte*)(pFld2)), 1 ); 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.ShiftRightArithmeticRoundedAdd(test._fld1, test._fld2, 1); 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.ShiftRightArithmeticRoundedAdd( AdvSimd.LoadVector64((SByte*)(&test._fld1)), AdvSimd.LoadVector64((SByte*)(&test._fld2)), 1 ); 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> firstOp, Vector64<SByte> secondOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), firstOp); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), secondOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector64<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] firstOp, SByte[] secondOp, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftRightArithmeticRoundedAdd(firstOp[i], secondOp[i], Imm) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftRightArithmeticRoundedAdd)}<SByte>(Vector64<SByte>, Vector64<SByte>, 1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftRightArithmeticRoundedAdd_Vector64_SByte_1() { var test = new ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_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 ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_SByte_1 { 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, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); 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(ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_SByte_1 testClass) { var result = AdvSimd.ShiftRightArithmeticRoundedAdd(_fld1, _fld2, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_SByte_1 testClass) { fixed (Vector64<SByte>* pFld1 = &_fld1) fixed (Vector64<SByte>* pFld2 = &_fld2) { var result = AdvSimd.ShiftRightArithmeticRoundedAdd( AdvSimd.LoadVector64((SByte*)(pFld1)), AdvSimd.LoadVector64((SByte*)(pFld2)), 1 ); 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<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte); private static readonly byte Imm = 1; 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 ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_SByte_1() { 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 ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_SByte_1() { 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 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.ShiftRightArithmeticRoundedAdd( Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr), 1 ); 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.ShiftRightArithmeticRoundedAdd( AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)), 1 ); 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.ShiftRightArithmeticRoundedAdd), new Type[] { typeof(Vector64<SByte>), typeof(Vector64<SByte>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(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.ShiftRightArithmeticRoundedAdd), new Type[] { typeof(Vector64<SByte>), typeof(Vector64<SByte>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftRightArithmeticRoundedAdd( _clsVar1, _clsVar2, 1 ); 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.ShiftRightArithmeticRoundedAdd( AdvSimd.LoadVector64((SByte*)(pClsVar1)), AdvSimd.LoadVector64((SByte*)(pClsVar2)), 1 ); 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.ShiftRightArithmeticRoundedAdd(op1, op2, 1); 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.ShiftRightArithmeticRoundedAdd(op1, op2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_SByte_1(); var result = AdvSimd.ShiftRightArithmeticRoundedAdd(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmBinaryOpTest__ShiftRightArithmeticRoundedAdd_Vector64_SByte_1(); fixed (Vector64<SByte>* pFld1 = &test._fld1) fixed (Vector64<SByte>* pFld2 = &test._fld2) { var result = AdvSimd.ShiftRightArithmeticRoundedAdd( AdvSimd.LoadVector64((SByte*)(pFld1)), AdvSimd.LoadVector64((SByte*)(pFld2)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftRightArithmeticRoundedAdd(_fld1, _fld2, 1); 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.ShiftRightArithmeticRoundedAdd( AdvSimd.LoadVector64((SByte*)(pFld1)), AdvSimd.LoadVector64((SByte*)(pFld2)), 1 ); 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.ShiftRightArithmeticRoundedAdd(test._fld1, test._fld2, 1); 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.ShiftRightArithmeticRoundedAdd( AdvSimd.LoadVector64((SByte*)(&test._fld1)), AdvSimd.LoadVector64((SByte*)(&test._fld2)), 1 ); 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> firstOp, Vector64<SByte> secondOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), firstOp); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), secondOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector64<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] firstOp, SByte[] secondOp, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftRightArithmeticRoundedAdd(firstOp[i], secondOp[i], Imm) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftRightArithmeticRoundedAdd)}<SByte>(Vector64<SByte>, Vector64<SByte>, 1): {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
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/Microsoft.Bcl.AsyncInterfaces/src/System/Runtime/CompilerServices/AsyncIteratorMethodBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // NOTE: This is a copy of // https://github.com/dotnet/coreclr/blame/07b3afc27304800f00975c8fd4836b319aaa8820/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncIteratorMethodBuilder.cs // modified to be compilable against .NET Standard 2.0. Key differences: // - Uses the wrapped AsyncTaskMethodBuilder for Create and MoveNext. // - Uses a custom object for the debugger identity. // - Nullable annotations removed. using System.Runtime.InteropServices; using System.Threading; namespace System.Runtime.CompilerServices { /// <summary>Represents a builder for asynchronous iterators.</summary> [StructLayout(LayoutKind.Auto)] public struct AsyncIteratorMethodBuilder { private AsyncTaskMethodBuilder _methodBuilder; // mutable struct; do not make it readonly private object _id; /// <summary>Creates an instance of the <see cref="AsyncIteratorMethodBuilder"/> struct.</summary> /// <returns>The initialized instance.</returns> public static AsyncIteratorMethodBuilder Create() => new AsyncIteratorMethodBuilder() { _methodBuilder = AsyncTaskMethodBuilder.Create() }; /// <summary>Invokes <see cref="IAsyncStateMachine.MoveNext"/> on the state machine while guarding the <see cref="ExecutionContext"/>.</summary> /// <typeparam name="TStateMachine">The type of the state machine.</typeparam> /// <param name="stateMachine">The state machine instance, passed by reference.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void MoveNext<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine => _methodBuilder.Start(ref stateMachine); /// <summary>Schedules the state machine to proceed to the next action when the specified awaiter completes.</summary> /// <typeparam name="TAwaiter">The type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">The type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine => _methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine); /// <summary>Schedules the state machine to proceed to the next action when the specified awaiter completes.</summary> /// <typeparam name="TAwaiter">The type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">The type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine => _methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); /// <summary>Marks iteration as being completed, whether successfully or otherwise.</summary> public void Complete() => _methodBuilder.SetResult(); /// <summary>Gets an object that may be used to uniquely identify this builder to the debugger.</summary> internal object ObjectIdForDebugger => _id ?? Interlocked.CompareExchange(ref _id, new object(), null) ?? _id; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // NOTE: This is a copy of // https://github.com/dotnet/coreclr/blame/07b3afc27304800f00975c8fd4836b319aaa8820/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncIteratorMethodBuilder.cs // modified to be compilable against .NET Standard 2.0. Key differences: // - Uses the wrapped AsyncTaskMethodBuilder for Create and MoveNext. // - Uses a custom object for the debugger identity. // - Nullable annotations removed. using System.Runtime.InteropServices; using System.Threading; namespace System.Runtime.CompilerServices { /// <summary>Represents a builder for asynchronous iterators.</summary> [StructLayout(LayoutKind.Auto)] public struct AsyncIteratorMethodBuilder { private AsyncTaskMethodBuilder _methodBuilder; // mutable struct; do not make it readonly private object _id; /// <summary>Creates an instance of the <see cref="AsyncIteratorMethodBuilder"/> struct.</summary> /// <returns>The initialized instance.</returns> public static AsyncIteratorMethodBuilder Create() => new AsyncIteratorMethodBuilder() { _methodBuilder = AsyncTaskMethodBuilder.Create() }; /// <summary>Invokes <see cref="IAsyncStateMachine.MoveNext"/> on the state machine while guarding the <see cref="ExecutionContext"/>.</summary> /// <typeparam name="TStateMachine">The type of the state machine.</typeparam> /// <param name="stateMachine">The state machine instance, passed by reference.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void MoveNext<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine => _methodBuilder.Start(ref stateMachine); /// <summary>Schedules the state machine to proceed to the next action when the specified awaiter completes.</summary> /// <typeparam name="TAwaiter">The type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">The type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine => _methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine); /// <summary>Schedules the state machine to proceed to the next action when the specified awaiter completes.</summary> /// <typeparam name="TAwaiter">The type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">The type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine => _methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); /// <summary>Marks iteration as being completed, whether successfully or otherwise.</summary> public void Complete() => _methodBuilder.SetResult(); /// <summary>Gets an object that may be used to uniquely identify this builder to the debugger.</summary> internal object ObjectIdForDebugger => _id ?? Interlocked.CompareExchange(ref _id, new object(), null) ?? _id; } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Speech/src/Synthesis/VoiceInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Speech.AudioFormat; using System.Speech.Internal; using System.Speech.Internal.ObjectTokens; using System.Speech.Internal.Synthesis; namespace System.Speech.Synthesis { [DebuggerDisplay("{(_name != null ? \"'\" + _name + \"' \" : \"\") + (_culture != null ? \" '\" + _culture.ToString () + \"' \" : \"\") + (_gender != VoiceGender.NotSet ? \" '\" + _gender.ToString () + \"' \" : \"\") + (_age != VoiceAge.NotSet ? \" '\" + _age.ToString () + \"' \" : \"\") + (_variant > 0 ? \" \" + _variant.ToString () : \"\")}")] [Serializable] public class VoiceInfo { #region Constructors internal VoiceInfo(string name) { Helpers.ThrowIfEmptyOrNull(name, nameof(name)); _name = name; } internal VoiceInfo(CultureInfo culture) { // Fails if no culture is provided Helpers.ThrowIfNull(culture, nameof(culture)); if (culture.Equals(CultureInfo.InvariantCulture)) { throw new ArgumentException(SR.Get(SRID.InvariantCultureInfo), nameof(culture)); } _culture = culture; } internal VoiceInfo(ObjectToken token) { _registryKeyPath = token._sKeyId; // Retrieve the token name _id = token.Name; // Retrieve default display name _description = token.Description; // Get other attributes _name = token.TokenName(); SsmlParserHelpers.TryConvertAge(token.Age.ToLowerInvariant(), out _age); SsmlParserHelpers.TryConvertGender(token.Gender.ToLowerInvariant(), out _gender); string langId; if (token.Attributes.TryGetString("Language", out langId)) { _culture = SapiAttributeParser.GetCultureInfoFromLanguageString(langId); } string assemblyName; if (token.TryGetString("Assembly", out assemblyName)) { _assemblyName = assemblyName; } string clsid; if (token.TryGetString("CLSID", out clsid)) { _clsid = clsid; } if (token.Attributes != null) { // Enum all values and add to custom table Dictionary<string, string> attrs = new(); foreach (string keyName in token.Attributes.GetValueNames()) { string attributeValue; if (token.Attributes.TryGetString(keyName, out attributeValue)) { attrs.Add(keyName, attributeValue); } } _attributes = new ReadOnlyDictionary<string, string>(attrs); } string audioFormats; if (token.Attributes != null && token.Attributes.TryGetString("AudioFormats", out audioFormats)) { _audioFormats = new ReadOnlyCollection<SpeechAudioFormatInfo>(SapiAttributeParser.GetAudioFormatsFromString(audioFormats)); } else { _audioFormats = new ReadOnlyCollection<SpeechAudioFormatInfo>(new List<SpeechAudioFormatInfo>()); } } internal VoiceInfo(VoiceGender gender) { _gender = gender; } internal VoiceInfo(VoiceGender gender, VoiceAge age) { _gender = gender; _age = age; } internal VoiceInfo(VoiceGender gender, VoiceAge age, int voiceAlternate) { if (voiceAlternate < 0) { throw new ArgumentOutOfRangeException(nameof(voiceAlternate), SR.Get(SRID.PromptBuilderInvalidVariant)); } _gender = gender; _age = age; _variant = voiceAlternate + 1; } #endregion #region public Methods /// <summary> /// Tests whether two AutomationIdentifier objects are equivalent /// </summary> public override bool Equals(object obj) { #pragma warning disable 6506 VoiceInfo voice = obj as VoiceInfo; return voice != null && _name == voice._name && (_age == voice._age || _age == VoiceAge.NotSet || voice._age == VoiceAge.NotSet) && (_gender == voice._gender || _gender == VoiceGender.NotSet || voice._gender == VoiceGender.NotSet) && (_culture == null || voice._culture == null || _culture.Equals(voice._culture)); #pragma warning restore 6506 } /// <summary> /// Overrides Object.GetHashCode() /// </summary> public override int GetHashCode() { return _name.GetHashCode(); } #endregion #region public Properties public VoiceGender Gender { get { return _gender; } } public VoiceAge Age { get { return _age; } } public string Name { get { return _name; } } /// <summary> /// /// Return a copy of the internal Language set. This disable client /// applications to modify the internal languages list. /// </summary> public CultureInfo Culture { get { return _culture; } } public string Id { get { return _id; } } public string Description { get { return _description != null ? _description : string.Empty; } } [EditorBrowsable(EditorBrowsableState.Advanced)] public ReadOnlyCollection<SpeechAudioFormatInfo> SupportedAudioFormats { get { return _audioFormats; } } [EditorBrowsable(EditorBrowsableState.Advanced)] public IDictionary<string, string> AdditionalInfo { get { if (_attributes == null) _attributes = new ReadOnlyDictionary<string, string>(new Dictionary<string, string>(0)); return _attributes; } } #endregion #region Internal Methods internal static bool ValidateGender(VoiceGender gender) { return gender == VoiceGender.Female || gender == VoiceGender.Male || gender == VoiceGender.Neutral || gender == VoiceGender.NotSet; } internal static bool ValidateAge(VoiceAge age) { return age == VoiceAge.Adult || age == VoiceAge.Child || age == VoiceAge.NotSet || age == VoiceAge.Senior || age == VoiceAge.Teen; } #endregion #region Internal Property internal int Variant { get { return _variant; } } internal string AssemblyName { get { return _assemblyName; } } internal string Clsid { get { return _clsid; } } internal string RegistryKeyPath { get { return _registryKeyPath; } } #endregion #region Private Fields private string _name; private CultureInfo _culture; private VoiceGender _gender; private VoiceAge _age; private int _variant = -1; [NonSerialized] private string _id; [NonSerialized] private string _registryKeyPath; [NonSerialized] private string _assemblyName; [NonSerialized] private string _clsid; [NonSerialized] private string _description; [NonSerialized] private ReadOnlyDictionary<string, string> _attributes; [NonSerialized] private ReadOnlyCollection<SpeechAudioFormatInfo> _audioFormats; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Speech.AudioFormat; using System.Speech.Internal; using System.Speech.Internal.ObjectTokens; using System.Speech.Internal.Synthesis; namespace System.Speech.Synthesis { [DebuggerDisplay("{(_name != null ? \"'\" + _name + \"' \" : \"\") + (_culture != null ? \" '\" + _culture.ToString () + \"' \" : \"\") + (_gender != VoiceGender.NotSet ? \" '\" + _gender.ToString () + \"' \" : \"\") + (_age != VoiceAge.NotSet ? \" '\" + _age.ToString () + \"' \" : \"\") + (_variant > 0 ? \" \" + _variant.ToString () : \"\")}")] [Serializable] public class VoiceInfo { #region Constructors internal VoiceInfo(string name) { Helpers.ThrowIfEmptyOrNull(name, nameof(name)); _name = name; } internal VoiceInfo(CultureInfo culture) { // Fails if no culture is provided Helpers.ThrowIfNull(culture, nameof(culture)); if (culture.Equals(CultureInfo.InvariantCulture)) { throw new ArgumentException(SR.Get(SRID.InvariantCultureInfo), nameof(culture)); } _culture = culture; } internal VoiceInfo(ObjectToken token) { _registryKeyPath = token._sKeyId; // Retrieve the token name _id = token.Name; // Retrieve default display name _description = token.Description; // Get other attributes _name = token.TokenName(); SsmlParserHelpers.TryConvertAge(token.Age.ToLowerInvariant(), out _age); SsmlParserHelpers.TryConvertGender(token.Gender.ToLowerInvariant(), out _gender); string langId; if (token.Attributes.TryGetString("Language", out langId)) { _culture = SapiAttributeParser.GetCultureInfoFromLanguageString(langId); } string assemblyName; if (token.TryGetString("Assembly", out assemblyName)) { _assemblyName = assemblyName; } string clsid; if (token.TryGetString("CLSID", out clsid)) { _clsid = clsid; } if (token.Attributes != null) { // Enum all values and add to custom table Dictionary<string, string> attrs = new(); foreach (string keyName in token.Attributes.GetValueNames()) { string attributeValue; if (token.Attributes.TryGetString(keyName, out attributeValue)) { attrs.Add(keyName, attributeValue); } } _attributes = new ReadOnlyDictionary<string, string>(attrs); } string audioFormats; if (token.Attributes != null && token.Attributes.TryGetString("AudioFormats", out audioFormats)) { _audioFormats = new ReadOnlyCollection<SpeechAudioFormatInfo>(SapiAttributeParser.GetAudioFormatsFromString(audioFormats)); } else { _audioFormats = new ReadOnlyCollection<SpeechAudioFormatInfo>(new List<SpeechAudioFormatInfo>()); } } internal VoiceInfo(VoiceGender gender) { _gender = gender; } internal VoiceInfo(VoiceGender gender, VoiceAge age) { _gender = gender; _age = age; } internal VoiceInfo(VoiceGender gender, VoiceAge age, int voiceAlternate) { if (voiceAlternate < 0) { throw new ArgumentOutOfRangeException(nameof(voiceAlternate), SR.Get(SRID.PromptBuilderInvalidVariant)); } _gender = gender; _age = age; _variant = voiceAlternate + 1; } #endregion #region public Methods /// <summary> /// Tests whether two AutomationIdentifier objects are equivalent /// </summary> public override bool Equals(object obj) { #pragma warning disable 6506 VoiceInfo voice = obj as VoiceInfo; return voice != null && _name == voice._name && (_age == voice._age || _age == VoiceAge.NotSet || voice._age == VoiceAge.NotSet) && (_gender == voice._gender || _gender == VoiceGender.NotSet || voice._gender == VoiceGender.NotSet) && (_culture == null || voice._culture == null || _culture.Equals(voice._culture)); #pragma warning restore 6506 } /// <summary> /// Overrides Object.GetHashCode() /// </summary> public override int GetHashCode() { return _name.GetHashCode(); } #endregion #region public Properties public VoiceGender Gender { get { return _gender; } } public VoiceAge Age { get { return _age; } } public string Name { get { return _name; } } /// <summary> /// /// Return a copy of the internal Language set. This disable client /// applications to modify the internal languages list. /// </summary> public CultureInfo Culture { get { return _culture; } } public string Id { get { return _id; } } public string Description { get { return _description != null ? _description : string.Empty; } } [EditorBrowsable(EditorBrowsableState.Advanced)] public ReadOnlyCollection<SpeechAudioFormatInfo> SupportedAudioFormats { get { return _audioFormats; } } [EditorBrowsable(EditorBrowsableState.Advanced)] public IDictionary<string, string> AdditionalInfo { get { if (_attributes == null) _attributes = new ReadOnlyDictionary<string, string>(new Dictionary<string, string>(0)); return _attributes; } } #endregion #region Internal Methods internal static bool ValidateGender(VoiceGender gender) { return gender == VoiceGender.Female || gender == VoiceGender.Male || gender == VoiceGender.Neutral || gender == VoiceGender.NotSet; } internal static bool ValidateAge(VoiceAge age) { return age == VoiceAge.Adult || age == VoiceAge.Child || age == VoiceAge.NotSet || age == VoiceAge.Senior || age == VoiceAge.Teen; } #endregion #region Internal Property internal int Variant { get { return _variant; } } internal string AssemblyName { get { return _assemblyName; } } internal string Clsid { get { return _clsid; } } internal string RegistryKeyPath { get { return _registryKeyPath; } } #endregion #region Private Fields private string _name; private CultureInfo _culture; private VoiceGender _gender; private VoiceAge _age; private int _variant = -1; [NonSerialized] private string _id; [NonSerialized] private string _registryKeyPath; [NonSerialized] private string _assemblyName; [NonSerialized] private string _clsid; [NonSerialized] private string _description; [NonSerialized] private ReadOnlyDictionary<string, string> _attributes; [NonSerialized] private ReadOnlyCollection<SpeechAudioFormatInfo> _audioFormats; #endregion } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/jit64/valuetypes/nullable/castclass/interface/castclass-interface011.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // <Area> Nullable - CastClass </Area> // <Title> Nullable type with castclass expr </Title> // <Description> // checking type of ushort using cast expr // </Description> // <RelatedBugs> </RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQ(object o) { return Helper.Compare((ushort)(IComparable)o, Helper.Create(default(ushort))); } private static bool BoxUnboxToQ(object o) { return Helper.Compare((ushort?)(IComparable)o, Helper.Create(default(ushort))); } private static int Main() { ushort? s = Helper.Create(default(ushort)); if (BoxUnboxToNQ(s) && BoxUnboxToQ(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // <Area> Nullable - CastClass </Area> // <Title> Nullable type with castclass expr </Title> // <Description> // checking type of ushort using cast expr // </Description> // <RelatedBugs> </RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQ(object o) { return Helper.Compare((ushort)(IComparable)o, Helper.Create(default(ushort))); } private static bool BoxUnboxToQ(object o) { return Helper.Compare((ushort?)(IComparable)o, Helper.Create(default(ushort))); } private static int Main() { ushort? s = Helper.Create(default(ushort)); if (BoxUnboxToNQ(s) && BoxUnboxToQ(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/HardwareIntrinsics/X86/Pclmulqdq/Pclmulqdq_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup> <DebugType>Embedded</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="CarrylessMultiply.Int64.0.cs" /> <Compile Include="CarrylessMultiply.Int64.1.cs" /> <Compile Include="CarrylessMultiply.Int64.16.cs" /> <Compile Include="CarrylessMultiply.Int64.17.cs" /> <Compile Include="CarrylessMultiply.Int64.129.cs" /> <Compile Include="CarrylessMultiply.UInt64.0.cs" /> <Compile Include="CarrylessMultiply.UInt64.1.cs" /> <Compile Include="CarrylessMultiply.UInt64.16.cs" /> <Compile Include="CarrylessMultiply.UInt64.17.cs" /> <Compile Include="CarrylessMultiply.UInt64.129.cs" /> <Compile Include="Program.Pclmulqdq.cs" /> <Compile Include="..\Shared\Program.cs" /> <Compile Include="..\Shared\SimpleBinOpTest_DataTable.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup> <DebugType>Embedded</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="CarrylessMultiply.Int64.0.cs" /> <Compile Include="CarrylessMultiply.Int64.1.cs" /> <Compile Include="CarrylessMultiply.Int64.16.cs" /> <Compile Include="CarrylessMultiply.Int64.17.cs" /> <Compile Include="CarrylessMultiply.Int64.129.cs" /> <Compile Include="CarrylessMultiply.UInt64.0.cs" /> <Compile Include="CarrylessMultiply.UInt64.1.cs" /> <Compile Include="CarrylessMultiply.UInt64.16.cs" /> <Compile Include="CarrylessMultiply.UInt64.17.cs" /> <Compile Include="CarrylessMultiply.UInt64.129.cs" /> <Compile Include="Program.Pclmulqdq.cs" /> <Compile Include="..\Shared\Program.cs" /> <Compile Include="..\Shared\SimpleBinOpTest_DataTable.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/GC/API/GCHandle/Normal.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestExecutionArguments /> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="Normal.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestExecutionArguments /> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="Normal.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Private.CoreLib/src/System/Range.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.Runtime.CompilerServices; #if NETSTANDARD2_0 || NETFRAMEWORK using System.Numerics.Hashing; #endif namespace System { /// <summary>Represent a range has start and end indexes.</summary> /// <remarks> /// Range is used by the C# compiler to support the range syntax. /// <code> /// int[] someArray = new int[5] { 1, 2, 3, 4, 5 }; /// int[] subArray1 = someArray[0..2]; // { 1, 2 } /// int[] subArray2 = someArray[1..^0]; // { 2, 3, 4, 5 } /// </code> /// </remarks> public readonly struct Range : IEquatable<Range> { /// <summary>Represent the inclusive start index of the Range.</summary> public Index Start { get; } /// <summary>Represent the exclusive end index of the Range.</summary> public Index End { get; } /// <summary>Construct a Range object using the start and end indexes.</summary> /// <param name="start">Represent the inclusive start index of the range.</param> /// <param name="end">Represent the exclusive end index of the range.</param> public Range(Index start, Index end) { Start = start; End = end; } /// <summary>Indicates whether the current Range object is equal to another object of the same type.</summary> /// <param name="value">An object to compare with this object</param> public override bool Equals([NotNullWhen(true)] object? value) => value is Range r && r.Start.Equals(Start) && r.End.Equals(End); /// <summary>Indicates whether the current Range object is equal to another Range object.</summary> /// <param name="other">An object to compare with this object</param> public bool Equals(Range other) => other.Start.Equals(Start) && other.End.Equals(End); /// <summary>Returns the hash code for this instance.</summary> public override int GetHashCode() { #if (!NETSTANDARD2_0 && !NETFRAMEWORK) return HashCode.Combine(Start.GetHashCode(), End.GetHashCode()); #else return HashHelpers.Combine(Start.GetHashCode(), End.GetHashCode()); #endif } /// <summary>Converts the value of the current Range object to its equivalent string representation.</summary> public override string ToString() { #if (!NETSTANDARD2_0 && !NETFRAMEWORK) Span<char> span = stackalloc char[2 + (2 * 11)]; // 2 for "..", then for each index 1 for '^' and 10 for longest possible uint int pos = 0; if (Start.IsFromEnd) { span[0] = '^'; pos = 1; } bool formatted = ((uint)Start.Value).TryFormat(span.Slice(pos), out int charsWritten); Debug.Assert(formatted); pos += charsWritten; span[pos++] = '.'; span[pos++] = '.'; if (End.IsFromEnd) { span[pos++] = '^'; } formatted = ((uint)End.Value).TryFormat(span.Slice(pos), out charsWritten); Debug.Assert(formatted); pos += charsWritten; return new string(span.Slice(0, pos)); #else return Start.ToString() + ".." + End.ToString(); #endif } /// <summary>Create a Range object starting from start index to the end of the collection.</summary> public static Range StartAt(Index start) => new Range(start, Index.End); /// <summary>Create a Range object starting from first element in the collection to the end Index.</summary> public static Range EndAt(Index end) => new Range(Index.Start, end); /// <summary>Create a Range object starting from first element to the end.</summary> public static Range All => new Range(Index.Start, Index.End); /// <summary>Calculate the start offset and length of range object using a collection length.</summary> /// <param name="length">The length of the collection that the range will be used with. length has to be a positive value.</param> /// <remarks> /// For performance reason, we don't validate the input length parameter against negative values. /// It is expected Range will be used with collections which always have non negative length/count. /// We validate the range is inside the length scope though. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public (int Offset, int Length) GetOffsetAndLength(int length) { int start; Index startIndex = Start; if (startIndex.IsFromEnd) start = length - startIndex.Value; else start = startIndex.Value; int end; Index endIndex = End; if (endIndex.IsFromEnd) end = length - endIndex.Value; else end = endIndex.Value; if ((uint)end > (uint)length || (uint)start > (uint)end) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); } return (start, end - start); } } }
// 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.Runtime.CompilerServices; #if NETSTANDARD2_0 || NETFRAMEWORK using System.Numerics.Hashing; #endif namespace System { /// <summary>Represent a range has start and end indexes.</summary> /// <remarks> /// Range is used by the C# compiler to support the range syntax. /// <code> /// int[] someArray = new int[5] { 1, 2, 3, 4, 5 }; /// int[] subArray1 = someArray[0..2]; // { 1, 2 } /// int[] subArray2 = someArray[1..^0]; // { 2, 3, 4, 5 } /// </code> /// </remarks> public readonly struct Range : IEquatable<Range> { /// <summary>Represent the inclusive start index of the Range.</summary> public Index Start { get; } /// <summary>Represent the exclusive end index of the Range.</summary> public Index End { get; } /// <summary>Construct a Range object using the start and end indexes.</summary> /// <param name="start">Represent the inclusive start index of the range.</param> /// <param name="end">Represent the exclusive end index of the range.</param> public Range(Index start, Index end) { Start = start; End = end; } /// <summary>Indicates whether the current Range object is equal to another object of the same type.</summary> /// <param name="value">An object to compare with this object</param> public override bool Equals([NotNullWhen(true)] object? value) => value is Range r && r.Start.Equals(Start) && r.End.Equals(End); /// <summary>Indicates whether the current Range object is equal to another Range object.</summary> /// <param name="other">An object to compare with this object</param> public bool Equals(Range other) => other.Start.Equals(Start) && other.End.Equals(End); /// <summary>Returns the hash code for this instance.</summary> public override int GetHashCode() { #if (!NETSTANDARD2_0 && !NETFRAMEWORK) return HashCode.Combine(Start.GetHashCode(), End.GetHashCode()); #else return HashHelpers.Combine(Start.GetHashCode(), End.GetHashCode()); #endif } /// <summary>Converts the value of the current Range object to its equivalent string representation.</summary> public override string ToString() { #if (!NETSTANDARD2_0 && !NETFRAMEWORK) Span<char> span = stackalloc char[2 + (2 * 11)]; // 2 for "..", then for each index 1 for '^' and 10 for longest possible uint int pos = 0; if (Start.IsFromEnd) { span[0] = '^'; pos = 1; } bool formatted = ((uint)Start.Value).TryFormat(span.Slice(pos), out int charsWritten); Debug.Assert(formatted); pos += charsWritten; span[pos++] = '.'; span[pos++] = '.'; if (End.IsFromEnd) { span[pos++] = '^'; } formatted = ((uint)End.Value).TryFormat(span.Slice(pos), out charsWritten); Debug.Assert(formatted); pos += charsWritten; return new string(span.Slice(0, pos)); #else return Start.ToString() + ".." + End.ToString(); #endif } /// <summary>Create a Range object starting from start index to the end of the collection.</summary> public static Range StartAt(Index start) => new Range(start, Index.End); /// <summary>Create a Range object starting from first element in the collection to the end Index.</summary> public static Range EndAt(Index end) => new Range(Index.Start, end); /// <summary>Create a Range object starting from first element to the end.</summary> public static Range All => new Range(Index.Start, Index.End); /// <summary>Calculate the start offset and length of range object using a collection length.</summary> /// <param name="length">The length of the collection that the range will be used with. length has to be a positive value.</param> /// <remarks> /// For performance reason, we don't validate the input length parameter against negative values. /// It is expected Range will be used with collections which always have non negative length/count. /// We validate the range is inside the length scope though. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public (int Offset, int Length) GetOffsetAndLength(int length) { int start; Index startIndex = Start; if (startIndex.IsFromEnd) start = length - startIndex.Value; else start = startIndex.Value; int end; Index endIndex = End; if (endIndex.IsFromEnd) end = length - endIndex.Value; else end = endIndex.Value; if ((uint)end > (uint)length || (uint)start > (uint)end) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); } return (start, end - start); } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/Performance/CodeQuality/Bytemark/nnet.dat
5 7 8 26 0 0 1 0 0 0 1 0 1 0 1 0 0 0 1 1 0 0 0 1 1 1 1 1 1 1 0 0 0 1 1 0 0 0 1 0 1 0 0 0 0 0 1 1 1 1 1 0 1 0 0 0 1 1 0 0 0 1 1 1 1 1 0 1 0 0 0 1 1 0 0 0 1 1 1 1 1 0 0 1 0 0 0 0 1 0 0 1 1 1 0 1 0 0 0 1 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 0 1 1 1 0 0 1 0 0 0 0 1 1 1 1 1 1 0 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 1 1 1 0 0 1 0 0 0 1 0 0 1 1 1 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 1 0 0 0 0 1 0 0 0 0 1 1 1 1 1 0 1 0 0 0 1 0 1 1 1 1 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 1 1 0 0 1 1 1 0 1 0 0 0 1 1 0 0 0 0 1 0 0 0 0 1 0 0 1 1 1 0 0 0 1 0 1 1 1 0 0 1 0 0 0 1 1 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 1 1 1 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 0 1 0 0 1 0 0 0 0 1 1 1 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 1 1 0 0 1 0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0 1 1 0 0 0 1 0 1 1 1 0 0 1 0 0 1 0 1 0 1 0 0 0 1 1 0 0 1 0 1 0 1 0 0 1 1 0 0 0 1 0 1 0 0 1 0 0 1 0 1 0 0 0 1 0 1 0 0 1 0 1 1 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1 1 1 1 0 1 0 0 1 1 0 0 1 0 0 0 1 1 1 0 1 1 1 0 1 0 1 1 0 1 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 0 1 0 0 1 1 0 1 1 0 0 0 1 1 1 0 0 1 1 0 1 0 1 1 0 1 0 1 1 0 1 0 1 1 0 0 1 1 1 0 0 0 1 0 1 0 0 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 0 1 1 1 0 0 1 0 0 1 1 1 1 1 1 1 1 0 1 0 0 0 1 1 0 0 0 1 1 1 1 1 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 1 1 1 0 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 1 0 1 1 0 0 1 1 0 1 1 1 1 0 1 0 1 0 0 0 1 1 1 1 1 0 1 0 0 0 1 1 0 0 0 1 1 1 1 1 0 1 0 1 0 0 1 0 0 1 0 1 0 0 0 1 0 1 0 1 0 0 1 0 0 1 1 1 1 1 0 0 0 0 1 0 0 0 0 0 1 1 1 0 0 0 0 0 1 0 0 0 0 1 1 1 1 1 0 0 1 0 1 0 0 1 1 1 1 1 1 1 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 0 1 0 1 0 0 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 0 1 1 1 0 0 1 0 1 0 1 0 1 1 0 0 0 1 1 0 0 0 1 0 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0 0 1 0 0 0 1 0 1 0 1 1 0 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 1 0 1 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 1 0 1 1 1 1 0 0 0 1 0 1 0 1 0 0 1 0 1 0 0 0 1 0 0 0 1 0 1 0 0 1 0 1 0 1 0 0 0 1 0 1 0 1 1 0 0 0 1 0 0 0 1 0 1 0 1 0 0 1 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 0 1 1 0 0 1 1 1 1 1 1 0 0 0 1 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 1 1 1 1 1 0 1 0 1 1 0 1 0
5 7 8 26 0 0 1 0 0 0 1 0 1 0 1 0 0 0 1 1 0 0 0 1 1 1 1 1 1 1 0 0 0 1 1 0 0 0 1 0 1 0 0 0 0 0 1 1 1 1 1 0 1 0 0 0 1 1 0 0 0 1 1 1 1 1 0 1 0 0 0 1 1 0 0 0 1 1 1 1 1 0 0 1 0 0 0 0 1 0 0 1 1 1 0 1 0 0 0 1 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 0 1 1 1 0 0 1 0 0 0 0 1 1 1 1 1 1 0 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 1 1 1 0 0 1 0 0 0 1 0 0 1 1 1 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 1 0 0 0 0 1 0 0 0 0 1 1 1 1 1 0 1 0 0 0 1 0 1 1 1 1 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 1 1 0 0 1 1 1 0 1 0 0 0 1 1 0 0 0 0 1 0 0 0 0 1 0 0 1 1 1 0 0 0 1 0 1 1 1 0 0 1 0 0 0 1 1 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 1 1 1 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 0 1 0 0 1 0 0 0 0 1 1 1 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 1 1 0 0 1 0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0 1 1 0 0 0 1 0 1 1 1 0 0 1 0 0 1 0 1 0 1 0 0 0 1 1 0 0 1 0 1 0 1 0 0 1 1 0 0 0 1 0 1 0 0 1 0 0 1 0 1 0 0 0 1 0 1 0 0 1 0 1 1 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1 1 1 1 0 1 0 0 1 1 0 0 1 0 0 0 1 1 1 0 1 1 1 0 1 0 1 1 0 1 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 0 1 0 0 1 1 0 1 1 0 0 0 1 1 1 0 0 1 1 0 1 0 1 1 0 1 0 1 1 0 1 0 1 1 0 0 1 1 1 0 0 0 1 0 1 0 0 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 0 1 1 1 0 0 1 0 0 1 1 1 1 1 1 1 1 0 1 0 0 0 1 1 0 0 0 1 1 1 1 1 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 1 1 1 0 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 1 0 1 1 0 0 1 1 0 1 1 1 1 0 1 0 1 0 0 0 1 1 1 1 1 0 1 0 0 0 1 1 0 0 0 1 1 1 1 1 0 1 0 1 0 0 1 0 0 1 0 1 0 0 0 1 0 1 0 1 0 0 1 0 0 1 1 1 1 1 0 0 0 0 1 0 0 0 0 0 1 1 1 0 0 0 0 0 1 0 0 0 0 1 1 1 1 1 0 0 1 0 1 0 0 1 1 1 1 1 1 1 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 0 1 0 1 0 0 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 0 1 1 1 0 0 1 0 1 0 1 0 1 1 0 0 0 1 1 0 0 0 1 0 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0 0 1 0 0 0 1 0 1 0 1 1 0 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 1 0 1 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 1 0 1 1 1 1 0 0 0 1 0 1 0 1 0 0 1 0 1 0 0 0 1 0 0 0 1 0 1 0 0 1 0 1 0 1 0 0 0 1 0 1 0 1 1 0 0 0 1 0 0 0 1 0 1 0 1 0 0 1 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 0 1 1 0 0 1 1 1 1 1 1 0 0 0 1 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 1 1 1 1 1 0 1 0 1 1 0 1 0
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Resources/xlf/Strings.it.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="it" original="../Strings.resx"> <body> <trans-unit id="AddMissingCustomTypeMarshallerMembers"> <source>Add missing custom type marshaller members</source> <target state="translated">Aggiungi membri mancanti del gestore del marshalling di tipi personalizzato mancanti</target> <note /> </trans-unit> <trans-unit id="AddMissingFeaturesToCustomTypeMarshaller"> <source>Add missing features to the 'CustomTypeMarshallerAttribute' attribute</source> <target state="translated">Aggiungi funzionalità mancanti all'attributo 'CustomTypeMarshallerAttribute'</target> <note /> </trans-unit> <trans-unit id="CallerAllocConstructorMustHaveBufferSizeDescription"> <source>When a constructor taking a 'Span&lt;byte&gt;' is specified on the native type, the type must set the BufferSize field on the 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' to provide the size of the caller-allocated buffer.</source> <target state="translated">Quando nel tipo nativo è specificato un costruttore che accetta 'Span&lt;byte&gt;', il tipo deve impostare il campo BufferSize in 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' per fornire le dimensioni del buffer allocato dal chiamante.</target> <note /> </trans-unit> <trans-unit id="CallerAllocConstructorMustHaveBufferSizeMessage"> <source>The native type '{0}' must set the 'BufferSize' field on the applied 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' to specify the size of the caller-allocated buffer because it has a constructor that takes a caller-allocated 'Span&lt;byte&gt;'</source> <target state="translated">Il tipo nativo '{0}' deve impostare il campo 'BufferSize' nell'elemento 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' applicato per specificare le dimensioni del buffer allocato dal chiamante, perché contiene un costruttore che accetta un elemento 'Span&lt;byte&gt;' allocato dal chiamante</target> <note /> </trans-unit> <trans-unit id="CallerAllocConstructorMustHaveBufferSizeTitle"> <source>'BufferSize' should be set on 'CustomTypeMarshallerAttribute'</source> <target state="translated">'BufferSize' deve essere impostato su 'CustomTypeMarshallerAttribute'</target> <note /> </trans-unit> <trans-unit id="CallerAllocMarshallingShouldSupportAllocatingMarshallingFallbackDescription"> <source>A type that supports marshalling from managed to native using a caller-allocated buffer should also support marshalling from managed to native where using a caller-allocated buffer is impossible.</source> <target state="translated">Un tipo che supporta il marshalling da gestito a nativo tramite un buffer allocato dal chiamante deve supportare anche il marshalling da gestito a nativo in cui non è possibile usare un buffer allocato dal chiamante.</target> <note /> </trans-unit> <trans-unit id="CallerAllocMarshallingShouldSupportAllocatingMarshallingFallbackMessage"> <source>Native type '{0}' has a constructor taking a caller-allocated buffer, but does not support marshalling in scenarios where using a caller-allocated buffer is impossible</source> <target state="translated">Il tipo nativo '{0}' include un costruttore che accetta un buffer allocato dal chiamante, ma non supporta il marshalling in scenari in cui l'uso di un buffer allocato dal chiamante risulta impossibile</target> <note /> </trans-unit> <trans-unit id="CallerAllocatedBufferConstructorProvidedShouldSpecifyFeatureDescription"> <source>A marshaller type that provides a constructor taking a caller-allocated 'Span&lt;byte&gt;' should specify that it supports the 'CallerAllocatedBuffer' feature.</source> <target state="translated">Un tipo di gestore del marshalling che fornisce un costruttore che accetta un elemento 'Span&lt;byte&gt;' allocato dal chiamante deve specificare che supporta la funzionalità 'CallerAllocatedBuffer'.</target> <note /> </trans-unit> <trans-unit id="CallerAllocatedBufferConstructorProvidedShouldSpecifyFeatureMessage"> <source>The type '{0}' provides a constructor taking a caller-allocated 'Span&lt;byte&gt;' but does not specify that it supports the 'CallerAllocatedBuffer' feature. The constructor will not be used unless the feature is specified.</source> <target state="translated">Il tipo '{0}' fornisce un costruttore che accetta un elemento 'Span&lt;byte&gt;' allocato dal chiamante, ma non specifica che supporta la funzionalità 'CallerAllocatedBuffer'. Il costruttore verrà usato solo se è specificata la funzionalità.</target> <note /> </trans-unit> <trans-unit id="CannotForwardToDllImportDescription"> <source>The generated 'DllImportAttribute' will not have a value corresponding to '{0}'.</source> <target state="translated">L'elemento 'DllImportAttribute' generato non avrà un valore corrispondente a '{0}'.</target> <note /> </trans-unit> <trans-unit id="CannotForwardToDllImportMessage"> <source>'{0}' has no equivalent in 'DllImportAtttribute' and will not be forwarded</source> <target state="translated">'{0}' non ha equivalenti in 'DllImportAtttribute' e non verrà inoltrato</target> <note /> </trans-unit> <trans-unit id="CannotForwardToDllImportTitle"> <source>Specified 'LibraryImportAttribute' arguments cannot be forwarded to 'DllImportAttribute'</source> <target state="translated">Gli argomenti 'LibraryImportAttribute' specificati non possono essere inoltrati a 'DllImportAttribute'</target> <note /> </trans-unit> <trans-unit id="ConfigurationNotSupportedDescription"> <source>Source-generated P/Invokes will ignore any configuration that is not supported.</source> <target state="translated">I P/Invoke generati dall'origine ignoreranno qualsiasi configurazione non supportata.</target> <note /> </trans-unit> <trans-unit id="ConfigurationNotSupportedMessage"> <source>The '{0}' configuration is not supported by source-generated P/Invokes. If the specified configuration is required, use a regular `DllImport` instead.</source> <target state="translated">La configurazione '{0}' non è supportata dai P/Invoke generati dall'origine. Se la configurazione specificata è obbligatoria, usare un attributo `DllImport` normale.</target> <note /> </trans-unit> <trans-unit id="ConfigurationNotSupportedMessageMarshallingInfo"> <source>The specified marshalling configuration is not supported by source-generated P/Invokes. {0}.</source> <target state="translated">La configurazione di marshalling specificata non è supportata dai P/Invoke generati dall'origine. {0}.</target> <note /> </trans-unit> <trans-unit id="ConfigurationNotSupportedMessageParameter"> <source>The specified '{0}' configuration for parameter '{1}' is not supported by source-generated P/Invokes. If the specified configuration is required, use a regular `DllImport` instead.</source> <target state="translated">La configurazione '{0}' specificata per il parametro '{1}' non è supportata dai P/Invoke generati dall'origine. Se la configurazione specificata è obbligatoria, usare un attributo `DllImport` normale.</target> <note /> </trans-unit> <trans-unit id="ConfigurationNotSupportedMessageReturn"> <source>The specified '{0}' configuration for the return value of method '{1}' is not supported by source-generated P/Invokes. If the specified configuration is required, use a regular `DllImport` instead.</source> <target state="translated">La configurazione '{0}' specificata per il valore restituito del metodo '{1}' non è supportata dai P/Invoke generati dall'origine. Se la configurazione specificata è obbligatoria, usare un attributo `DllImport` normale.</target> <note /> </trans-unit> <trans-unit id="ConfigurationNotSupportedMessageValue"> <source>The specified value '{0}' for '{1}' is not supported by source-generated P/Invokes. If the specified value is required, use a regular `DllImport` instead.</source> <target state="translated">Il valore specificato '{0}' per '{1}' non è supportato da P/Invoke generati dall'origine. Se il valore specificato è obbligatorio, usare un 'DllImport' normale.</target> <note /> </trans-unit> <trans-unit id="ConfigurationNotSupportedTitle"> <source>Specified configuration is not supported by source-generated P/Invokes.</source> <target state="translated">La configurazione specificata non è supportata dai P/Invoke generati dall'origine.</target> <note /> </trans-unit> <trans-unit id="ConstantAndElementCountInfoDisallowed"> <source>Only one of 'ConstantElementCount' or 'ElementCountInfo' may be used in a 'MarshalUsingAttribute' for a given 'ElementIndirectionDepth'</source> <target state="translated">In un elemento 'MarshalUsingAttribute' per un elemento 'ElementIndirectionDepth' specificato è possibile usare solo uno dei valori 'ConstantElementCount' o 'ElementCountInfo'</target> <note /> </trans-unit> <trans-unit id="ConvertNoPreserveSigDllImportToGeneratedMayProduceInvalidCode"> <source>Automatically converting a P/Invoke with 'PreserveSig' set to 'false' to a source-generated P/Invoke may produce invalid code</source> <target state="translated">La conversione automatica di un P/Invoke con 'PreserveSig' impostato su 'false' in un P/Invoke generato dall'origine può produrre codice non valido</target> <note /> </trans-unit> <trans-unit id="ConvertToLibraryImport"> <source>Convert to 'LibraryImport'</source> <target state="translated">Converti in 'LibraryImport'</target> <note /> </trans-unit> <trans-unit id="ConvertToLibraryImportDescription"> <source>Use 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time</source> <target state="translated">Usare 'LibraryImportAttribute' invece di 'DllImportAttribute' per generare codice di marshalling di P/Invoke in fase di compilazione</target> <note /> </trans-unit> <trans-unit id="ConvertToLibraryImportMessage"> <source>Mark the method '{0}' with 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time</source> <target state="translated">Contrassegnare il metodo '{0}' con 'LibraryImportAttribute' invece di 'DllImportAttribute' per generare codice di marshalling di P/Invoke in fase di compilazione</target> <note /> </trans-unit> <trans-unit id="ConvertToLibraryImportTitle"> <source>Use 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time</source> <target state="translated">Usare 'LibraryImportAttribute' invece di 'DllImportAttribute' per generare codice di marshalling di P/Invoke in fase di compilazione</target> <note /> </trans-unit> <trans-unit id="ConvertToLibraryImportWarning"> <source>Conversion to 'LibraryImport' may change behavior and compatibility. See {0} for more information.</source> <target state="translated">La conversione in 'LibraryImport' può modificare il comportamento e la compatibilità. Per altre informazioni, vedere {0}.</target> <note>{0} is a documentation link</note> </trans-unit> <trans-unit id="ConvertToLibraryImportWithSuffix"> <source>Convert to 'LibraryImport' with '{0}' suffix</source> <target state="translated">Converti in 'LibraryImport' con il suffisso '{0}'</target> <note /> </trans-unit> <trans-unit id="CustomMarshallerTypeMustHaveRequiredShapeTitle"> <source>Marshaller type does not have the required shape</source> <target state="translated">Il tipo di marshaller non ha la forma richiesta</target> <note /> </trans-unit> <trans-unit id="CustomMarshallerTypeMustSupportDirectionDescription"> <source>A native must set the 'Direction' property on the 'CustomTypeMarshallerAttribute' to a value that sets at least one known flag value on the 'CustomTypeMarshallerDirection' enum</source> <target state="translated">Un tipo nativo deve impostare la proprietà 'Direction' in 'CustomTypeMarshallerAttribute' su un valore che imposta almeno un valore di flag noto nell'enumerazione 'CustomTypeMarshallerDirection'</target> <note /> </trans-unit> <trans-unit id="CustomMarshallerTypeMustSupportDirectionMessage"> <source>The native type '{0}' must set the 'Direction' property on the 'CustomTypeMarshallerAttribute' to a value that sets at least one known flag value on the 'CustomTypeMarshallerDirection' enum</source> <target state="translated">Il tipo nativo '{0}' deve impostare la proprietà 'Direction' in 'CustomTypeMarshallerAttribute' su un valore che imposta almeno un valore di flag noto nell'enumerazione 'CustomTypeMarshallerDirection'</target> <note /> </trans-unit> <trans-unit id="CustomTypeMarshallerAttributeMustBeValidDescription"> <source>The 'CustomTypeMarshallerAttribute' attribute must be semantically valid</source> <target state="translated">L'attributo 'CustomTypeMarshallerAttribute' deve essere semanticamente valido</target> <note /> </trans-unit> <trans-unit id="CustomTypeMarshallerAttributeMustBeValidMessage"> <source>The 'CustomTypeMarshallerAttribute' on '{0}' is semantically invalid</source> <target state="translated">'CustomTypeMarshallerAttribute' in '{0}' non è semanticamente valido</target> <note /> </trans-unit> <trans-unit id="CustomTypeMarshallingManagedToNativeUnsupported"> <source>The specified parameter needs to be marshalled from managed to native, but the native type '{0}' does not support it.</source> <target state="translated">È necessario effettuare il marshalling del parametro specificato da gestito a nativo, ma il tipo nativo '{0}' non lo supporta.</target> <note /> </trans-unit> <trans-unit id="CustomTypeMarshallingNativeToManagedUnsupported"> <source>The specified parameter needs to be marshalled from native to managed, but the native type '{0}' does not support it.</source> <target state="translated">È necessario effettuare il marshalling del parametro specificato da nativo a gestito, ma il tipo nativo '{0}' non lo supporta.</target> <note /> </trans-unit> <trans-unit id="FreeNativeMethodProvidedShouldSpecifyUnmanagedResourcesFeatureDescription"> <source>A marshaller type that provides a 'FreeNative' method should specify that it supports the 'UnmanagedResources' feature.</source> <target state="translated">Un tipo di gestore del marshalling che fornisce un metodo 'FreeNative' deve specificare che supporta la funzionalità 'UnmanagedResources'.</target> <note /> </trans-unit> <trans-unit id="FreeNativeMethodProvidedShouldSpecifyUnmanagedResourcesFeatureMessage"> <source>The type '{0}' provides a 'FreeNative' method but does not specify that it supports the 'UnmanagedResources' feature. The method will not be used unless the feature is specified.</source> <target state="translated">Il tipo '{0}' fornisce un metodo 'FreeNative', ma non specifica che supporta la funzionalità 'UnmanagedResources'. Il metodo verrà usato solo se è specificata la funzionalità.</target> <note /> </trans-unit> <trans-unit id="FromNativeValueMethodProvidedShouldSpecifyTwoStageMarshallingFeatureDescription"> <source>A marshaller type that provides a 'FromNativeValue' method should specify that it supports the 'TwoStageMarshalling' feature.</source> <target state="translated">Un tipo di gestore del marshalling che fornisce un metodo 'FromNativeValue' deve specificare che supporta la funzionalità 'TwoStageMarshalling'.</target> <note /> </trans-unit> <trans-unit id="FromNativeValueMethodProvidedShouldSpecifyTwoStageMarshallingFeatureMessage"> <source>The type '{0}' provides a 'FromNativeValue' method but does not specify that it supports the 'TwoStageMarshalling' feature. The method will not be used unless the feature is specified.</source> <target state="translated">Il tipo '{0}' fornisce un metodo 'FromNativeValue', ma non specifica che supporta la funzionalità 'TwoStageMarshalling'. Il metodo verrà usato solo se è specificata la funzionalità.</target> <note /> </trans-unit> <trans-unit id="GetPinnableReferenceReturnTypeBlittableDescription"> <source>The return type of 'GetPinnableReference' (after accounting for 'ref') must be blittable.</source> <target state="translated">Il tipo restituito di 'GetPinnableReference' (dopo l'accounting di 'ref') deve essere copiabile da BLT.</target> <note /> </trans-unit> <trans-unit id="GetPinnableReferenceReturnTypeBlittableMessage"> <source>The dereferenced type of the return type of the 'GetPinnableReference' method must be blittable</source> <target state="translated">Il tipo dereferenziato del tipo restituito del metodo 'GetPinnableReference' deve essere copiabile da BLT</target> <note /> </trans-unit> <trans-unit id="GetPinnableReferenceShouldSupportAllocatingMarshallingFallbackDescription"> <source>A type that supports marshalling from managed to native by pinning should also support marshalling from managed to native where pinning is impossible.</source> <target state="translated">Un tipo che supporta il marshalling da gestito a nativo tramite l'aggiunta deve supportare anche il marshalling da gestito a nativo nei casi in cui l'aggiunta risulta impossibile.</target> <note /> </trans-unit> <trans-unit id="GetPinnableReferenceShouldSupportAllocatingMarshallingFallbackMessage"> <source>Type '{0}' has a 'GetPinnableReference' method but its native type does not support marshalling in scenarios where pinning is impossible</source> <target state="translated">Il tipo '{0}' include un metodo 'GetPinnableReference', ma il relativo tipo nativo non supporta il marshalling in scenari in cui l'aggiunta risulta impossibile</target> <note /> </trans-unit> <trans-unit id="InTwoStageMarshallingRequiresToNativeValueDescription"> <source>The 'TwoStageMarshalling' feature requires a 'TNativeType ToNativeValue()' method for the 'In' direction.</source> <target state="translated">La funzionalità 'TwoStageMarshalling' richiede un metodo 'TNativeType ToNativeValue()' per la direzione 'In'.</target> <note /> </trans-unit> <trans-unit id="InTwoStageMarshallingRequiresToNativeValueMessage"> <source>A marshaller type '{0}' that supports marshalling in the 'In' direction with the 'TwoStageMarshalling' feature must provide a 'ToNativeValue' instance method that returns the native value</source> <target state="translated">Un tipo di marshaller '{0}' che supporta il marshalling nella direzione 'In' con la funzionalità 'TwoStageMarshalling' deve fornire un metodo di istanza 'ToNativeValue' che restituisce il valore nativo</target> <note /> </trans-unit> <trans-unit id="InvalidAttributedMethodContainingTypeMissingModifiersMessage"> <source>Method '{0}' is contained in a type '{1}' that is not marked 'partial'. P/Invoke source generation will ignore method '{0}'.</source> <target state="translated">Il metodo '{0}' è contenuto in un tipo '{1}' non contrassegnato come 'partial'. Durante la generazione dell'origine P/Invoke il metodo '{0}' verrà ignorato.</target> <note /> </trans-unit> <trans-unit id="InvalidAttributedMethodDescription"> <source>Methods marked with 'LibraryImportAttribute' should be 'static', 'partial', and non-generic. P/Invoke source generation will ignore methods that are non-'static', non-'partial', or generic.</source> <target state="translated">I metodi contrassegnati con 'LibraryImportAttribute' devono essere 'static', 'partial' e non generici. Durante la generazione dell'origine P/Invoke i metodi non 'static', non 'partial' o generici verranno ignorati.</target> <note /> </trans-unit> <trans-unit id="InvalidAttributedMethodSignatureMessage"> <source>Method '{0}' should be 'static', 'partial', and non-generic when marked with 'LibraryImportAttribute'. P/Invoke source generation will ignore method '{0}'.</source> <target state="translated">Il metodo '{0}' deve essere 'static', 'partial' e non generico quando è contrassegnato con 'LibraryImportAttribute'. Durante la generazione dell'origine P/Invoke il metodo '{0}' verrà ignorato.</target> <note /> </trans-unit> <trans-unit id="InvalidCustomTypeMarshallerAttributeUsageTitle"> <source>Invalid `CustomTypeMarshallerAttribute` usage</source> <target state="translated">Utilizzo di 'CustomTypeMarshallerAttribute' non valido</target> <note /> </trans-unit> <trans-unit id="InvalidLibraryImportAttributeUsageTitle"> <source>Invalid 'LibraryImportAttribute' usage</source> <target state="translated">Utilizzo di 'LibraryImportAttribute' non valido</target> <note /> </trans-unit> <trans-unit id="InvalidNativeTypeTitle"> <source>Specified native type is invalid</source> <target state="translated">Il tipo nativo specificato non è valido</target> <note /> </trans-unit> <trans-unit id="InvalidSignaturesInMarshallerShapeTitle"> <source>Marshaller type has incompatible method signatures</source> <target state="translated">Il tipo marshaller ha firme di metodo incompatibili</target> <note /> </trans-unit> <trans-unit id="InvalidStringMarshallingConfigurationDescription"> <source>The configuration of 'StringMarshalling' and 'StringMarshallingCustomType' is invalid.</source> <target state="translated">La configurazione di 'StringMarshalling' e 'StringMarshallingCustomType' non è valida.</target> <note /> </trans-unit> <trans-unit id="InvalidStringMarshallingConfigurationMessage"> <source>The configuration of 'StringMarshalling' and 'StringMarshallingCustomType' on method '{0}' is invalid. {1}</source> <target state="translated">La configurazione di 'StringMarshalling' e 'StringMarshallingCustomType' nel metodo '{0}' non è valida. {1}</target> <note>{1} is a message containing additional details about what is not valid</note> </trans-unit> <trans-unit id="InvalidStringMarshallingConfigurationMissingCustomType"> <source>'StringMarshallingCustomType' must be specified when 'StringMarshalling' is set to 'StringMarshalling.Custom'.</source> <target state="translated">È necessario specificare 'StringMarshallingCustomType' quando 'StringMarshalling' è impostato su 'StringMarshalling.Custom'.</target> <note /> </trans-unit> <trans-unit id="InvalidStringMarshallingConfigurationNotCustom"> <source>'StringMarshalling' should be set to 'StringMarshalling.Custom' when 'StringMarshallingCustomType' is specified.</source> <target state="translated">'StringMarshalling' deve essere impostato su 'StringMarshalling.Custom' quando è specificato 'StringMarshallingCustomType'.</target> <note /> </trans-unit> <trans-unit id="LinearCollectionElementTypesMustMatchDescription"> <source>The element type of the 'ReadOnlySpan' returned by 'GetManagedValuesSource' must be the same as the element type returned by 'GetManagedValuesDestination'.</source> <target state="translated">Il tipo di elemento di 'ReadOnlySpan' restituito da 'GetManagedValuesSource' deve essere uguale al tipo di elemento restituito da 'GetManagedValuesDestination'.</target> <note /> </trans-unit> <trans-unit id="LinearCollectionElementTypesMustMatchMessage"> <source>The element type of the 'ReadOnlySpan' returned by 'GetManagedValuesSource' must be the same as the element type returned by 'GetManagedValuesDestination'</source> <target state="translated">Il tipo di elemento di 'ReadOnlySpan' restituito da 'GetManagedValuesSource' deve essere uguale al tipo di elemento restituito da 'GetManagedValuesDestination'</target> <note /> </trans-unit> <trans-unit id="LinearCollectionInCallerAllocatedBufferRequiresSpanConstructorDescription"> <source>A 'LinearCollection'-kind native type that supports the 'CallerAllocatedBuffer' feature must provide a three-parameter constructor taking the managed type as the first parameter, a 'Span&lt;byte&gt;' as the second parameter, and the native size of the element as the third parameter</source> <target state="translated">Un tipo nativo di tipo 'LinearCollection' che supporta la funzionalità 'CallerAllocatedBuffer' deve fornire un costruttore a tre parametri che accetta il tipo gestito come primo parametro, un elemento 'Span&lt;byte&gt;' come secondo parametro e la dimensione nativa dell'elemento come terzo parametro</target> <note /> </trans-unit> <trans-unit id="LinearCollectionInCallerAllocatedBufferRequiresSpanConstructorMessage"> <source>The type '{0}' specifies that it supports 'In' marshalling with the 'CallerAllocatedBuffer' feature for '{1}' but does not provide a three-parameter constructor that takes a '{1}' , a 'Span&lt;byte&gt;', and an 'int'</source> <target state="translated">Il tipo '{0}' specifica che supporta il marshalling 'In' con la funzionalità 'CallerAllocatedBuffer' per '{1}', ma non fornisce un costruttore a tre parametri che accetta '{1}', 'Span&lt;byte&gt;' e 'int'</target> <note /> </trans-unit> <trans-unit id="LinearCollectionInRequiresCollectionMethodsDescription"> <source>A 'LinearCollection'-kind native type that supports marshalling in the 'In' direction must provide a 'GetManagedValuesSource' that returns a 'ReadOnlySpan&lt;&gt;' and a 'GetNativeValuesDestination' method that returns a 'Span&lt;byte&gt;'.</source> <target state="translated">Il tipo nativo di tipo 'LinearCollection' che supporta il marshalling nella direzione 'In' deve fornire un elemento 'GetManagedValuesSource' che restituisce un elemento 'ReadOnlySpan&lt;&gt;' e un metodo 'GetNativeValuesDestination' che restituisce un elemento 'Span&lt;byte&gt;'.</target> <note /> </trans-unit> <trans-unit id="LinearCollectionInRequiresCollectionMethodsMessage"> <source>The type '{0}' specifies that is supports marshalling in the 'In' direction, but it does not provide a 'GetManagedValuesSource' that returns a 'ReadOnlySpan&lt;&gt;' and a 'GetNativeValuesDestination' method that returns a 'Span&lt;byte&gt;'</source> <target state="translated">Il tipo '{0}' specifica che supporta il marshalling nella direzione 'In', ma non fornisce un elemento 'GetManagedValuesSource' che restituisce un elemento 'ReadOnlySpan&lt;&gt;' e un metodo 'GetNativeValuesDestination' che restituisce un elemento 'Span&lt;byte&gt;'</target> <note /> </trans-unit> <trans-unit id="LinearCollectionInRequiresTwoParameterConstructorDescription"> <source>A 'LinearCollection'-kind native type must provide a two-parameter constructor taking the managed type as the first parameter and the native size of the element as the second parameter</source> <target state="translated">Un tipo nativo di tipo 'LinearCollection' deve fornire un costruttore a due parametri che accetta il tipo gestito come primo parametro e le dimensioni native dell'elemento come secondo parametro</target> <note /> </trans-unit> <trans-unit id="LinearCollectionInRequiresTwoParameterConstructorMessage"> <source>The type '{0}' specifies that it supports 'In' marshalling of '{1}' but does not provide a two-parameter constructor that takes a '{1}' as the first parameter and an 'int' as the second parameter</source> <target state="translated">Il tipo '{0}' specifica che supporta il marshalling 'In' di '{1}' ma non fornisce un costruttore a due parametri che accetta '{1}' come primo parametro e 'int' come secondo parametro</target> <note /> </trans-unit> <trans-unit id="LinearCollectionOutRequiresCollectionMethodsDescription"> <source>A 'LinearCollection'-kind native type that supports marshalling in the 'Out' direction must provide a 'GetManagedValuesDestination' that takes an 'int' and returns a 'Span&lt;&gt;' and a 'GetNativeValuesSource' method that takes an 'int' and rreturns a 'ReadOnlySpan&lt;byte&gt;'.</source> <target state="translated">Un tipo nativo di tipo 'LinearCollection' che supporta il marshalling nella direzione 'Out' deve fornire un metodo 'GetManagedValuesDestination' che accetta 'int' e restituisce un elemento 'Span&lt;&gt;' e un metodo 'GetNativeValuesSource' che accetta 'int' e restituisce un elemento 'ReadOnlySpan&lt;byte&gt;'.</target> <note /> </trans-unit> <trans-unit id="LinearCollectionOutRequiresCollectionMethodsMessage"> <source>The type '{0}' specifies that it supports marshalling in the 'Out' direction, but it does not provide a 'GetManagedValuesDestination' that takes an 'int' and returns a 'Span&lt;&gt;' and a 'GetNativeValuesSource' method that takes an 'int' and rreturns a 'ReadOnlySpan&lt;byte&gt;'</source> <target state="translated">Il tipo '{0}' specifica che supporta il marshalling nella direzione 'Out', ma non fornisce un metodo 'GetManagedValuesDestination' che accetta 'int' e restituisce un elemento 'Span&lt;&gt;' e un metodo 'GetNativeValuesSource' che accetta 'int' e restituisce un elemento 'ReadOnlySpan&lt;byte&gt;'</target> <note /> </trans-unit> <trans-unit id="LinearCollectionOutRequiresIntConstructorDescription"> <source>A 'LinearCollection'-kind native type that supports marshalling in the 'Out' direction must provide a constructor that takes the size of the native element as an 'int'.</source> <target state="translated">Un tipo nativo di tipo 'LinearCollection' che supporta il marshalling nella direzione 'Out' deve fornire un costruttore che accetta le dimensioni dell'elemento nativo come 'int'.</target> <note /> </trans-unit> <trans-unit id="LinearCollectionOutRequiresIntConstructorMessage"> <source>The type '{0}' specifies that it supports marshalling in the 'Out' direction, but it does not provide a constructor that takes the size of the native element as an 'int'.</source> <target state="translated">Il tipo '{0}' specifica che supporta il marshalling nella direzione 'Out', ma non fornisce un costruttore che accetta le dimensioni dell'elemento nativo come 'int'.</target> <note /> </trans-unit> <trans-unit id="MarshallerDirectionMustBeValidDescription"> <source>The specified marshaller direction must be a valid value of the 'System.Runtime.InteropServices.CustomMarshallerDirection' enum.</source> <target state="translated">La direzione del gestore del marshalling specificato deve essere un valore valido dell'enumerazione 'System.Runtime.InteropServices.CustomMarshallerDirection'.</target> <note /> </trans-unit> <trans-unit id="MarshallerDirectionMustBeValidMessage"> <source>The specified custom marshaller direction for '{0}' is invalid</source> <target state="translated">La direzione del gestore del marshalling personalizzato specificata per '{0}' non è valida</target> <note /> </trans-unit> <trans-unit id="MarshallerGetPinnableReferenceRequiresTwoStageMarshallingDescription"> <source>The use cases for 'GetPinnableReference' are not applicable in any scenarios where 'TwoStageMarshalling' is not also required.</source> <target state="translated">I casi d'uso per 'GetPinnableReference' non sono applicabili in nessuno scenario in cui non è richiesto anche 'TwoStageMarshalling'.</target> <note /> </trans-unit> <trans-unit id="MarshallerGetPinnableReferenceRequiresTwoStageMarshallingMessage"> <source>The 'GetPinnableReference' method cannot be provided on the native type '{0}' unless the 'TwoStageMarshalling' feature is also supported</source> <target state="translated">Non è possibile specificare il metodo 'GetPinnableReference' nel tipo nativo '{0}' a meno che non sia supportata anche la funzionalità 'TwoStageMarshalling'</target> <note /> </trans-unit> <trans-unit id="MarshallerKindMustBeValidDescription"> <source>The specified marshaller kind must be a valid value of the 'System.Runtime.InteropServices.CustomMarshallerKind' enum.</source> <target state="translated">Il tipo di gestore del marshalling specificato deve essere un valore valido dell'enumerazione 'System.Runtime.InteropServices.CustomMarshallerKind'.</target> <note /> </trans-unit> <trans-unit id="MarshallerKindMustBeValidMessage"> <source>The specified custom marshaller kind for '{0}' is invalid</source> <target state="translated">Il tipo del gestore del marshalling personalizzato specificata per '{0}' non è valida</target> <note /> </trans-unit> <trans-unit id="MarshallerTypeMustSpecifyManagedTypeDescription"> <source>A type with a 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' must specify a managed type</source> <target state="translated">Un tipo con 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' deve specificare un tipo gestito</target> <note /> </trans-unit> <trans-unit id="MarshallerTypeMustSpecifyManagedTypeMessage"> <source>The type '{0}' does not specify a managed type in the 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' applied to the type</source> <target state="translated">Il tipo '{0}' non specifica un tipo gestito nell'elemento 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' applicato al tipo</target> <note /> </trans-unit> <trans-unit id="MissingAllocatingMarshallingFallbackTitle"> <source>Marshaller type does not support allocating constructor</source> <target state="translated">Il tipo marshaller non supporta l'allocazione del costruttore</target> <note /> </trans-unit> <trans-unit id="NativeGenericTypeMustBeClosedOrMatchArityDescription"> <source>The native type '{0}' must be a closed generic or have the same number of generic parameters as the managed type so the emitted code can use a specific instantiation.</source> <target state="translated">Il tipo nativo '{0}' deve essere un generico chiuso o avere lo stesso numero di parametri generici del tipo gestito in modo che il codice emesso possa usare una creazione di istanza specifica.</target> <note /> </trans-unit> <trans-unit id="NativeGenericTypeMustBeClosedOrMatchArityMessage"> <source>The native type '{0}' for managed type '{1}' must be a closed generic type or have the same arity as the managed type.</source> <target state="translated">Il tipo nativo '{0}' per il tipo gestito '{1}' deve essere un tipo generico chiuso o avere lo stesso grado del tipo gestito.</target> <note /> </trans-unit> <trans-unit id="NativeTypeMustBeBlittableDescription"> <source>A native type must be blittable.</source> <target state="translated">Un tipo nativo deve essere copiabile da BLT.</target> <note /> </trans-unit> <trans-unit id="NativeTypeMustBeBlittableMessage"> <source>The native type '{0}' for type '{1}' must be blittable</source> <target state="translated">Il tipo nativo '{0}' per il tipo '{1}' deve essere copiabile da BLT</target> <note /> </trans-unit> <trans-unit id="NativeTypeMustBePointerSizedDescription"> <source>The native type must be pointer sized so the pinned result of 'GetPinnableReference' can be cast to the native type.</source> <target state="translated">Il tipo nativo deve essere dimensionato in base al puntatore in modo da poter eseguire il cast del risultato aggiunto di 'GetPinnableReference' al tipo nativo.</target> <note /> </trans-unit> <trans-unit id="NativeTypeMustBePointerSizedMessage"> <source>The native type '{0}' must be pointer sized because the managed type '{1}' has a 'GetPinnableReference' method</source> <target state="translated">Il tipo nativo '{0}' deve essere dimensionato in base al puntatore perché il tipo gestito '{1}' include un metodo 'GetPinnableReference'</target> <note /> </trans-unit> <trans-unit id="NativeTypeMustHaveCustomTypeMarshallerAttributeDescription"> <source>A native type for a given type must have the 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' that specifies this type as the managed type.</source> <target state="translated">Un tipo nativo per un tipo specificato deve includere un elemento 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' che specifica questo tipo come tipo gestito.</target> <note /> </trans-unit> <trans-unit id="NativeTypeMustHaveCustomTypeMarshallerAttributeMessage"> <source>The native type for the type '{0}' must be a type with the 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' that specifies this type as the managed type</source> <target state="translated">Il tipo nativo per il tipo '{0}' deve essere un tipo con 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' che specifica questo tipo come tipo gestito</target> <note /> </trans-unit> <trans-unit id="OutRequiresToManagedDescription"> <source>A 'Value' or 'LinearCollection'-kind native type that supports marshalling in the 'Out' direction must provide a 'ToManaged' method that returns the managed type.</source> <target state="translated">Un tipo nativo di tipo 'Value' o 'LinearCollection' che supporta il marshalling nella direzione 'Out' deve fornire un metodo 'ToManaged' che restituisce il tipo gestito.</target> <note /> </trans-unit> <trans-unit id="OutRequiresToManagedMessage"> <source>The type '{0}' specifies it supports marshalling in the 'Out' direction, but it does not provide a 'ToManaged' method that returns the managed type</source> <target state="translated">Il tipo '{0}' specifica che supporta il marshalling nella direzione 'Out', ma non fornisce un metodo 'ToManaged' che restituisce il tipo gestito</target> <note /> </trans-unit> <trans-unit id="OutTwoStageMarshallingRequiresFromNativeValueDescription"> <source>The 'TwoStageMarshalling' feature requires a 'void FromNativeValue(TNativeType value)' method for the 'Out' direction.</source> <target state="translated">Con la funzionalità 'TwoStageMarshalling' è richiesto un metodo 'void FromNativeValue(TNativeType value)' per la direzione 'Out'.</target> <note /> </trans-unit> <trans-unit id="OutTwoStageMarshallingRequiresFromNativeValueMessage"> <source>The marshaller type '{0}' supports marshalling in the 'Out' direction with the 'TwoStageMarshalling' feature, but it does not provide a 'FromNativeValue' instance method that returns 'void' and takes one parameter.</source> <target state="translated">Il tipo di gestore del marshalling '{0}' supporta il marshalling nella direzione 'Out' con la funzionalità 'TwoStageMarshalling', ma non fornisce un metodo di istanza 'FromNativeValue' che restituisce 'void' e accetta un solo parametro.</target> <note /> </trans-unit> <trans-unit id="ProvidedMethodsNotSpecifiedInFeaturesTitle"> <source>Marshaller type defines a well-known method without specifying support for the corresponding feature</source> <target state="translated">Il tipo marshaller definisce un metodo noto senza specificare il supporto per la funzionalità corrispondente</target> <note /> </trans-unit> <trans-unit id="RefNativeValueUnsupportedDescription"> <source>The 'Value' property must not be a 'ref' or 'readonly ref' property.</source> <target state="translated">La proprietà 'Value' non deve essere una proprietà 'ref' o 'readonly ref'.</target> <note /> </trans-unit> <trans-unit id="RefNativeValueUnsupportedMessage"> <source>The 'Value' property on the native type '{0}' must not be a 'ref' or 'readonly ref' property.</source> <target state="translated">La proprietà 'Value' nel tipo nativo '{0}' non deve essere una proprietà 'ref' o 'readonly ref'.</target> <note /> </trans-unit> <trans-unit id="SafeHandleByRefMustBeConcrete"> <source>An abstract type derived from 'SafeHandle' cannot be marshalled by reference. The provided type must be concrete.</source> <target state="translated">Non è possibile effettuare il marshalling per riferimento di un tipo astratto derivato da 'SafeHandle'. Il tipo specificato deve essere concreto.</target> <note /> </trans-unit> <trans-unit id="ToNativeValueMethodProvidedShouldSpecifyTwoStageMarshallingFeatureDescription"> <source>A marshaller type that provides a 'ToNativeValue' method should specify that it supports the 'TwoStageMarshalling' feature.</source> <target state="translated">Un tipo di gestore del marshalling che fornisce un metodo 'ToNativeValue' deve specificare che supporta la funzionalità 'TwoStageMarshalling'.</target> <note /> </trans-unit> <trans-unit id="ToNativeValueMethodProvidedShouldSpecifyTwoStageMarshallingFeatureMessage"> <source>The type '{0}' provides a 'ToNativeValue' method but does not specify that it supports the 'TwoStageMarshalling' feature. The method will not be used unless the feature is specified.</source> <target state="translated">Il tipo '{0}' fornisce un metodo 'ToNativeValue', ma non specifica che supporta la funzionalità 'TwoStageMarshalling'. Il metodo verrà usato solo se è specificata la funzionalità.</target> <note /> </trans-unit> <trans-unit id="TwoStageMarshallingNativeTypesMustMatchDescription"> <source>The return type of 'ToNativeValue' and the parameter type of 'FromNativeValue' must be the same.</source> <target state="translated">Il tipo restituito di 'ToNativeValue' e il tipo di parametro di 'FromNativeValue' devono essere uguali.</target> <note /> </trans-unit> <trans-unit id="TwoStageMarshallingNativeTypesMustMatchMessage"> <source>The return type of 'ToNativeValue' and the parameter type of 'FromNativeValue' must be the same</source> <target state="translated">Il tipo restituito di 'ToNativeValue' e il tipo di parametro di 'FromNativeValue' devono essere uguali</target> <note /> </trans-unit> <trans-unit id="TypeNotSupportedDescription"> <source>For types that are not supported by source-generated P/Invokes, the resulting P/Invoke will rely on the underlying runtime to marshal the specified type.</source> <target state="translated">Per i tipi non supportati da P/Invoke generati dall'origine, il P/Invoke risultante si baserà sul runtime sottostante per effettuare il marshalling del tipo specificato.</target> <note /> </trans-unit> <trans-unit id="TypeNotSupportedMessageParameter"> <source>The type '{0}' is not supported by source-generated P/Invokes. The generated source will not handle marshalling of parameter '{1}'.</source> <target state="translated">Il tipo '{0}' non è supportato dai P/Invoke generati dall'origine. L'origine generata non gestirà il marshalling del parametro '{1}'.</target> <note /> </trans-unit> <trans-unit id="TypeNotSupportedMessageParameterWithDetails"> <source>{0} The generated source will not handle marshalling of parameter '{1}'.</source> <target state="translated">{0} L'origine generata non gestirà il marshalling del parametro '{1}'.</target> <note>{0} is a message containing additional details about what is not supported {1} is the name of the parameter</note> </trans-unit> <trans-unit id="TypeNotSupportedMessageReturn"> <source>The type '{0}' is not supported by source-generated P/Invokes. The generated source will not handle marshalling of the return value of method '{1}'.</source> <target state="translated">Il tipo '{0}' non è supportato dai P/Invoke generati dall'origine. L'origine generata non gestirà il marshalling del valore restituito del metodo '{1}'.</target> <note /> </trans-unit> <trans-unit id="TypeNotSupportedMessageReturnWithDetails"> <source>{0} The generated source will not handle marshalling of the return value of method '{1}'.</source> <target state="translated">{0} L'origine generata non gestirà il marshalling del valore restituito del metodo '{1}'.</target> <note>{0} is a message containing additional details about what is not supported {1} is the name of the method</note> </trans-unit> <trans-unit id="TypeNotSupportedTitle"> <source>Specified type is not supported by source-generated P/Invokes</source> <target state="translated">Il tipo specificato non è supportato dai P/Invoke generati dall'origine</target> <note /> </trans-unit> <trans-unit id="UnmanagedResourcesRequiresFreeNativeDescription"> <source>The 'UnmanagedResources' feature requires a 'void FreeNative()' method.</source> <target state="translated">Con la funzionalità 'UnmanagedResources' è richiesto un metodo 'void FreeNative()'.</target> <note /> </trans-unit> <trans-unit id="UnmanagedResourcesRequiresFreeNativeMessage"> <source>The marshaller type '{0}' supports marshalling with the 'UnmanagedResources' feature, but it does not provide a parameterless 'FreeNative' instance method that returns 'void'</source> <target state="translated">Il tipo di gestore del marshalling '{0}' supporta il marshalling con la funzionalità 'UnmanagedResources', ma non fornisce un metodo di istanza 'FreeNative' senza parametri che restituisce 'void'</target> <note /> </trans-unit> <trans-unit id="ValueInCallerAllocatedBufferRequiresSpanConstructorDescription"> <source>A 'Value'-kind native type that supports the 'CallerAllocatedBuffer' feature must provide a two-parameter constructor taking the managed type and a 'Span' of an 'unmanaged' type as parameters</source> <target state="translated">Un tipo nativo di tipo 'Value' che supporta la funzionalità 'CallerAllocatedBuffer' deve fornire un costruttore a due parametri che accetta il tipo gestito e un 'Span' di un tipo 'non gestito' come parametri</target> <note /> </trans-unit> <trans-unit id="ValueInCallerAllocatedBufferRequiresSpanConstructorMessage"> <source>The type '{0}' specifies that it supports 'In' marshalling with the 'CallerAllocatedBuffer' feature for '{1}' but does not provide a two-parameter constructor that takes a '{1}' and 'Span' of an 'unmanaged' type as parameters</source> <target state="new">The type '{0}' specifies that it supports 'In' marshalling with the 'CallerAllocatedBuffer' feature for '{1}' but does not provide a two-parameter constructor that takes a '{1}' and 'Span' of an 'unmanaged' type as parameters</target> <note /> </trans-unit> <trans-unit id="ValueInRequiresOneParameterConstructorDescription"> <source>A 'Value'-kind native type must provide a one-parameter constructor taking the managed type as a parameter</source> <target state="translated">Un tipo nativo di tipo 'Value' deve fornire un costruttore a un parametro che accetta il tipo gestito come parametro</target> <note /> </trans-unit> <trans-unit id="ValueInRequiresOneParameterConstructorMessage"> <source>The type '{0}' specifies that it supports 'In' marshalling of '{1}' but does not provide a one-parameter constructor that takes a '{1}' as a parameter</source> <target state="translated">Il tipo '{0}' specifica che supporta il marshalling 'In' di '{1}' ma non fornisce un costruttore con un solo parametro che accetta '{1}' come parametro</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="it" original="../Strings.resx"> <body> <trans-unit id="AddMissingCustomTypeMarshallerMembers"> <source>Add missing custom type marshaller members</source> <target state="translated">Aggiungi membri mancanti del gestore del marshalling di tipi personalizzato mancanti</target> <note /> </trans-unit> <trans-unit id="AddMissingFeaturesToCustomTypeMarshaller"> <source>Add missing features to the 'CustomTypeMarshallerAttribute' attribute</source> <target state="translated">Aggiungi funzionalità mancanti all'attributo 'CustomTypeMarshallerAttribute'</target> <note /> </trans-unit> <trans-unit id="CallerAllocConstructorMustHaveBufferSizeDescription"> <source>When a constructor taking a 'Span&lt;byte&gt;' is specified on the native type, the type must set the BufferSize field on the 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' to provide the size of the caller-allocated buffer.</source> <target state="translated">Quando nel tipo nativo è specificato un costruttore che accetta 'Span&lt;byte&gt;', il tipo deve impostare il campo BufferSize in 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' per fornire le dimensioni del buffer allocato dal chiamante.</target> <note /> </trans-unit> <trans-unit id="CallerAllocConstructorMustHaveBufferSizeMessage"> <source>The native type '{0}' must set the 'BufferSize' field on the applied 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' to specify the size of the caller-allocated buffer because it has a constructor that takes a caller-allocated 'Span&lt;byte&gt;'</source> <target state="translated">Il tipo nativo '{0}' deve impostare il campo 'BufferSize' nell'elemento 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' applicato per specificare le dimensioni del buffer allocato dal chiamante, perché contiene un costruttore che accetta un elemento 'Span&lt;byte&gt;' allocato dal chiamante</target> <note /> </trans-unit> <trans-unit id="CallerAllocConstructorMustHaveBufferSizeTitle"> <source>'BufferSize' should be set on 'CustomTypeMarshallerAttribute'</source> <target state="translated">'BufferSize' deve essere impostato su 'CustomTypeMarshallerAttribute'</target> <note /> </trans-unit> <trans-unit id="CallerAllocMarshallingShouldSupportAllocatingMarshallingFallbackDescription"> <source>A type that supports marshalling from managed to native using a caller-allocated buffer should also support marshalling from managed to native where using a caller-allocated buffer is impossible.</source> <target state="translated">Un tipo che supporta il marshalling da gestito a nativo tramite un buffer allocato dal chiamante deve supportare anche il marshalling da gestito a nativo in cui non è possibile usare un buffer allocato dal chiamante.</target> <note /> </trans-unit> <trans-unit id="CallerAllocMarshallingShouldSupportAllocatingMarshallingFallbackMessage"> <source>Native type '{0}' has a constructor taking a caller-allocated buffer, but does not support marshalling in scenarios where using a caller-allocated buffer is impossible</source> <target state="translated">Il tipo nativo '{0}' include un costruttore che accetta un buffer allocato dal chiamante, ma non supporta il marshalling in scenari in cui l'uso di un buffer allocato dal chiamante risulta impossibile</target> <note /> </trans-unit> <trans-unit id="CallerAllocatedBufferConstructorProvidedShouldSpecifyFeatureDescription"> <source>A marshaller type that provides a constructor taking a caller-allocated 'Span&lt;byte&gt;' should specify that it supports the 'CallerAllocatedBuffer' feature.</source> <target state="translated">Un tipo di gestore del marshalling che fornisce un costruttore che accetta un elemento 'Span&lt;byte&gt;' allocato dal chiamante deve specificare che supporta la funzionalità 'CallerAllocatedBuffer'.</target> <note /> </trans-unit> <trans-unit id="CallerAllocatedBufferConstructorProvidedShouldSpecifyFeatureMessage"> <source>The type '{0}' provides a constructor taking a caller-allocated 'Span&lt;byte&gt;' but does not specify that it supports the 'CallerAllocatedBuffer' feature. The constructor will not be used unless the feature is specified.</source> <target state="translated">Il tipo '{0}' fornisce un costruttore che accetta un elemento 'Span&lt;byte&gt;' allocato dal chiamante, ma non specifica che supporta la funzionalità 'CallerAllocatedBuffer'. Il costruttore verrà usato solo se è specificata la funzionalità.</target> <note /> </trans-unit> <trans-unit id="CannotForwardToDllImportDescription"> <source>The generated 'DllImportAttribute' will not have a value corresponding to '{0}'.</source> <target state="translated">L'elemento 'DllImportAttribute' generato non avrà un valore corrispondente a '{0}'.</target> <note /> </trans-unit> <trans-unit id="CannotForwardToDllImportMessage"> <source>'{0}' has no equivalent in 'DllImportAtttribute' and will not be forwarded</source> <target state="translated">'{0}' non ha equivalenti in 'DllImportAtttribute' e non verrà inoltrato</target> <note /> </trans-unit> <trans-unit id="CannotForwardToDllImportTitle"> <source>Specified 'LibraryImportAttribute' arguments cannot be forwarded to 'DllImportAttribute'</source> <target state="translated">Gli argomenti 'LibraryImportAttribute' specificati non possono essere inoltrati a 'DllImportAttribute'</target> <note /> </trans-unit> <trans-unit id="ConfigurationNotSupportedDescription"> <source>Source-generated P/Invokes will ignore any configuration that is not supported.</source> <target state="translated">I P/Invoke generati dall'origine ignoreranno qualsiasi configurazione non supportata.</target> <note /> </trans-unit> <trans-unit id="ConfigurationNotSupportedMessage"> <source>The '{0}' configuration is not supported by source-generated P/Invokes. If the specified configuration is required, use a regular `DllImport` instead.</source> <target state="translated">La configurazione '{0}' non è supportata dai P/Invoke generati dall'origine. Se la configurazione specificata è obbligatoria, usare un attributo `DllImport` normale.</target> <note /> </trans-unit> <trans-unit id="ConfigurationNotSupportedMessageMarshallingInfo"> <source>The specified marshalling configuration is not supported by source-generated P/Invokes. {0}.</source> <target state="translated">La configurazione di marshalling specificata non è supportata dai P/Invoke generati dall'origine. {0}.</target> <note /> </trans-unit> <trans-unit id="ConfigurationNotSupportedMessageParameter"> <source>The specified '{0}' configuration for parameter '{1}' is not supported by source-generated P/Invokes. If the specified configuration is required, use a regular `DllImport` instead.</source> <target state="translated">La configurazione '{0}' specificata per il parametro '{1}' non è supportata dai P/Invoke generati dall'origine. Se la configurazione specificata è obbligatoria, usare un attributo `DllImport` normale.</target> <note /> </trans-unit> <trans-unit id="ConfigurationNotSupportedMessageReturn"> <source>The specified '{0}' configuration for the return value of method '{1}' is not supported by source-generated P/Invokes. If the specified configuration is required, use a regular `DllImport` instead.</source> <target state="translated">La configurazione '{0}' specificata per il valore restituito del metodo '{1}' non è supportata dai P/Invoke generati dall'origine. Se la configurazione specificata è obbligatoria, usare un attributo `DllImport` normale.</target> <note /> </trans-unit> <trans-unit id="ConfigurationNotSupportedMessageValue"> <source>The specified value '{0}' for '{1}' is not supported by source-generated P/Invokes. If the specified value is required, use a regular `DllImport` instead.</source> <target state="translated">Il valore specificato '{0}' per '{1}' non è supportato da P/Invoke generati dall'origine. Se il valore specificato è obbligatorio, usare un 'DllImport' normale.</target> <note /> </trans-unit> <trans-unit id="ConfigurationNotSupportedTitle"> <source>Specified configuration is not supported by source-generated P/Invokes.</source> <target state="translated">La configurazione specificata non è supportata dai P/Invoke generati dall'origine.</target> <note /> </trans-unit> <trans-unit id="ConstantAndElementCountInfoDisallowed"> <source>Only one of 'ConstantElementCount' or 'ElementCountInfo' may be used in a 'MarshalUsingAttribute' for a given 'ElementIndirectionDepth'</source> <target state="translated">In un elemento 'MarshalUsingAttribute' per un elemento 'ElementIndirectionDepth' specificato è possibile usare solo uno dei valori 'ConstantElementCount' o 'ElementCountInfo'</target> <note /> </trans-unit> <trans-unit id="ConvertNoPreserveSigDllImportToGeneratedMayProduceInvalidCode"> <source>Automatically converting a P/Invoke with 'PreserveSig' set to 'false' to a source-generated P/Invoke may produce invalid code</source> <target state="translated">La conversione automatica di un P/Invoke con 'PreserveSig' impostato su 'false' in un P/Invoke generato dall'origine può produrre codice non valido</target> <note /> </trans-unit> <trans-unit id="ConvertToLibraryImport"> <source>Convert to 'LibraryImport'</source> <target state="translated">Converti in 'LibraryImport'</target> <note /> </trans-unit> <trans-unit id="ConvertToLibraryImportDescription"> <source>Use 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time</source> <target state="translated">Usare 'LibraryImportAttribute' invece di 'DllImportAttribute' per generare codice di marshalling di P/Invoke in fase di compilazione</target> <note /> </trans-unit> <trans-unit id="ConvertToLibraryImportMessage"> <source>Mark the method '{0}' with 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time</source> <target state="translated">Contrassegnare il metodo '{0}' con 'LibraryImportAttribute' invece di 'DllImportAttribute' per generare codice di marshalling di P/Invoke in fase di compilazione</target> <note /> </trans-unit> <trans-unit id="ConvertToLibraryImportTitle"> <source>Use 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time</source> <target state="translated">Usare 'LibraryImportAttribute' invece di 'DllImportAttribute' per generare codice di marshalling di P/Invoke in fase di compilazione</target> <note /> </trans-unit> <trans-unit id="ConvertToLibraryImportWarning"> <source>Conversion to 'LibraryImport' may change behavior and compatibility. See {0} for more information.</source> <target state="translated">La conversione in 'LibraryImport' può modificare il comportamento e la compatibilità. Per altre informazioni, vedere {0}.</target> <note>{0} is a documentation link</note> </trans-unit> <trans-unit id="ConvertToLibraryImportWithSuffix"> <source>Convert to 'LibraryImport' with '{0}' suffix</source> <target state="translated">Converti in 'LibraryImport' con il suffisso '{0}'</target> <note /> </trans-unit> <trans-unit id="CustomMarshallerTypeMustHaveRequiredShapeTitle"> <source>Marshaller type does not have the required shape</source> <target state="translated">Il tipo di marshaller non ha la forma richiesta</target> <note /> </trans-unit> <trans-unit id="CustomMarshallerTypeMustSupportDirectionDescription"> <source>A native must set the 'Direction' property on the 'CustomTypeMarshallerAttribute' to a value that sets at least one known flag value on the 'CustomTypeMarshallerDirection' enum</source> <target state="translated">Un tipo nativo deve impostare la proprietà 'Direction' in 'CustomTypeMarshallerAttribute' su un valore che imposta almeno un valore di flag noto nell'enumerazione 'CustomTypeMarshallerDirection'</target> <note /> </trans-unit> <trans-unit id="CustomMarshallerTypeMustSupportDirectionMessage"> <source>The native type '{0}' must set the 'Direction' property on the 'CustomTypeMarshallerAttribute' to a value that sets at least one known flag value on the 'CustomTypeMarshallerDirection' enum</source> <target state="translated">Il tipo nativo '{0}' deve impostare la proprietà 'Direction' in 'CustomTypeMarshallerAttribute' su un valore che imposta almeno un valore di flag noto nell'enumerazione 'CustomTypeMarshallerDirection'</target> <note /> </trans-unit> <trans-unit id="CustomTypeMarshallerAttributeMustBeValidDescription"> <source>The 'CustomTypeMarshallerAttribute' attribute must be semantically valid</source> <target state="translated">L'attributo 'CustomTypeMarshallerAttribute' deve essere semanticamente valido</target> <note /> </trans-unit> <trans-unit id="CustomTypeMarshallerAttributeMustBeValidMessage"> <source>The 'CustomTypeMarshallerAttribute' on '{0}' is semantically invalid</source> <target state="translated">'CustomTypeMarshallerAttribute' in '{0}' non è semanticamente valido</target> <note /> </trans-unit> <trans-unit id="CustomTypeMarshallingManagedToNativeUnsupported"> <source>The specified parameter needs to be marshalled from managed to native, but the native type '{0}' does not support it.</source> <target state="translated">È necessario effettuare il marshalling del parametro specificato da gestito a nativo, ma il tipo nativo '{0}' non lo supporta.</target> <note /> </trans-unit> <trans-unit id="CustomTypeMarshallingNativeToManagedUnsupported"> <source>The specified parameter needs to be marshalled from native to managed, but the native type '{0}' does not support it.</source> <target state="translated">È necessario effettuare il marshalling del parametro specificato da nativo a gestito, ma il tipo nativo '{0}' non lo supporta.</target> <note /> </trans-unit> <trans-unit id="FreeNativeMethodProvidedShouldSpecifyUnmanagedResourcesFeatureDescription"> <source>A marshaller type that provides a 'FreeNative' method should specify that it supports the 'UnmanagedResources' feature.</source> <target state="translated">Un tipo di gestore del marshalling che fornisce un metodo 'FreeNative' deve specificare che supporta la funzionalità 'UnmanagedResources'.</target> <note /> </trans-unit> <trans-unit id="FreeNativeMethodProvidedShouldSpecifyUnmanagedResourcesFeatureMessage"> <source>The type '{0}' provides a 'FreeNative' method but does not specify that it supports the 'UnmanagedResources' feature. The method will not be used unless the feature is specified.</source> <target state="translated">Il tipo '{0}' fornisce un metodo 'FreeNative', ma non specifica che supporta la funzionalità 'UnmanagedResources'. Il metodo verrà usato solo se è specificata la funzionalità.</target> <note /> </trans-unit> <trans-unit id="FromNativeValueMethodProvidedShouldSpecifyTwoStageMarshallingFeatureDescription"> <source>A marshaller type that provides a 'FromNativeValue' method should specify that it supports the 'TwoStageMarshalling' feature.</source> <target state="translated">Un tipo di gestore del marshalling che fornisce un metodo 'FromNativeValue' deve specificare che supporta la funzionalità 'TwoStageMarshalling'.</target> <note /> </trans-unit> <trans-unit id="FromNativeValueMethodProvidedShouldSpecifyTwoStageMarshallingFeatureMessage"> <source>The type '{0}' provides a 'FromNativeValue' method but does not specify that it supports the 'TwoStageMarshalling' feature. The method will not be used unless the feature is specified.</source> <target state="translated">Il tipo '{0}' fornisce un metodo 'FromNativeValue', ma non specifica che supporta la funzionalità 'TwoStageMarshalling'. Il metodo verrà usato solo se è specificata la funzionalità.</target> <note /> </trans-unit> <trans-unit id="GetPinnableReferenceReturnTypeBlittableDescription"> <source>The return type of 'GetPinnableReference' (after accounting for 'ref') must be blittable.</source> <target state="translated">Il tipo restituito di 'GetPinnableReference' (dopo l'accounting di 'ref') deve essere copiabile da BLT.</target> <note /> </trans-unit> <trans-unit id="GetPinnableReferenceReturnTypeBlittableMessage"> <source>The dereferenced type of the return type of the 'GetPinnableReference' method must be blittable</source> <target state="translated">Il tipo dereferenziato del tipo restituito del metodo 'GetPinnableReference' deve essere copiabile da BLT</target> <note /> </trans-unit> <trans-unit id="GetPinnableReferenceShouldSupportAllocatingMarshallingFallbackDescription"> <source>A type that supports marshalling from managed to native by pinning should also support marshalling from managed to native where pinning is impossible.</source> <target state="translated">Un tipo che supporta il marshalling da gestito a nativo tramite l'aggiunta deve supportare anche il marshalling da gestito a nativo nei casi in cui l'aggiunta risulta impossibile.</target> <note /> </trans-unit> <trans-unit id="GetPinnableReferenceShouldSupportAllocatingMarshallingFallbackMessage"> <source>Type '{0}' has a 'GetPinnableReference' method but its native type does not support marshalling in scenarios where pinning is impossible</source> <target state="translated">Il tipo '{0}' include un metodo 'GetPinnableReference', ma il relativo tipo nativo non supporta il marshalling in scenari in cui l'aggiunta risulta impossibile</target> <note /> </trans-unit> <trans-unit id="InTwoStageMarshallingRequiresToNativeValueDescription"> <source>The 'TwoStageMarshalling' feature requires a 'TNativeType ToNativeValue()' method for the 'In' direction.</source> <target state="translated">La funzionalità 'TwoStageMarshalling' richiede un metodo 'TNativeType ToNativeValue()' per la direzione 'In'.</target> <note /> </trans-unit> <trans-unit id="InTwoStageMarshallingRequiresToNativeValueMessage"> <source>A marshaller type '{0}' that supports marshalling in the 'In' direction with the 'TwoStageMarshalling' feature must provide a 'ToNativeValue' instance method that returns the native value</source> <target state="translated">Un tipo di marshaller '{0}' che supporta il marshalling nella direzione 'In' con la funzionalità 'TwoStageMarshalling' deve fornire un metodo di istanza 'ToNativeValue' che restituisce il valore nativo</target> <note /> </trans-unit> <trans-unit id="InvalidAttributedMethodContainingTypeMissingModifiersMessage"> <source>Method '{0}' is contained in a type '{1}' that is not marked 'partial'. P/Invoke source generation will ignore method '{0}'.</source> <target state="translated">Il metodo '{0}' è contenuto in un tipo '{1}' non contrassegnato come 'partial'. Durante la generazione dell'origine P/Invoke il metodo '{0}' verrà ignorato.</target> <note /> </trans-unit> <trans-unit id="InvalidAttributedMethodDescription"> <source>Methods marked with 'LibraryImportAttribute' should be 'static', 'partial', and non-generic. P/Invoke source generation will ignore methods that are non-'static', non-'partial', or generic.</source> <target state="translated">I metodi contrassegnati con 'LibraryImportAttribute' devono essere 'static', 'partial' e non generici. Durante la generazione dell'origine P/Invoke i metodi non 'static', non 'partial' o generici verranno ignorati.</target> <note /> </trans-unit> <trans-unit id="InvalidAttributedMethodSignatureMessage"> <source>Method '{0}' should be 'static', 'partial', and non-generic when marked with 'LibraryImportAttribute'. P/Invoke source generation will ignore method '{0}'.</source> <target state="translated">Il metodo '{0}' deve essere 'static', 'partial' e non generico quando è contrassegnato con 'LibraryImportAttribute'. Durante la generazione dell'origine P/Invoke il metodo '{0}' verrà ignorato.</target> <note /> </trans-unit> <trans-unit id="InvalidCustomTypeMarshallerAttributeUsageTitle"> <source>Invalid `CustomTypeMarshallerAttribute` usage</source> <target state="translated">Utilizzo di 'CustomTypeMarshallerAttribute' non valido</target> <note /> </trans-unit> <trans-unit id="InvalidLibraryImportAttributeUsageTitle"> <source>Invalid 'LibraryImportAttribute' usage</source> <target state="translated">Utilizzo di 'LibraryImportAttribute' non valido</target> <note /> </trans-unit> <trans-unit id="InvalidNativeTypeTitle"> <source>Specified native type is invalid</source> <target state="translated">Il tipo nativo specificato non è valido</target> <note /> </trans-unit> <trans-unit id="InvalidSignaturesInMarshallerShapeTitle"> <source>Marshaller type has incompatible method signatures</source> <target state="translated">Il tipo marshaller ha firme di metodo incompatibili</target> <note /> </trans-unit> <trans-unit id="InvalidStringMarshallingConfigurationDescription"> <source>The configuration of 'StringMarshalling' and 'StringMarshallingCustomType' is invalid.</source> <target state="translated">La configurazione di 'StringMarshalling' e 'StringMarshallingCustomType' non è valida.</target> <note /> </trans-unit> <trans-unit id="InvalidStringMarshallingConfigurationMessage"> <source>The configuration of 'StringMarshalling' and 'StringMarshallingCustomType' on method '{0}' is invalid. {1}</source> <target state="translated">La configurazione di 'StringMarshalling' e 'StringMarshallingCustomType' nel metodo '{0}' non è valida. {1}</target> <note>{1} is a message containing additional details about what is not valid</note> </trans-unit> <trans-unit id="InvalidStringMarshallingConfigurationMissingCustomType"> <source>'StringMarshallingCustomType' must be specified when 'StringMarshalling' is set to 'StringMarshalling.Custom'.</source> <target state="translated">È necessario specificare 'StringMarshallingCustomType' quando 'StringMarshalling' è impostato su 'StringMarshalling.Custom'.</target> <note /> </trans-unit> <trans-unit id="InvalidStringMarshallingConfigurationNotCustom"> <source>'StringMarshalling' should be set to 'StringMarshalling.Custom' when 'StringMarshallingCustomType' is specified.</source> <target state="translated">'StringMarshalling' deve essere impostato su 'StringMarshalling.Custom' quando è specificato 'StringMarshallingCustomType'.</target> <note /> </trans-unit> <trans-unit id="LinearCollectionElementTypesMustMatchDescription"> <source>The element type of the 'ReadOnlySpan' returned by 'GetManagedValuesSource' must be the same as the element type returned by 'GetManagedValuesDestination'.</source> <target state="translated">Il tipo di elemento di 'ReadOnlySpan' restituito da 'GetManagedValuesSource' deve essere uguale al tipo di elemento restituito da 'GetManagedValuesDestination'.</target> <note /> </trans-unit> <trans-unit id="LinearCollectionElementTypesMustMatchMessage"> <source>The element type of the 'ReadOnlySpan' returned by 'GetManagedValuesSource' must be the same as the element type returned by 'GetManagedValuesDestination'</source> <target state="translated">Il tipo di elemento di 'ReadOnlySpan' restituito da 'GetManagedValuesSource' deve essere uguale al tipo di elemento restituito da 'GetManagedValuesDestination'</target> <note /> </trans-unit> <trans-unit id="LinearCollectionInCallerAllocatedBufferRequiresSpanConstructorDescription"> <source>A 'LinearCollection'-kind native type that supports the 'CallerAllocatedBuffer' feature must provide a three-parameter constructor taking the managed type as the first parameter, a 'Span&lt;byte&gt;' as the second parameter, and the native size of the element as the third parameter</source> <target state="translated">Un tipo nativo di tipo 'LinearCollection' che supporta la funzionalità 'CallerAllocatedBuffer' deve fornire un costruttore a tre parametri che accetta il tipo gestito come primo parametro, un elemento 'Span&lt;byte&gt;' come secondo parametro e la dimensione nativa dell'elemento come terzo parametro</target> <note /> </trans-unit> <trans-unit id="LinearCollectionInCallerAllocatedBufferRequiresSpanConstructorMessage"> <source>The type '{0}' specifies that it supports 'In' marshalling with the 'CallerAllocatedBuffer' feature for '{1}' but does not provide a three-parameter constructor that takes a '{1}' , a 'Span&lt;byte&gt;', and an 'int'</source> <target state="translated">Il tipo '{0}' specifica che supporta il marshalling 'In' con la funzionalità 'CallerAllocatedBuffer' per '{1}', ma non fornisce un costruttore a tre parametri che accetta '{1}', 'Span&lt;byte&gt;' e 'int'</target> <note /> </trans-unit> <trans-unit id="LinearCollectionInRequiresCollectionMethodsDescription"> <source>A 'LinearCollection'-kind native type that supports marshalling in the 'In' direction must provide a 'GetManagedValuesSource' that returns a 'ReadOnlySpan&lt;&gt;' and a 'GetNativeValuesDestination' method that returns a 'Span&lt;byte&gt;'.</source> <target state="translated">Il tipo nativo di tipo 'LinearCollection' che supporta il marshalling nella direzione 'In' deve fornire un elemento 'GetManagedValuesSource' che restituisce un elemento 'ReadOnlySpan&lt;&gt;' e un metodo 'GetNativeValuesDestination' che restituisce un elemento 'Span&lt;byte&gt;'.</target> <note /> </trans-unit> <trans-unit id="LinearCollectionInRequiresCollectionMethodsMessage"> <source>The type '{0}' specifies that is supports marshalling in the 'In' direction, but it does not provide a 'GetManagedValuesSource' that returns a 'ReadOnlySpan&lt;&gt;' and a 'GetNativeValuesDestination' method that returns a 'Span&lt;byte&gt;'</source> <target state="translated">Il tipo '{0}' specifica che supporta il marshalling nella direzione 'In', ma non fornisce un elemento 'GetManagedValuesSource' che restituisce un elemento 'ReadOnlySpan&lt;&gt;' e un metodo 'GetNativeValuesDestination' che restituisce un elemento 'Span&lt;byte&gt;'</target> <note /> </trans-unit> <trans-unit id="LinearCollectionInRequiresTwoParameterConstructorDescription"> <source>A 'LinearCollection'-kind native type must provide a two-parameter constructor taking the managed type as the first parameter and the native size of the element as the second parameter</source> <target state="translated">Un tipo nativo di tipo 'LinearCollection' deve fornire un costruttore a due parametri che accetta il tipo gestito come primo parametro e le dimensioni native dell'elemento come secondo parametro</target> <note /> </trans-unit> <trans-unit id="LinearCollectionInRequiresTwoParameterConstructorMessage"> <source>The type '{0}' specifies that it supports 'In' marshalling of '{1}' but does not provide a two-parameter constructor that takes a '{1}' as the first parameter and an 'int' as the second parameter</source> <target state="translated">Il tipo '{0}' specifica che supporta il marshalling 'In' di '{1}' ma non fornisce un costruttore a due parametri che accetta '{1}' come primo parametro e 'int' come secondo parametro</target> <note /> </trans-unit> <trans-unit id="LinearCollectionOutRequiresCollectionMethodsDescription"> <source>A 'LinearCollection'-kind native type that supports marshalling in the 'Out' direction must provide a 'GetManagedValuesDestination' that takes an 'int' and returns a 'Span&lt;&gt;' and a 'GetNativeValuesSource' method that takes an 'int' and rreturns a 'ReadOnlySpan&lt;byte&gt;'.</source> <target state="translated">Un tipo nativo di tipo 'LinearCollection' che supporta il marshalling nella direzione 'Out' deve fornire un metodo 'GetManagedValuesDestination' che accetta 'int' e restituisce un elemento 'Span&lt;&gt;' e un metodo 'GetNativeValuesSource' che accetta 'int' e restituisce un elemento 'ReadOnlySpan&lt;byte&gt;'.</target> <note /> </trans-unit> <trans-unit id="LinearCollectionOutRequiresCollectionMethodsMessage"> <source>The type '{0}' specifies that it supports marshalling in the 'Out' direction, but it does not provide a 'GetManagedValuesDestination' that takes an 'int' and returns a 'Span&lt;&gt;' and a 'GetNativeValuesSource' method that takes an 'int' and rreturns a 'ReadOnlySpan&lt;byte&gt;'</source> <target state="translated">Il tipo '{0}' specifica che supporta il marshalling nella direzione 'Out', ma non fornisce un metodo 'GetManagedValuesDestination' che accetta 'int' e restituisce un elemento 'Span&lt;&gt;' e un metodo 'GetNativeValuesSource' che accetta 'int' e restituisce un elemento 'ReadOnlySpan&lt;byte&gt;'</target> <note /> </trans-unit> <trans-unit id="LinearCollectionOutRequiresIntConstructorDescription"> <source>A 'LinearCollection'-kind native type that supports marshalling in the 'Out' direction must provide a constructor that takes the size of the native element as an 'int'.</source> <target state="translated">Un tipo nativo di tipo 'LinearCollection' che supporta il marshalling nella direzione 'Out' deve fornire un costruttore che accetta le dimensioni dell'elemento nativo come 'int'.</target> <note /> </trans-unit> <trans-unit id="LinearCollectionOutRequiresIntConstructorMessage"> <source>The type '{0}' specifies that it supports marshalling in the 'Out' direction, but it does not provide a constructor that takes the size of the native element as an 'int'.</source> <target state="translated">Il tipo '{0}' specifica che supporta il marshalling nella direzione 'Out', ma non fornisce un costruttore che accetta le dimensioni dell'elemento nativo come 'int'.</target> <note /> </trans-unit> <trans-unit id="MarshallerDirectionMustBeValidDescription"> <source>The specified marshaller direction must be a valid value of the 'System.Runtime.InteropServices.CustomMarshallerDirection' enum.</source> <target state="translated">La direzione del gestore del marshalling specificato deve essere un valore valido dell'enumerazione 'System.Runtime.InteropServices.CustomMarshallerDirection'.</target> <note /> </trans-unit> <trans-unit id="MarshallerDirectionMustBeValidMessage"> <source>The specified custom marshaller direction for '{0}' is invalid</source> <target state="translated">La direzione del gestore del marshalling personalizzato specificata per '{0}' non è valida</target> <note /> </trans-unit> <trans-unit id="MarshallerGetPinnableReferenceRequiresTwoStageMarshallingDescription"> <source>The use cases for 'GetPinnableReference' are not applicable in any scenarios where 'TwoStageMarshalling' is not also required.</source> <target state="translated">I casi d'uso per 'GetPinnableReference' non sono applicabili in nessuno scenario in cui non è richiesto anche 'TwoStageMarshalling'.</target> <note /> </trans-unit> <trans-unit id="MarshallerGetPinnableReferenceRequiresTwoStageMarshallingMessage"> <source>The 'GetPinnableReference' method cannot be provided on the native type '{0}' unless the 'TwoStageMarshalling' feature is also supported</source> <target state="translated">Non è possibile specificare il metodo 'GetPinnableReference' nel tipo nativo '{0}' a meno che non sia supportata anche la funzionalità 'TwoStageMarshalling'</target> <note /> </trans-unit> <trans-unit id="MarshallerKindMustBeValidDescription"> <source>The specified marshaller kind must be a valid value of the 'System.Runtime.InteropServices.CustomMarshallerKind' enum.</source> <target state="translated">Il tipo di gestore del marshalling specificato deve essere un valore valido dell'enumerazione 'System.Runtime.InteropServices.CustomMarshallerKind'.</target> <note /> </trans-unit> <trans-unit id="MarshallerKindMustBeValidMessage"> <source>The specified custom marshaller kind for '{0}' is invalid</source> <target state="translated">Il tipo del gestore del marshalling personalizzato specificata per '{0}' non è valida</target> <note /> </trans-unit> <trans-unit id="MarshallerTypeMustSpecifyManagedTypeDescription"> <source>A type with a 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' must specify a managed type</source> <target state="translated">Un tipo con 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' deve specificare un tipo gestito</target> <note /> </trans-unit> <trans-unit id="MarshallerTypeMustSpecifyManagedTypeMessage"> <source>The type '{0}' does not specify a managed type in the 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' applied to the type</source> <target state="translated">Il tipo '{0}' non specifica un tipo gestito nell'elemento 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' applicato al tipo</target> <note /> </trans-unit> <trans-unit id="MissingAllocatingMarshallingFallbackTitle"> <source>Marshaller type does not support allocating constructor</source> <target state="translated">Il tipo marshaller non supporta l'allocazione del costruttore</target> <note /> </trans-unit> <trans-unit id="NativeGenericTypeMustBeClosedOrMatchArityDescription"> <source>The native type '{0}' must be a closed generic or have the same number of generic parameters as the managed type so the emitted code can use a specific instantiation.</source> <target state="translated">Il tipo nativo '{0}' deve essere un generico chiuso o avere lo stesso numero di parametri generici del tipo gestito in modo che il codice emesso possa usare una creazione di istanza specifica.</target> <note /> </trans-unit> <trans-unit id="NativeGenericTypeMustBeClosedOrMatchArityMessage"> <source>The native type '{0}' for managed type '{1}' must be a closed generic type or have the same arity as the managed type.</source> <target state="translated">Il tipo nativo '{0}' per il tipo gestito '{1}' deve essere un tipo generico chiuso o avere lo stesso grado del tipo gestito.</target> <note /> </trans-unit> <trans-unit id="NativeTypeMustBeBlittableDescription"> <source>A native type must be blittable.</source> <target state="translated">Un tipo nativo deve essere copiabile da BLT.</target> <note /> </trans-unit> <trans-unit id="NativeTypeMustBeBlittableMessage"> <source>The native type '{0}' for type '{1}' must be blittable</source> <target state="translated">Il tipo nativo '{0}' per il tipo '{1}' deve essere copiabile da BLT</target> <note /> </trans-unit> <trans-unit id="NativeTypeMustBePointerSizedDescription"> <source>The native type must be pointer sized so the pinned result of 'GetPinnableReference' can be cast to the native type.</source> <target state="translated">Il tipo nativo deve essere dimensionato in base al puntatore in modo da poter eseguire il cast del risultato aggiunto di 'GetPinnableReference' al tipo nativo.</target> <note /> </trans-unit> <trans-unit id="NativeTypeMustBePointerSizedMessage"> <source>The native type '{0}' must be pointer sized because the managed type '{1}' has a 'GetPinnableReference' method</source> <target state="translated">Il tipo nativo '{0}' deve essere dimensionato in base al puntatore perché il tipo gestito '{1}' include un metodo 'GetPinnableReference'</target> <note /> </trans-unit> <trans-unit id="NativeTypeMustHaveCustomTypeMarshallerAttributeDescription"> <source>A native type for a given type must have the 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' that specifies this type as the managed type.</source> <target state="translated">Un tipo nativo per un tipo specificato deve includere un elemento 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' che specifica questo tipo come tipo gestito.</target> <note /> </trans-unit> <trans-unit id="NativeTypeMustHaveCustomTypeMarshallerAttributeMessage"> <source>The native type for the type '{0}' must be a type with the 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' that specifies this type as the managed type</source> <target state="translated">Il tipo nativo per il tipo '{0}' deve essere un tipo con 'System.Runtime.InteropServices.CustomTypeMarshallerAttribute' che specifica questo tipo come tipo gestito</target> <note /> </trans-unit> <trans-unit id="OutRequiresToManagedDescription"> <source>A 'Value' or 'LinearCollection'-kind native type that supports marshalling in the 'Out' direction must provide a 'ToManaged' method that returns the managed type.</source> <target state="translated">Un tipo nativo di tipo 'Value' o 'LinearCollection' che supporta il marshalling nella direzione 'Out' deve fornire un metodo 'ToManaged' che restituisce il tipo gestito.</target> <note /> </trans-unit> <trans-unit id="OutRequiresToManagedMessage"> <source>The type '{0}' specifies it supports marshalling in the 'Out' direction, but it does not provide a 'ToManaged' method that returns the managed type</source> <target state="translated">Il tipo '{0}' specifica che supporta il marshalling nella direzione 'Out', ma non fornisce un metodo 'ToManaged' che restituisce il tipo gestito</target> <note /> </trans-unit> <trans-unit id="OutTwoStageMarshallingRequiresFromNativeValueDescription"> <source>The 'TwoStageMarshalling' feature requires a 'void FromNativeValue(TNativeType value)' method for the 'Out' direction.</source> <target state="translated">Con la funzionalità 'TwoStageMarshalling' è richiesto un metodo 'void FromNativeValue(TNativeType value)' per la direzione 'Out'.</target> <note /> </trans-unit> <trans-unit id="OutTwoStageMarshallingRequiresFromNativeValueMessage"> <source>The marshaller type '{0}' supports marshalling in the 'Out' direction with the 'TwoStageMarshalling' feature, but it does not provide a 'FromNativeValue' instance method that returns 'void' and takes one parameter.</source> <target state="translated">Il tipo di gestore del marshalling '{0}' supporta il marshalling nella direzione 'Out' con la funzionalità 'TwoStageMarshalling', ma non fornisce un metodo di istanza 'FromNativeValue' che restituisce 'void' e accetta un solo parametro.</target> <note /> </trans-unit> <trans-unit id="ProvidedMethodsNotSpecifiedInFeaturesTitle"> <source>Marshaller type defines a well-known method without specifying support for the corresponding feature</source> <target state="translated">Il tipo marshaller definisce un metodo noto senza specificare il supporto per la funzionalità corrispondente</target> <note /> </trans-unit> <trans-unit id="RefNativeValueUnsupportedDescription"> <source>The 'Value' property must not be a 'ref' or 'readonly ref' property.</source> <target state="translated">La proprietà 'Value' non deve essere una proprietà 'ref' o 'readonly ref'.</target> <note /> </trans-unit> <trans-unit id="RefNativeValueUnsupportedMessage"> <source>The 'Value' property on the native type '{0}' must not be a 'ref' or 'readonly ref' property.</source> <target state="translated">La proprietà 'Value' nel tipo nativo '{0}' non deve essere una proprietà 'ref' o 'readonly ref'.</target> <note /> </trans-unit> <trans-unit id="SafeHandleByRefMustBeConcrete"> <source>An abstract type derived from 'SafeHandle' cannot be marshalled by reference. The provided type must be concrete.</source> <target state="translated">Non è possibile effettuare il marshalling per riferimento di un tipo astratto derivato da 'SafeHandle'. Il tipo specificato deve essere concreto.</target> <note /> </trans-unit> <trans-unit id="ToNativeValueMethodProvidedShouldSpecifyTwoStageMarshallingFeatureDescription"> <source>A marshaller type that provides a 'ToNativeValue' method should specify that it supports the 'TwoStageMarshalling' feature.</source> <target state="translated">Un tipo di gestore del marshalling che fornisce un metodo 'ToNativeValue' deve specificare che supporta la funzionalità 'TwoStageMarshalling'.</target> <note /> </trans-unit> <trans-unit id="ToNativeValueMethodProvidedShouldSpecifyTwoStageMarshallingFeatureMessage"> <source>The type '{0}' provides a 'ToNativeValue' method but does not specify that it supports the 'TwoStageMarshalling' feature. The method will not be used unless the feature is specified.</source> <target state="translated">Il tipo '{0}' fornisce un metodo 'ToNativeValue', ma non specifica che supporta la funzionalità 'TwoStageMarshalling'. Il metodo verrà usato solo se è specificata la funzionalità.</target> <note /> </trans-unit> <trans-unit id="TwoStageMarshallingNativeTypesMustMatchDescription"> <source>The return type of 'ToNativeValue' and the parameter type of 'FromNativeValue' must be the same.</source> <target state="translated">Il tipo restituito di 'ToNativeValue' e il tipo di parametro di 'FromNativeValue' devono essere uguali.</target> <note /> </trans-unit> <trans-unit id="TwoStageMarshallingNativeTypesMustMatchMessage"> <source>The return type of 'ToNativeValue' and the parameter type of 'FromNativeValue' must be the same</source> <target state="translated">Il tipo restituito di 'ToNativeValue' e il tipo di parametro di 'FromNativeValue' devono essere uguali</target> <note /> </trans-unit> <trans-unit id="TypeNotSupportedDescription"> <source>For types that are not supported by source-generated P/Invokes, the resulting P/Invoke will rely on the underlying runtime to marshal the specified type.</source> <target state="translated">Per i tipi non supportati da P/Invoke generati dall'origine, il P/Invoke risultante si baserà sul runtime sottostante per effettuare il marshalling del tipo specificato.</target> <note /> </trans-unit> <trans-unit id="TypeNotSupportedMessageParameter"> <source>The type '{0}' is not supported by source-generated P/Invokes. The generated source will not handle marshalling of parameter '{1}'.</source> <target state="translated">Il tipo '{0}' non è supportato dai P/Invoke generati dall'origine. L'origine generata non gestirà il marshalling del parametro '{1}'.</target> <note /> </trans-unit> <trans-unit id="TypeNotSupportedMessageParameterWithDetails"> <source>{0} The generated source will not handle marshalling of parameter '{1}'.</source> <target state="translated">{0} L'origine generata non gestirà il marshalling del parametro '{1}'.</target> <note>{0} is a message containing additional details about what is not supported {1} is the name of the parameter</note> </trans-unit> <trans-unit id="TypeNotSupportedMessageReturn"> <source>The type '{0}' is not supported by source-generated P/Invokes. The generated source will not handle marshalling of the return value of method '{1}'.</source> <target state="translated">Il tipo '{0}' non è supportato dai P/Invoke generati dall'origine. L'origine generata non gestirà il marshalling del valore restituito del metodo '{1}'.</target> <note /> </trans-unit> <trans-unit id="TypeNotSupportedMessageReturnWithDetails"> <source>{0} The generated source will not handle marshalling of the return value of method '{1}'.</source> <target state="translated">{0} L'origine generata non gestirà il marshalling del valore restituito del metodo '{1}'.</target> <note>{0} is a message containing additional details about what is not supported {1} is the name of the method</note> </trans-unit> <trans-unit id="TypeNotSupportedTitle"> <source>Specified type is not supported by source-generated P/Invokes</source> <target state="translated">Il tipo specificato non è supportato dai P/Invoke generati dall'origine</target> <note /> </trans-unit> <trans-unit id="UnmanagedResourcesRequiresFreeNativeDescription"> <source>The 'UnmanagedResources' feature requires a 'void FreeNative()' method.</source> <target state="translated">Con la funzionalità 'UnmanagedResources' è richiesto un metodo 'void FreeNative()'.</target> <note /> </trans-unit> <trans-unit id="UnmanagedResourcesRequiresFreeNativeMessage"> <source>The marshaller type '{0}' supports marshalling with the 'UnmanagedResources' feature, but it does not provide a parameterless 'FreeNative' instance method that returns 'void'</source> <target state="translated">Il tipo di gestore del marshalling '{0}' supporta il marshalling con la funzionalità 'UnmanagedResources', ma non fornisce un metodo di istanza 'FreeNative' senza parametri che restituisce 'void'</target> <note /> </trans-unit> <trans-unit id="ValueInCallerAllocatedBufferRequiresSpanConstructorDescription"> <source>A 'Value'-kind native type that supports the 'CallerAllocatedBuffer' feature must provide a two-parameter constructor taking the managed type and a 'Span' of an 'unmanaged' type as parameters</source> <target state="translated">Un tipo nativo di tipo 'Value' che supporta la funzionalità 'CallerAllocatedBuffer' deve fornire un costruttore a due parametri che accetta il tipo gestito e un 'Span' di un tipo 'non gestito' come parametri</target> <note /> </trans-unit> <trans-unit id="ValueInCallerAllocatedBufferRequiresSpanConstructorMessage"> <source>The type '{0}' specifies that it supports 'In' marshalling with the 'CallerAllocatedBuffer' feature for '{1}' but does not provide a two-parameter constructor that takes a '{1}' and 'Span' of an 'unmanaged' type as parameters</source> <target state="new">The type '{0}' specifies that it supports 'In' marshalling with the 'CallerAllocatedBuffer' feature for '{1}' but does not provide a two-parameter constructor that takes a '{1}' and 'Span' of an 'unmanaged' type as parameters</target> <note /> </trans-unit> <trans-unit id="ValueInRequiresOneParameterConstructorDescription"> <source>A 'Value'-kind native type must provide a one-parameter constructor taking the managed type as a parameter</source> <target state="translated">Un tipo nativo di tipo 'Value' deve fornire un costruttore a un parametro che accetta il tipo gestito come parametro</target> <note /> </trans-unit> <trans-unit id="ValueInRequiresOneParameterConstructorMessage"> <source>The type '{0}' specifies that it supports 'In' marshalling of '{1}' but does not provide a one-parameter constructor that takes a '{1}' as a parameter</source> <target state="translated">Il tipo '{0}' specifica che supporta il marshalling 'In' di '{1}' ma non fornisce un costruttore con un solo parametro che accetta '{1}' come parametro</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltScenarios/EXslt/datetime-max.xsl
<?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:date2="http://gotdotnet.com/exslt/dates-and-times"> <xsl:output indent="yes" omit-xml-declaration="yes"/> <xsl:template match="data"> <out> <test1> <xsl:value-of select="date2:max(timespan)"/> </test1> <test2> <xsl:value-of select="date2:max(/no/such/nodes)"/> </test2> <test2> <xsl:value-of select="date2:max(bad-data)"/> </test2> </out> </xsl:template> </xsl:stylesheet>
<?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:date2="http://gotdotnet.com/exslt/dates-and-times"> <xsl:output indent="yes" omit-xml-declaration="yes"/> <xsl:template match="data"> <out> <test1> <xsl:value-of select="date2:max(timespan)"/> </test1> <test2> <xsl:value-of select="date2:max(/no/such/nodes)"/> </test2> <test2> <xsl:value-of select="date2:max(bad-data)"/> </test2> </out> </xsl:template> </xsl:stylesheet>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/native/corehost/lib_static.cmake
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the MIT license. project(lib${DOTNET_PROJECT_NAME}) include(${CMAKE_CURRENT_LIST_DIR}/common.cmake) add_definitions(-D_NO_ASYNCRTIMP) add_definitions(-D_NO_PPLXIMP) add_definitions(-DEXPORT_SHARED_API=1) if (BUILD_OBJECT_LIBRARY) add_library(lib${DOTNET_PROJECT_NAME} OBJECT ${SOURCES} ${RESOURCES}) else () add_library(lib${DOTNET_PROJECT_NAME} STATIC ${SOURCES} ${RESOURCES}) endif () set_target_properties(lib${DOTNET_PROJECT_NAME} PROPERTIES MACOSX_RPATH TRUE) set_target_properties(lib${DOTNET_PROJECT_NAME} PROPERTIES PREFIX "") set_common_libs("lib-static")
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the MIT license. project(lib${DOTNET_PROJECT_NAME}) include(${CMAKE_CURRENT_LIST_DIR}/common.cmake) add_definitions(-D_NO_ASYNCRTIMP) add_definitions(-D_NO_PPLXIMP) add_definitions(-DEXPORT_SHARED_API=1) if (BUILD_OBJECT_LIBRARY) add_library(lib${DOTNET_PROJECT_NAME} OBJECT ${SOURCES} ${RESOURCES}) else () add_library(lib${DOTNET_PROJECT_NAME} STATIC ${SOURCES} ${RESOURCES}) endif () set_target_properties(lib${DOTNET_PROJECT_NAME} PROPERTIES MACOSX_RPATH TRUE) set_target_properties(lib${DOTNET_PROJECT_NAME} PROPERTIES PREFIX "") set_common_libs("lib-static")
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/jit64/valuetypes/nullable/box-unbox/box-unbox/box-unbox038.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // <Area> Nullable - Box-Unbox </Area> // <Title> Nullable type with unbox box expr </Title> // <Description> // checking type of ImplementOneInterface using is operator // </Description> // <RelatedBugs> </RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQ(object o) { return Helper.Compare((ImplementOneInterface)o, Helper.Create(default(ImplementOneInterface))); } private static bool BoxUnboxToQ(object o) { return Helper.Compare((ImplementOneInterface?)o, Helper.Create(default(ImplementOneInterface))); } private static int Main() { ImplementOneInterface? s = Helper.Create(default(ImplementOneInterface)); if (BoxUnboxToNQ(s) && BoxUnboxToQ(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // <Area> Nullable - Box-Unbox </Area> // <Title> Nullable type with unbox box expr </Title> // <Description> // checking type of ImplementOneInterface using is operator // </Description> // <RelatedBugs> </RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQ(object o) { return Helper.Compare((ImplementOneInterface)o, Helper.Create(default(ImplementOneInterface))); } private static bool BoxUnboxToQ(object o) { return Helper.Compare((ImplementOneInterface?)o, Helper.Create(default(ImplementOneInterface))); } private static int Main() { ImplementOneInterface? s = Helper.Create(default(ImplementOneInterface)); if (BoxUnboxToNQ(s) && BoxUnboxToQ(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Symbols/AggregateSymbol.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; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { // Name used for AGGDECLs in the symbol table. // AggregateSymbol - a symbol representing an aggregate type. These are classes, // interfaces, and structs. Parent is a namespace or class. Children are methods, // properties, and member variables, and types (including its own AGGTYPESYMs). internal sealed class AggregateSymbol : NamespaceOrAggregateSymbol { public Type AssociatedSystemType; public Assembly AssociatedAssembly; // The instance type. Created when first needed. private AggregateType _atsInst; private AggregateType _pBaseClass; // For a class/struct/enum, the base class. For iface: unused. private AggregateType _pUnderlyingType; // For enum, the underlying type. For iface, the resolved CoClass. Not used for class/struct. private TypeArray _ifaces; // The explicit base interfaces for a class or interface. private TypeArray _ifacesAll; // Recursive closure of base interfaces ordered so an iface appears before all of its base ifaces. private TypeArray _typeVarsThis; // Type variables for this generic class, as declarations. private TypeArray _typeVarsAll; // The type variables for this generic class and all containing classes. // First UD conversion operator. This chain is for this type only (not base types). // The hasConversion flag indicates whether this or any base types have UD conversions. private MethodSymbol _pConvFirst; // ------------------------------------------------------------------------ // // Put members that are bits under here in a contiguous section. // // ------------------------------------------------------------------------ private AggKindEnum _aggKind; // Where this came from - fabricated, source, import // Fabricated AGGs have isSource == true but hasParseTree == false. // N.B.: in incremental builds, it is quite possible for // isSource==TRUE and hasParseTree==FALSE. Be // sure you use the correct variable for what you are trying to do! // Predefined private bool _isPredefined; // A special predefined type. private PredefinedType _iPredef; // index of the predefined type, if isPredefined. // Flags private bool _isAbstract; // Can it be instantiated? private bool _isSealed; // Can it be derived from? // Constructors private bool _hasPubNoArgCtor; // Whether it has a public instance constructor taking no args // User defined operators private bool _isSkipUDOps; // Never check for user defined operators on this type (eg, decimal, string, delegate). // When this is unset we don't know if we have conversions. When this // is set it indicates if this type or any base type has user defined // conversion operators private bool? _hasConversion; // ---------------------------------------------------------------------------- // AggregateSymbol // ---------------------------------------------------------------------------- public AggregateSymbol GetBaseAgg() { return _pBaseClass?.OwningAggregate; } public AggregateType getThisType() { if (_atsInst == null) { Debug.Assert(GetTypeVars() == GetTypeVarsAll() || isNested()); AggregateType pOuterType = isNested() ? GetOuterAgg().getThisType() : null; _atsInst = TypeManager.GetAggregate(this, pOuterType, GetTypeVars()); } //Debug.Assert(GetTypeVars().Size == atsInst.GenericArguments.Count); return _atsInst; } public bool FindBaseAgg(AggregateSymbol agg) { for (AggregateSymbol aggT = this; aggT != null; aggT = aggT.GetBaseAgg()) { if (aggT == agg) return true; } return false; } public NamespaceOrAggregateSymbol Parent => parent as NamespaceOrAggregateSymbol; public bool isNested() => parent is AggregateSymbol; public AggregateSymbol GetOuterAgg() => parent as AggregateSymbol; public bool isPredefAgg(PredefinedType pt) { return _isPredefined && (PredefinedType)_iPredef == pt; } // ---------------------------------------------------------------------------- // The following are the Accessor functions for AggregateSymbol. // ---------------------------------------------------------------------------- public AggKindEnum AggKind() { return (AggKindEnum)_aggKind; } public void SetAggKind(AggKindEnum aggKind) { // NOTE: When importing can demote types: // - enums with no underlying type go to struct // - delegates which are abstract or have no .ctor/Invoke method goto class _aggKind = aggKind; //An interface is always abstract if (aggKind == AggKindEnum.Interface) { SetAbstract(true); } } public bool IsClass() { return AggKind() == AggKindEnum.Class; } public bool IsDelegate() { return AggKind() == AggKindEnum.Delegate; } public bool IsInterface() { return AggKind() == AggKindEnum.Interface; } public bool IsStruct() { return AggKind() == AggKindEnum.Struct; } public bool IsEnum() { return AggKind() == AggKindEnum.Enum; } public bool IsValueType() { return AggKind() == AggKindEnum.Struct || AggKind() == AggKindEnum.Enum; } public bool IsRefType() { return AggKind() == AggKindEnum.Class || AggKind() == AggKindEnum.Interface || AggKind() == AggKindEnum.Delegate; } public bool IsStatic() { return (_isAbstract && _isSealed); } public bool IsAbstract() { return _isAbstract; } public void SetAbstract(bool @abstract) { _isAbstract = @abstract; } public bool IsPredefined() { return _isPredefined; } public void SetPredefined(bool predefined) { _isPredefined = predefined; } public PredefinedType GetPredefType() { return (PredefinedType)_iPredef; } public void SetPredefType(PredefinedType predef) { _iPredef = predef; } public bool IsSealed() { return _isSealed == true; } public void SetSealed(bool @sealed) { _isSealed = @sealed; } //////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] public bool HasConversion() { SymbolTable.AddConversionsForType(AssociatedSystemType); if (!_hasConversion.HasValue) { // ok, we tried defining all the conversions, and we didn't get anything // for this type. However, we will still think this type has conversions // if it's base type has conversions. _hasConversion = GetBaseAgg() != null && GetBaseAgg().HasConversion(); } return _hasConversion.Value; } //////////////////////////////////////////////////////////////////////////////// public void SetHasConversion() { _hasConversion = true; } //////////////////////////////////////////////////////////////////////////////// public bool HasPubNoArgCtor() { return _hasPubNoArgCtor == true; } public void SetHasPubNoArgCtor(bool hasPubNoArgCtor) { _hasPubNoArgCtor = hasPubNoArgCtor; } public bool IsSkipUDOps() { return _isSkipUDOps == true; } public void SetSkipUDOps(bool skipUDOps) { _isSkipUDOps = skipUDOps; } public TypeArray GetTypeVars() { return _typeVarsThis; } public void SetTypeVars(TypeArray typeVars) { if (typeVars == null) { _typeVarsThis = null; _typeVarsAll = null; } else { TypeArray outerTypeVars; if (GetOuterAgg() != null) { Debug.Assert(GetOuterAgg().GetTypeVars() != null); Debug.Assert(GetOuterAgg().GetTypeVarsAll() != null); outerTypeVars = GetOuterAgg().GetTypeVarsAll(); } else { outerTypeVars = TypeArray.Empty; } _typeVarsThis = typeVars; _typeVarsAll = TypeArray.Concat(outerTypeVars, typeVars); } } public TypeArray GetTypeVarsAll() { return _typeVarsAll; } public AggregateType GetBaseClass() { return _pBaseClass; } public void SetBaseClass(AggregateType baseClass) { _pBaseClass = baseClass; } public AggregateType GetUnderlyingType() { return _pUnderlyingType; } public void SetUnderlyingType(AggregateType underlyingType) { _pUnderlyingType = underlyingType; } public TypeArray GetIfaces() { return _ifaces; } public void SetIfaces(TypeArray ifaces) { _ifaces = ifaces; } public TypeArray GetIfacesAll() { return _ifacesAll; } public void SetIfacesAll(TypeArray ifacesAll) { _ifacesAll = ifacesAll; } public MethodSymbol GetFirstUDConversion() { return _pConvFirst; } public void SetFirstUDConversion(MethodSymbol conv) { _pConvFirst = conv; } public bool InternalsVisibleTo(Assembly assembly) => TypeManager.InternalsVisibleTo(AssociatedAssembly, assembly); } }
// 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; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { // Name used for AGGDECLs in the symbol table. // AggregateSymbol - a symbol representing an aggregate type. These are classes, // interfaces, and structs. Parent is a namespace or class. Children are methods, // properties, and member variables, and types (including its own AGGTYPESYMs). internal sealed class AggregateSymbol : NamespaceOrAggregateSymbol { public Type AssociatedSystemType; public Assembly AssociatedAssembly; // The instance type. Created when first needed. private AggregateType _atsInst; private AggregateType _pBaseClass; // For a class/struct/enum, the base class. For iface: unused. private AggregateType _pUnderlyingType; // For enum, the underlying type. For iface, the resolved CoClass. Not used for class/struct. private TypeArray _ifaces; // The explicit base interfaces for a class or interface. private TypeArray _ifacesAll; // Recursive closure of base interfaces ordered so an iface appears before all of its base ifaces. private TypeArray _typeVarsThis; // Type variables for this generic class, as declarations. private TypeArray _typeVarsAll; // The type variables for this generic class and all containing classes. // First UD conversion operator. This chain is for this type only (not base types). // The hasConversion flag indicates whether this or any base types have UD conversions. private MethodSymbol _pConvFirst; // ------------------------------------------------------------------------ // // Put members that are bits under here in a contiguous section. // // ------------------------------------------------------------------------ private AggKindEnum _aggKind; // Where this came from - fabricated, source, import // Fabricated AGGs have isSource == true but hasParseTree == false. // N.B.: in incremental builds, it is quite possible for // isSource==TRUE and hasParseTree==FALSE. Be // sure you use the correct variable for what you are trying to do! // Predefined private bool _isPredefined; // A special predefined type. private PredefinedType _iPredef; // index of the predefined type, if isPredefined. // Flags private bool _isAbstract; // Can it be instantiated? private bool _isSealed; // Can it be derived from? // Constructors private bool _hasPubNoArgCtor; // Whether it has a public instance constructor taking no args // User defined operators private bool _isSkipUDOps; // Never check for user defined operators on this type (eg, decimal, string, delegate). // When this is unset we don't know if we have conversions. When this // is set it indicates if this type or any base type has user defined // conversion operators private bool? _hasConversion; // ---------------------------------------------------------------------------- // AggregateSymbol // ---------------------------------------------------------------------------- public AggregateSymbol GetBaseAgg() { return _pBaseClass?.OwningAggregate; } public AggregateType getThisType() { if (_atsInst == null) { Debug.Assert(GetTypeVars() == GetTypeVarsAll() || isNested()); AggregateType pOuterType = isNested() ? GetOuterAgg().getThisType() : null; _atsInst = TypeManager.GetAggregate(this, pOuterType, GetTypeVars()); } //Debug.Assert(GetTypeVars().Size == atsInst.GenericArguments.Count); return _atsInst; } public bool FindBaseAgg(AggregateSymbol agg) { for (AggregateSymbol aggT = this; aggT != null; aggT = aggT.GetBaseAgg()) { if (aggT == agg) return true; } return false; } public NamespaceOrAggregateSymbol Parent => parent as NamespaceOrAggregateSymbol; public bool isNested() => parent is AggregateSymbol; public AggregateSymbol GetOuterAgg() => parent as AggregateSymbol; public bool isPredefAgg(PredefinedType pt) { return _isPredefined && (PredefinedType)_iPredef == pt; } // ---------------------------------------------------------------------------- // The following are the Accessor functions for AggregateSymbol. // ---------------------------------------------------------------------------- public AggKindEnum AggKind() { return (AggKindEnum)_aggKind; } public void SetAggKind(AggKindEnum aggKind) { // NOTE: When importing can demote types: // - enums with no underlying type go to struct // - delegates which are abstract or have no .ctor/Invoke method goto class _aggKind = aggKind; //An interface is always abstract if (aggKind == AggKindEnum.Interface) { SetAbstract(true); } } public bool IsClass() { return AggKind() == AggKindEnum.Class; } public bool IsDelegate() { return AggKind() == AggKindEnum.Delegate; } public bool IsInterface() { return AggKind() == AggKindEnum.Interface; } public bool IsStruct() { return AggKind() == AggKindEnum.Struct; } public bool IsEnum() { return AggKind() == AggKindEnum.Enum; } public bool IsValueType() { return AggKind() == AggKindEnum.Struct || AggKind() == AggKindEnum.Enum; } public bool IsRefType() { return AggKind() == AggKindEnum.Class || AggKind() == AggKindEnum.Interface || AggKind() == AggKindEnum.Delegate; } public bool IsStatic() { return (_isAbstract && _isSealed); } public bool IsAbstract() { return _isAbstract; } public void SetAbstract(bool @abstract) { _isAbstract = @abstract; } public bool IsPredefined() { return _isPredefined; } public void SetPredefined(bool predefined) { _isPredefined = predefined; } public PredefinedType GetPredefType() { return (PredefinedType)_iPredef; } public void SetPredefType(PredefinedType predef) { _iPredef = predef; } public bool IsSealed() { return _isSealed == true; } public void SetSealed(bool @sealed) { _isSealed = @sealed; } //////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] public bool HasConversion() { SymbolTable.AddConversionsForType(AssociatedSystemType); if (!_hasConversion.HasValue) { // ok, we tried defining all the conversions, and we didn't get anything // for this type. However, we will still think this type has conversions // if it's base type has conversions. _hasConversion = GetBaseAgg() != null && GetBaseAgg().HasConversion(); } return _hasConversion.Value; } //////////////////////////////////////////////////////////////////////////////// public void SetHasConversion() { _hasConversion = true; } //////////////////////////////////////////////////////////////////////////////// public bool HasPubNoArgCtor() { return _hasPubNoArgCtor == true; } public void SetHasPubNoArgCtor(bool hasPubNoArgCtor) { _hasPubNoArgCtor = hasPubNoArgCtor; } public bool IsSkipUDOps() { return _isSkipUDOps == true; } public void SetSkipUDOps(bool skipUDOps) { _isSkipUDOps = skipUDOps; } public TypeArray GetTypeVars() { return _typeVarsThis; } public void SetTypeVars(TypeArray typeVars) { if (typeVars == null) { _typeVarsThis = null; _typeVarsAll = null; } else { TypeArray outerTypeVars; if (GetOuterAgg() != null) { Debug.Assert(GetOuterAgg().GetTypeVars() != null); Debug.Assert(GetOuterAgg().GetTypeVarsAll() != null); outerTypeVars = GetOuterAgg().GetTypeVarsAll(); } else { outerTypeVars = TypeArray.Empty; } _typeVarsThis = typeVars; _typeVarsAll = TypeArray.Concat(outerTypeVars, typeVars); } } public TypeArray GetTypeVarsAll() { return _typeVarsAll; } public AggregateType GetBaseClass() { return _pBaseClass; } public void SetBaseClass(AggregateType baseClass) { _pBaseClass = baseClass; } public AggregateType GetUnderlyingType() { return _pUnderlyingType; } public void SetUnderlyingType(AggregateType underlyingType) { _pUnderlyingType = underlyingType; } public TypeArray GetIfaces() { return _ifaces; } public void SetIfaces(TypeArray ifaces) { _ifaces = ifaces; } public TypeArray GetIfacesAll() { return _ifacesAll; } public void SetIfacesAll(TypeArray ifacesAll) { _ifacesAll = ifacesAll; } public MethodSymbol GetFirstUDConversion() { return _pConvFirst; } public void SetFirstUDConversion(MethodSymbol conv) { _pConvFirst = conv; } public bool InternalsVisibleTo(Assembly assembly) => TypeManager.InternalsVisibleTo(AssociatedAssembly, assembly); } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/HardwareIntrinsics/X86/Avx2/AlignRight.Int32.0.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 AlignRightInt320() { var test = new ImmBinaryOpTest__AlignRightInt320(); 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 ImmBinaryOpTest__AlignRightInt320 { private struct TestStruct { public Vector256<Int32> _fld1; public Vector256<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<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__AlignRightInt320 testClass) { var result = Avx2.AlignRight(_fld1, _fld2, 0); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector256<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static ImmBinaryOpTest__AlignRightInt320() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); } public ImmBinaryOpTest__AlignRightInt320() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<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 SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[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.AlignRight( Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr), 0 ); 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.AlignRight( Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)), 0 ); 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.AlignRight( Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)), 0 ); 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.AlignRight), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(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.AlignRight), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(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.AlignRight), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.AlignRight( _clsVar1, _clsVar2, 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); var result = Avx2.AlignRight(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.AlignRight(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.AlignRight(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__AlignRightInt320(); var result = Avx2.AlignRight(test._fld1, test._fld2, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.AlignRight(_fld1, _fld2, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.AlignRight(test._fld1, test._fld2, 0); 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 RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int32> left, Vector256<Int32> right, 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]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, 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>(left), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != right[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != right[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.AlignRight)}<Int32>(Vector256<Int32>.0, Vector256<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\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 AlignRightInt320() { var test = new ImmBinaryOpTest__AlignRightInt320(); 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 ImmBinaryOpTest__AlignRightInt320 { private struct TestStruct { public Vector256<Int32> _fld1; public Vector256<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<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__AlignRightInt320 testClass) { var result = Avx2.AlignRight(_fld1, _fld2, 0); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector256<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static ImmBinaryOpTest__AlignRightInt320() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); } public ImmBinaryOpTest__AlignRightInt320() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<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 SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[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.AlignRight( Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr), 0 ); 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.AlignRight( Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)), 0 ); 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.AlignRight( Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)), 0 ); 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.AlignRight), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(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.AlignRight), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(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.AlignRight), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)), (byte)0 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.AlignRight( _clsVar1, _clsVar2, 0 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); var result = Avx2.AlignRight(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.AlignRight(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.AlignRight(left, right, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__AlignRightInt320(); var result = Avx2.AlignRight(test._fld1, test._fld2, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.AlignRight(_fld1, _fld2, 0); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.AlignRight(test._fld1, test._fld2, 0); 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 RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int32> left, Vector256<Int32> right, 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]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, 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>(left), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != right[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != right[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.AlignRight)}<Int32>(Vector256<Int32>.0, Vector256<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
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.Core.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.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Text; using System.Threading; namespace System.Resources { public partial class ResourceReader { private readonly bool _permitDeserialization; // can deserialize BinaryFormatted resources private object? _binaryFormatter; // binary formatter instance to use for deserializing // statics used to dynamically call into BinaryFormatter // When successfully located s_binaryFormatterType will point to the BinaryFormatter type // and s_deserializeMethod will point to an unbound delegate to the deserialize method. [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] private static Type? s_binaryFormatterType; private static Func<object?, Stream, object>? s_deserializeMethod; // This is the constructor the RuntimeResourceSet calls, // passing in the stream to read from and the RuntimeResourceSet's // internal hash table (hash table of names with file offsets // and values, coupled to this ResourceReader). internal ResourceReader(Stream stream, Dictionary<string, ResourceLocator> resCache, bool permitDeserialization) { Debug.Assert(stream != null, "Need a stream!"); Debug.Assert(stream.CanRead, "Stream should be readable!"); Debug.Assert(resCache != null, "Need a Dictionary!"); _resCache = resCache; _store = new BinaryReader(stream, Encoding.UTF8); _ums = stream as UnmanagedMemoryStream; _permitDeserialization = permitDeserialization; ReadResources(); } [UnconditionalSuppressMessage("AotAnalysis", "IL3050:RequiresDynamicCode", Justification = "InitializeBinaryFormatter will get trimmed out when AllowCustomResourceTypes is set to false. " + "When set to true, we will already throw a warning for this feature switch, so we suppress this one in order for" + "the user to only get one error.")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "InitializeBinaryFormatter will get trimmed out when AllowCustomResourceTypes is set to false. " + "When set to true, we will already throw a warning for this feature switch, so we suppress this one in order for" + "the user to only get one error.")] private object DeserializeObject(int typeIndex) { if (!AllowCustomResourceTypes) { throw new NotSupportedException(SR.ResourceManager_ReflectionNotAllowed); } if (!_permitDeserialization) { throw new NotSupportedException(SR.NotSupported_ResourceObjectSerialization); } if (Volatile.Read(ref _binaryFormatter) is null) { if (!InitializeBinaryFormatter()) { // The linker trimmed away the BinaryFormatter implementation and we can't call into it. // We'll throw an exception with the same text that BinaryFormatter would have thrown // had we been able to call into it. Keep this resource string in sync with the same // resource from the Formatters assembly. throw new NotSupportedException(SR.BinaryFormatter_SerializationDisallowed); } } Type type = FindType(typeIndex); object graph = s_deserializeMethod!(_binaryFormatter, _store.BaseStream); // guard against corrupted resources if (graph.GetType() != type) throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResType_SerBlobMismatch, type.FullName, graph.GetType().FullName)); return graph; } // Issue https://github.com/dotnet/runtime/issues/39290 tracks finding an alternative to BinaryFormatter [RequiresDynamicCode("The native code for this instantiation might not be available at runtime.")] [RequiresUnreferencedCode("The CustomResourceTypesSupport feature switch has been enabled for this app which is being trimmed. " + "Custom readers as well as custom objects on the resources file are not observable by the trimmer and so required assemblies, types and members may be removed.")] private bool InitializeBinaryFormatter() { // If BinaryFormatter support is disabled for the app, the linker will replace this entire // method body with "return false;", skipping all reflection code below. if (Volatile.Read(ref s_binaryFormatterType) is null || Volatile.Read(ref s_deserializeMethod) is null) { Type binaryFormatterType = Type.GetType("System.Runtime.Serialization.Formatters.Binary.BinaryFormatter, System.Runtime.Serialization.Formatters", throwOnError: true)!; MethodInfo? binaryFormatterDeserialize = binaryFormatterType.GetMethod("Deserialize", new[] { typeof(Stream) }); Func<object?, Stream, object>? deserializeMethod = (Func<object?, Stream, object>?) typeof(ResourceReader) .GetMethod(nameof(CreateUntypedDelegate), BindingFlags.NonPublic | BindingFlags.Static) ?.MakeGenericMethod(binaryFormatterType) .Invoke(null, new[] { binaryFormatterDeserialize }); Interlocked.CompareExchange(ref s_binaryFormatterType, binaryFormatterType, null); Interlocked.CompareExchange(ref s_deserializeMethod, deserializeMethod, null); } Volatile.Write(ref _binaryFormatter, Activator.CreateInstance(s_binaryFormatterType!)); return s_deserializeMethod != null; } // generic method that we specialize at runtime once we've loaded the BinaryFormatter type // permits creating an unbound delegate so that we can avoid reflection after the initial // lightup code completes. private static Func<object, Stream, object> CreateUntypedDelegate<TInstance>(MethodInfo method) { Func<TInstance, Stream, object> typedDelegate = (Func<TInstance, Stream, object>)Delegate.CreateDelegate(typeof(Func<TInstance, Stream, object>), null, method); return (obj, stream) => typedDelegate((TInstance)obj, stream); } private static bool ValidateReaderType(string readerType) { return ResourceManager.IsDefaultType(readerType, ResourceManager.ResReaderTypeName); } public void GetResourceData(string resourceName, out string resourceType, out byte[] resourceData) { ArgumentNullException.ThrowIfNull(resourceName); if (_resCache == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed); // Get the type information from the data section. Also, // sort all of the data section's indexes to compute length of // the serialized data for this type (making sure to subtract // off the length of the type code). int[] sortedDataPositions = new int[_numResources]; int dataPos = FindPosForResource(resourceName); if (dataPos == -1) { throw new ArgumentException(SR.Format(SR.Arg_ResourceNameNotExist, resourceName)); } lock (this) { // Read all the positions of data within the data section. for (int i = 0; i < _numResources; i++) { _store.BaseStream.Position = _nameSectionOffset + GetNamePosition(i); // Skip over name of resource int numBytesToSkip = _store.Read7BitEncodedInt(); if (numBytesToSkip < 0) { throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesNameInvalidOffset, numBytesToSkip)); } _store.BaseStream.Position += numBytesToSkip; int dPos = _store.ReadInt32(); if (dPos < 0 || dPos >= _store.BaseStream.Length - _dataSectionOffset) { throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesDataInvalidOffset, dPos)); } sortedDataPositions[i] = dPos; } Array.Sort(sortedDataPositions); int index = Array.BinarySearch(sortedDataPositions, dataPos); Debug.Assert(index >= 0 && index < _numResources, "Couldn't find data position within sorted data positions array!"); long nextData = (index < _numResources - 1) ? sortedDataPositions[index + 1] + _dataSectionOffset : _store.BaseStream.Length; int len = (int)(nextData - (dataPos + _dataSectionOffset)); Debug.Assert(len >= 0 && len <= (int)_store.BaseStream.Length - dataPos + _dataSectionOffset, "Length was negative or outside the bounds of the file!"); // Read type code then byte[] _store.BaseStream.Position = _dataSectionOffset + dataPos; ResourceTypeCode typeCode = (ResourceTypeCode)_store.Read7BitEncodedInt(); if (typeCode < 0 || typeCode >= ResourceTypeCode.StartOfUserTypes + _typeTable.Length) { throw new BadImageFormatException(SR.BadImageFormat_InvalidType); } resourceType = TypeNameFromTypeCode(typeCode); // The length must be adjusted to subtract off the number // of bytes in the 7 bit encoded type code. len -= (int)(_store.BaseStream.Position - (_dataSectionOffset + dataPos)); byte[] bytes = _store.ReadBytes(len); if (bytes.Length != len) throw new FormatException(SR.BadImageFormat_ResourceNameCorrupted); resourceData = 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.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Text; using System.Threading; namespace System.Resources { public partial class ResourceReader { private readonly bool _permitDeserialization; // can deserialize BinaryFormatted resources private object? _binaryFormatter; // binary formatter instance to use for deserializing // statics used to dynamically call into BinaryFormatter // When successfully located s_binaryFormatterType will point to the BinaryFormatter type // and s_deserializeMethod will point to an unbound delegate to the deserialize method. [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] private static Type? s_binaryFormatterType; private static Func<object?, Stream, object>? s_deserializeMethod; // This is the constructor the RuntimeResourceSet calls, // passing in the stream to read from and the RuntimeResourceSet's // internal hash table (hash table of names with file offsets // and values, coupled to this ResourceReader). internal ResourceReader(Stream stream, Dictionary<string, ResourceLocator> resCache, bool permitDeserialization) { Debug.Assert(stream != null, "Need a stream!"); Debug.Assert(stream.CanRead, "Stream should be readable!"); Debug.Assert(resCache != null, "Need a Dictionary!"); _resCache = resCache; _store = new BinaryReader(stream, Encoding.UTF8); _ums = stream as UnmanagedMemoryStream; _permitDeserialization = permitDeserialization; ReadResources(); } [UnconditionalSuppressMessage("AotAnalysis", "IL3050:RequiresDynamicCode", Justification = "InitializeBinaryFormatter will get trimmed out when AllowCustomResourceTypes is set to false. " + "When set to true, we will already throw a warning for this feature switch, so we suppress this one in order for" + "the user to only get one error.")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "InitializeBinaryFormatter will get trimmed out when AllowCustomResourceTypes is set to false. " + "When set to true, we will already throw a warning for this feature switch, so we suppress this one in order for" + "the user to only get one error.")] private object DeserializeObject(int typeIndex) { if (!AllowCustomResourceTypes) { throw new NotSupportedException(SR.ResourceManager_ReflectionNotAllowed); } if (!_permitDeserialization) { throw new NotSupportedException(SR.NotSupported_ResourceObjectSerialization); } if (Volatile.Read(ref _binaryFormatter) is null) { if (!InitializeBinaryFormatter()) { // The linker trimmed away the BinaryFormatter implementation and we can't call into it. // We'll throw an exception with the same text that BinaryFormatter would have thrown // had we been able to call into it. Keep this resource string in sync with the same // resource from the Formatters assembly. throw new NotSupportedException(SR.BinaryFormatter_SerializationDisallowed); } } Type type = FindType(typeIndex); object graph = s_deserializeMethod!(_binaryFormatter, _store.BaseStream); // guard against corrupted resources if (graph.GetType() != type) throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResType_SerBlobMismatch, type.FullName, graph.GetType().FullName)); return graph; } // Issue https://github.com/dotnet/runtime/issues/39290 tracks finding an alternative to BinaryFormatter [RequiresDynamicCode("The native code for this instantiation might not be available at runtime.")] [RequiresUnreferencedCode("The CustomResourceTypesSupport feature switch has been enabled for this app which is being trimmed. " + "Custom readers as well as custom objects on the resources file are not observable by the trimmer and so required assemblies, types and members may be removed.")] private bool InitializeBinaryFormatter() { // If BinaryFormatter support is disabled for the app, the linker will replace this entire // method body with "return false;", skipping all reflection code below. if (Volatile.Read(ref s_binaryFormatterType) is null || Volatile.Read(ref s_deserializeMethod) is null) { Type binaryFormatterType = Type.GetType("System.Runtime.Serialization.Formatters.Binary.BinaryFormatter, System.Runtime.Serialization.Formatters", throwOnError: true)!; MethodInfo? binaryFormatterDeserialize = binaryFormatterType.GetMethod("Deserialize", new[] { typeof(Stream) }); Func<object?, Stream, object>? deserializeMethod = (Func<object?, Stream, object>?) typeof(ResourceReader) .GetMethod(nameof(CreateUntypedDelegate), BindingFlags.NonPublic | BindingFlags.Static) ?.MakeGenericMethod(binaryFormatterType) .Invoke(null, new[] { binaryFormatterDeserialize }); Interlocked.CompareExchange(ref s_binaryFormatterType, binaryFormatterType, null); Interlocked.CompareExchange(ref s_deserializeMethod, deserializeMethod, null); } Volatile.Write(ref _binaryFormatter, Activator.CreateInstance(s_binaryFormatterType!)); return s_deserializeMethod != null; } // generic method that we specialize at runtime once we've loaded the BinaryFormatter type // permits creating an unbound delegate so that we can avoid reflection after the initial // lightup code completes. private static Func<object, Stream, object> CreateUntypedDelegate<TInstance>(MethodInfo method) { Func<TInstance, Stream, object> typedDelegate = (Func<TInstance, Stream, object>)Delegate.CreateDelegate(typeof(Func<TInstance, Stream, object>), null, method); return (obj, stream) => typedDelegate((TInstance)obj, stream); } private static bool ValidateReaderType(string readerType) { return ResourceManager.IsDefaultType(readerType, ResourceManager.ResReaderTypeName); } public void GetResourceData(string resourceName, out string resourceType, out byte[] resourceData) { ArgumentNullException.ThrowIfNull(resourceName); if (_resCache == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed); // Get the type information from the data section. Also, // sort all of the data section's indexes to compute length of // the serialized data for this type (making sure to subtract // off the length of the type code). int[] sortedDataPositions = new int[_numResources]; int dataPos = FindPosForResource(resourceName); if (dataPos == -1) { throw new ArgumentException(SR.Format(SR.Arg_ResourceNameNotExist, resourceName)); } lock (this) { // Read all the positions of data within the data section. for (int i = 0; i < _numResources; i++) { _store.BaseStream.Position = _nameSectionOffset + GetNamePosition(i); // Skip over name of resource int numBytesToSkip = _store.Read7BitEncodedInt(); if (numBytesToSkip < 0) { throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesNameInvalidOffset, numBytesToSkip)); } _store.BaseStream.Position += numBytesToSkip; int dPos = _store.ReadInt32(); if (dPos < 0 || dPos >= _store.BaseStream.Length - _dataSectionOffset) { throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesDataInvalidOffset, dPos)); } sortedDataPositions[i] = dPos; } Array.Sort(sortedDataPositions); int index = Array.BinarySearch(sortedDataPositions, dataPos); Debug.Assert(index >= 0 && index < _numResources, "Couldn't find data position within sorted data positions array!"); long nextData = (index < _numResources - 1) ? sortedDataPositions[index + 1] + _dataSectionOffset : _store.BaseStream.Length; int len = (int)(nextData - (dataPos + _dataSectionOffset)); Debug.Assert(len >= 0 && len <= (int)_store.BaseStream.Length - dataPos + _dataSectionOffset, "Length was negative or outside the bounds of the file!"); // Read type code then byte[] _store.BaseStream.Position = _dataSectionOffset + dataPos; ResourceTypeCode typeCode = (ResourceTypeCode)_store.Read7BitEncodedInt(); if (typeCode < 0 || typeCode >= ResourceTypeCode.StartOfUserTypes + _typeTable.Length) { throw new BadImageFormatException(SR.BadImageFormat_InvalidType); } resourceType = TypeNameFromTypeCode(typeCode); // The length must be adjusted to subtract off the number // of bytes in the 7 bit encoded type code. len -= (int)(_store.BaseStream.Position - (_dataSectionOffset + dataPos)); byte[] bytes = _store.ReadBytes(len); if (bytes.Length != len) throw new FormatException(SR.BadImageFormat_ResourceNameCorrupted); resourceData = bytes; } } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/RoundToZero.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 RoundToZero_Vector128_Double() { var test = new SimpleUnaryOpTest__RoundToZero_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 SimpleUnaryOpTest__RoundToZero_Vector128_Double { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); 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<Double, 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<Double> _fld1; 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>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__RoundToZero_Vector128_Double testClass) { var result = AdvSimd.Arm64.RoundToZero(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundToZero_Vector128_Double testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) { var result = AdvSimd.Arm64.RoundToZero( AdvSimd.LoadVector128((Double*)(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<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Vector128<Double> _clsVar1; private Vector128<Double> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__RoundToZero_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>>()); } public SimpleUnaryOpTest__RoundToZero_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 < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, 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.RoundToZero( Unsafe.Read<Vector128<Double>>(_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.Arm64.RoundToZero( AdvSimd.LoadVector128((Double*)(_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.Arm64).GetMethod(nameof(AdvSimd.Arm64.RoundToZero), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.RoundToZero), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.RoundToZero( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) { var result = AdvSimd.Arm64.RoundToZero( AdvSimd.LoadVector128((Double*)(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<Double>>(_dataTable.inArray1Ptr); var result = AdvSimd.Arm64.RoundToZero(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var result = AdvSimd.Arm64.RoundToZero(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__RoundToZero_Vector128_Double(); var result = AdvSimd.Arm64.RoundToZero(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__RoundToZero_Vector128_Double(); fixed (Vector128<Double>* pFld1 = &test._fld1) { var result = AdvSimd.Arm64.RoundToZero( AdvSimd.LoadVector128((Double*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.RoundToZero(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) { var result = AdvSimd.Arm64.RoundToZero( AdvSimd.LoadVector128((Double*)(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.Arm64.RoundToZero(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.Arm64.RoundToZero( AdvSimd.LoadVector128((Double*)(&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<Double> op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; 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 outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(Helpers.RoundToZero(firstOp[i])) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.RoundToZero)}<Double>(Vector128<Double>): {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 RoundToZero_Vector128_Double() { var test = new SimpleUnaryOpTest__RoundToZero_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 SimpleUnaryOpTest__RoundToZero_Vector128_Double { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); 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<Double, 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<Double> _fld1; 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>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__RoundToZero_Vector128_Double testClass) { var result = AdvSimd.Arm64.RoundToZero(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundToZero_Vector128_Double testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) { var result = AdvSimd.Arm64.RoundToZero( AdvSimd.LoadVector128((Double*)(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<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Vector128<Double> _clsVar1; private Vector128<Double> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__RoundToZero_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>>()); } public SimpleUnaryOpTest__RoundToZero_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 < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, 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.RoundToZero( Unsafe.Read<Vector128<Double>>(_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.Arm64.RoundToZero( AdvSimd.LoadVector128((Double*)(_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.Arm64).GetMethod(nameof(AdvSimd.Arm64.RoundToZero), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.RoundToZero), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.RoundToZero( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) { var result = AdvSimd.Arm64.RoundToZero( AdvSimd.LoadVector128((Double*)(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<Double>>(_dataTable.inArray1Ptr); var result = AdvSimd.Arm64.RoundToZero(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var result = AdvSimd.Arm64.RoundToZero(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__RoundToZero_Vector128_Double(); var result = AdvSimd.Arm64.RoundToZero(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__RoundToZero_Vector128_Double(); fixed (Vector128<Double>* pFld1 = &test._fld1) { var result = AdvSimd.Arm64.RoundToZero( AdvSimd.LoadVector128((Double*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.RoundToZero(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) { var result = AdvSimd.Arm64.RoundToZero( AdvSimd.LoadVector128((Double*)(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.Arm64.RoundToZero(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.Arm64.RoundToZero( AdvSimd.LoadVector128((Double*)(&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<Double> op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; 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 outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(Helpers.RoundToZero(firstOp[i])) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.RoundToZero)}<Double>(Vector128<Double>): {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
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/System.ComponentModel.TypeConverter/tests/TypeListConverterTests.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.Globalization; using System.Tests; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.ComponentModel.Tests { public class TypeListConverterTests : ConverterTestBase { // TypeListConverter is an abstract type private static TypeListConverter s_converter = new MyTypeListConverter(new Type[] { typeof(bool), typeof(int) }); [Fact] public static void CanConvertFrom_WithContext_TypeListConverter() { CanConvertFrom_WithContext(new object[2, 2] { { typeof(string), true }, { typeof(int), false } }, TypeListConverterTests.s_converter); } [Fact] public static void ConvertFrom_WithContext_TypeListConverter() { ConvertFrom_WithContext(new object[1, 3] { { "System.Int32", typeof(int), null } }, TypeListConverterTests.s_converter); } [Fact] public static void ConvertTo_WithContext_TypeListConverter() { using (new ThreadCultureChange(CultureInfo.InvariantCulture)) { ConvertTo_WithContext(new object[2, 3] { { typeof(char), "System.Char", null }, // the base class is not verifying if this type is not in the list { null, "(none)", CultureInfo.InvariantCulture } }, TypeListConverterTests.s_converter); } } [Fact] public static void ConvertTo_WithContext_Negative() { Assert.Throws<InvalidCastException>( () => TypeListConverterTests.s_converter.ConvertTo(TypeConverterTests.s_context, null, 3, typeof(string))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; using System.Tests; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.ComponentModel.Tests { public class TypeListConverterTests : ConverterTestBase { // TypeListConverter is an abstract type private static TypeListConverter s_converter = new MyTypeListConverter(new Type[] { typeof(bool), typeof(int) }); [Fact] public static void CanConvertFrom_WithContext_TypeListConverter() { CanConvertFrom_WithContext(new object[2, 2] { { typeof(string), true }, { typeof(int), false } }, TypeListConverterTests.s_converter); } [Fact] public static void ConvertFrom_WithContext_TypeListConverter() { ConvertFrom_WithContext(new object[1, 3] { { "System.Int32", typeof(int), null } }, TypeListConverterTests.s_converter); } [Fact] public static void ConvertTo_WithContext_TypeListConverter() { using (new ThreadCultureChange(CultureInfo.InvariantCulture)) { ConvertTo_WithContext(new object[2, 3] { { typeof(char), "System.Char", null }, // the base class is not verifying if this type is not in the list { null, "(none)", CultureInfo.InvariantCulture } }, TypeListConverterTests.s_converter); } } [Fact] public static void ConvertTo_WithContext_Negative() { Assert.Throws<InvalidCastException>( () => TypeListConverterTests.s_converter.ConvertTo(TypeConverterTests.s_context, null, 3, typeof(string))); } } }
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/installer/pkg/README.md
THIRD-PARTY-NOTICES.TXT in this directory contains TPNs from all repos that contribute to installer packages that install files under dotnet directory. This file is included in .NET Host installer package and installed to dotnet directory. It should be updated, manually or automatically to include new TPNs for each release. THIRD-PARTY-NOTICES.TXT in the root of this repo contains TPNs for this repo only.
THIRD-PARTY-NOTICES.TXT in this directory contains TPNs from all repos that contribute to installer packages that install files under dotnet directory. This file is included in .NET Host installer package and installed to dotnet directory. It should be updated, manually or automatically to include new TPNs for each release. THIRD-PARTY-NOTICES.TXT in the root of this repo contains TPNs for this repo only.
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M10/b08797/b08797.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).il" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/libraries/Microsoft.Extensions.Logging.EventLog/src/Microsoft.Extensions.Logging.EventLog.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks> <EnableDefaultItems>true</EnableDefaultItems> <IsPackable>true</IsPackable> <PackageDescription>Windows Event Log logger provider implementation for Microsoft.Extensions.Logging.</PackageDescription> </PropertyGroup> <ItemGroup> <Compile Include="$(CommonPath)Extensions\Logging\NullExternalScopeProvider.cs" Link="Common\src\Extensions\Logging\NullExternalScopeProvider.cs" /> <Compile Include="$(CommonPath)Extensions\Logging\NullScope.cs" Link="Common\src\Extensions\Logging\NullScope.cs" /> <Compile Include="$(CommonPath)System\ThrowHelper.cs" Link="Common\System\ThrowHelper.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.DependencyInjection.Abstractions\src\Microsoft.Extensions.DependencyInjection.Abstractions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Logging\src\Microsoft.Extensions.Logging.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Logging.Abstractions\src\Microsoft.Extensions.Logging.Abstractions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Options\src\Microsoft.Extensions.Options.csproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' != '.NETFramework'"> <ProjectReference Include="$(LibrariesProjectRoot)System.Diagnostics.EventLog\src\System.Diagnostics.EventLog.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks> <EnableDefaultItems>true</EnableDefaultItems> <IsPackable>true</IsPackable> <PackageDescription>Windows Event Log logger provider implementation for Microsoft.Extensions.Logging.</PackageDescription> </PropertyGroup> <ItemGroup> <Compile Include="$(CommonPath)Extensions\Logging\NullExternalScopeProvider.cs" Link="Common\src\Extensions\Logging\NullExternalScopeProvider.cs" /> <Compile Include="$(CommonPath)Extensions\Logging\NullScope.cs" Link="Common\src\Extensions\Logging\NullScope.cs" /> <Compile Include="$(CommonPath)System\ThrowHelper.cs" Link="Common\System\ThrowHelper.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.DependencyInjection.Abstractions\src\Microsoft.Extensions.DependencyInjection.Abstractions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Logging\src\Microsoft.Extensions.Logging.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Logging.Abstractions\src\Microsoft.Extensions.Logging.Abstractions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Options\src\Microsoft.Extensions.Options.csproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' != '.NETFramework'"> <ProjectReference Include="$(LibrariesProjectRoot)System.Diagnostics.EventLog\src\System.Diagnostics.EventLog.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,966
Use SubtleCrypto API on browser DOM scenarios
Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
layomia
2022-02-28T18:25:51Z
2022-05-24T22:19:32Z
c5f949efa20bcb555c453037fa954fcc403f9490
bfbb78354e536ac616f2f9dabf3db2b8fa8b9f64
Use SubtleCrypto API on browser DOM scenarios. Contributes to https://github.com/dotnet/runtime/issues/40074. For WASM, uses the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) browser-native implementation for the SHA1, SHA256, SHA384, SHA512 algorithms, and adds infrastructure to support using the native implementation. Support for the rest of the algorithms will come in a single follow-up PR.
./src/coreclr/pal/tests/palsuite/c_runtime/fread/test2/test2.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*===================================================================== ** ** Source: test2.c ** ** Purpose: Tests the PAL implementation of the fread function. ** Open a file in READ mode, and then try to read all ** the characters, more than all the characters, ** 0 characters and 0 sized characters and check that ** the strings read in are correct. ** ** Depends: ** fopen ** fseek ** fclose ** strcmp ** memset ** ** **===================================================================*/ /* Note: testfile should exist in the directory with 15 characters in it ... something got lost if it isn't here. */ /* Note: The behaviour in win32 is to crash if a NULL pointer is passed to fread, so the test to check that it returns 0 has been removed. */ #include <palsuite.h> PALTEST(c_runtime_fread_test2_paltest_fread_test2, "c_runtime/fread/test2/paltest_fread_test2") { const char filename[] = "testfile"; char buffer[128]; FILE * fp = NULL; if (0 != PAL_Initialize(argc, argv)) { return FAIL; } /* Open a file in READ mode */ if((fp = fopen(filename, "r")) == NULL) { Fail("Unable to open a file for reading. Is the file " "in the directory? It should be."); } /* Read 15 characters from the file. The file has exactly this many in it. Then check to see that the data read in is correct. Note: The 'testfile' should have "This is a test." written in it. */ memset(buffer,'\0',128); fread(buffer,1,15,fp); if(strcmp(buffer,"This is a test.") != 0) { Fail("ERROR: The data read in should have been " "'This is a test.' but, the buffer contains '%s'.", buffer); } /* Go back to the start of the file */ if(fseek(fp, 0, SEEK_SET)) { Fail("ERROR: fseek failed, and this test depends on it."); } /* Attempt to read 17 characters. The same 15 characters should be in the buffer. */ memset(buffer,'\0',128); fread(buffer,1,17,fp); if(strcmp(buffer,"This is a test.") != 0) { Fail("ERROR: The data read in should have been " "'This is a test.' but, the buffer contains '%s'.", buffer); } /* Back to the start of the file */ if(fseek(fp, 0, SEEK_SET)) { Fail("ERROR: fseek failed, and this test depends on it."); } /* Read 0 characters and ensure the buffer is empty */ memset(buffer,'\0',128); fread(buffer,1,0,fp); if(strcmp(buffer,"\0") != 0) { Fail("ERROR: The data read in should have been " "NULL but, the buffer contains '%s'.", buffer); } /* Read characters of 0 size and ensure the buffer is empty */ memset(buffer,'\0',128); fread(buffer,0,5,fp); if(strcmp(buffer,"\0") != 0) { Fail("ERROR: The data read in should have been " "NULL but, the buffer contains '%s'.", buffer); } /* Close the file */ if(fclose(fp)) { Fail("ERROR: fclose failed. Test depends on it."); } /* Read 5 characters of 1 size from a closed file pointer and ensure the buffer is empty */ memset(buffer,'\0',128); fread(buffer,1,5,fp); if(strcmp(buffer,"\0") != 0) { Fail("ERROR: The data read in should have been " "NULL but, the buffer contains '%s'.", buffer); } PAL_Terminate(); return PASS; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*===================================================================== ** ** Source: test2.c ** ** Purpose: Tests the PAL implementation of the fread function. ** Open a file in READ mode, and then try to read all ** the characters, more than all the characters, ** 0 characters and 0 sized characters and check that ** the strings read in are correct. ** ** Depends: ** fopen ** fseek ** fclose ** strcmp ** memset ** ** **===================================================================*/ /* Note: testfile should exist in the directory with 15 characters in it ... something got lost if it isn't here. */ /* Note: The behaviour in win32 is to crash if a NULL pointer is passed to fread, so the test to check that it returns 0 has been removed. */ #include <palsuite.h> PALTEST(c_runtime_fread_test2_paltest_fread_test2, "c_runtime/fread/test2/paltest_fread_test2") { const char filename[] = "testfile"; char buffer[128]; FILE * fp = NULL; if (0 != PAL_Initialize(argc, argv)) { return FAIL; } /* Open a file in READ mode */ if((fp = fopen(filename, "r")) == NULL) { Fail("Unable to open a file for reading. Is the file " "in the directory? It should be."); } /* Read 15 characters from the file. The file has exactly this many in it. Then check to see that the data read in is correct. Note: The 'testfile' should have "This is a test." written in it. */ memset(buffer,'\0',128); fread(buffer,1,15,fp); if(strcmp(buffer,"This is a test.") != 0) { Fail("ERROR: The data read in should have been " "'This is a test.' but, the buffer contains '%s'.", buffer); } /* Go back to the start of the file */ if(fseek(fp, 0, SEEK_SET)) { Fail("ERROR: fseek failed, and this test depends on it."); } /* Attempt to read 17 characters. The same 15 characters should be in the buffer. */ memset(buffer,'\0',128); fread(buffer,1,17,fp); if(strcmp(buffer,"This is a test.") != 0) { Fail("ERROR: The data read in should have been " "'This is a test.' but, the buffer contains '%s'.", buffer); } /* Back to the start of the file */ if(fseek(fp, 0, SEEK_SET)) { Fail("ERROR: fseek failed, and this test depends on it."); } /* Read 0 characters and ensure the buffer is empty */ memset(buffer,'\0',128); fread(buffer,1,0,fp); if(strcmp(buffer,"\0") != 0) { Fail("ERROR: The data read in should have been " "NULL but, the buffer contains '%s'.", buffer); } /* Read characters of 0 size and ensure the buffer is empty */ memset(buffer,'\0',128); fread(buffer,0,5,fp); if(strcmp(buffer,"\0") != 0) { Fail("ERROR: The data read in should have been " "NULL but, the buffer contains '%s'.", buffer); } /* Close the file */ if(fclose(fp)) { Fail("ERROR: fclose failed. Test depends on it."); } /* Read 5 characters of 1 size from a closed file pointer and ensure the buffer is empty */ memset(buffer,'\0',128); fread(buffer,1,5,fp); if(strcmp(buffer,"\0") != 0) { Fail("ERROR: The data read in should have been " "NULL but, the buffer contains '%s'.", buffer); } PAL_Terminate(); return PASS; }
-1