repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
timestamp[ns, tz=UTC] | date_merged
timestamp[ns, tz=UTC] | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Reflection.Emit/tests/ParameterBuilder/ParameterBuilderSetConstant.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.Reflection.Emit.Tests
{
public class ParameterBuilderSetConstant
{
public static IEnumerable<object[]> SetConstant_ReferenceTypes_TestData()
{
yield return new object[] { typeof(object) };
yield return new object[] { typeof(string) };
yield return new object[] { typeof(UserDefinedClass) };
}
public static IEnumerable<object[]> SetConstant_NullableValueTypes_TestData()
{
yield return new object[] { typeof(bool?) };
yield return new object[] { typeof(byte?) };
yield return new object[] { typeof(char?) };
yield return new object[] { typeof(DateTime?) };
yield return new object[] { typeof(decimal?) };
yield return new object[] { typeof(double?) };
yield return new object[] { typeof(float?) };
yield return new object[] { typeof(int?) };
yield return new object[] { typeof(long?) };
yield return new object[] { typeof(sbyte?) };
yield return new object[] { typeof(short?) };
yield return new object[] { typeof(uint?) };
yield return new object[] { typeof(ulong?) };
yield return new object[] { typeof(UserDefinedStruct?) };
yield return new object[] { typeof(ushort?) };
}
public static IEnumerable<object[]> SetConstant_ValueTypes_TestData()
{
yield return new object[] { typeof(bool) };
yield return new object[] { typeof(byte) };
yield return new object[] { typeof(char) };
yield return new object[] { typeof(DateTime) };
yield return new object[] { typeof(decimal) };
yield return new object[] { typeof(double) };
yield return new object[] { typeof(float) };
yield return new object[] { typeof(int) };
yield return new object[] { typeof(long) };
yield return new object[] { typeof(sbyte) };
yield return new object[] { typeof(short) };
yield return new object[] { typeof(uint) };
yield return new object[] { typeof(ulong) };
yield return new object[] { typeof(UserDefinedStruct) };
yield return new object[] { typeof(ushort) };
}
[Theory]
[MemberData(nameof(SetConstant_ReferenceTypes_TestData))]
[MemberData(nameof(SetConstant_NullableValueTypes_TestData))]
[MemberData(nameof(SetConstant_ValueTypes_TestData))]
public void SetConstant_Null_fully_supported(Type parameterType)
{
SetConstant_Null(parameterType);
}
[Theory]
[InlineData(typeof(AttributeTargets?), AttributeTargets.All, (int)AttributeTargets.All)]
[InlineData(typeof(AttributeTargets?), (int)AttributeTargets.All, (int)AttributeTargets.All)]
public void SetConstant_NonNull_on_nullable_enum(Type parameterType, object valueToWrite, object expectedValueWhenRead)
{
SetConstant(parameterType, valueToWrite, expectedValueWhenRead);
}
private void SetConstant_Null(Type parameterType)
{
SetConstant(parameterType, null, null);
}
private void SetConstant(Type parameterType, object valueToWrite, object expectedValueWhenRead)
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Interface | TypeAttributes.Abstract);
MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(void), new Type[] { parameterType });
ParameterBuilder parameter = method.DefineParameter(1, ParameterAttributes.Optional | ParameterAttributes.HasDefault, "arg");
parameter.SetConstant(valueToWrite);
ParameterInfo createdParameter = GetCreatedParameter(type, "TestMethod", 1);
Assert.True(createdParameter.HasDefaultValue);
Assert.Equal(expectedValueWhenRead, createdParameter.DefaultValue);
}
private static ParameterInfo GetCreatedParameter(TypeBuilder type, string methodName, int parameterIndex)
{
Type createdType = type.CreateTypeInfo().AsType();
MethodInfo createdMethod = createdType.GetMethod(methodName);
if (parameterIndex > 0)
{
return createdMethod.GetParameters()[parameterIndex - 1];
}
else
{
return createdMethod.ReturnParameter;
}
}
private class UserDefinedClass
{
}
private struct UserDefinedStruct
{
}
}
}
| // 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.Reflection.Emit.Tests
{
public class ParameterBuilderSetConstant
{
public static IEnumerable<object[]> SetConstant_ReferenceTypes_TestData()
{
yield return new object[] { typeof(object) };
yield return new object[] { typeof(string) };
yield return new object[] { typeof(UserDefinedClass) };
}
public static IEnumerable<object[]> SetConstant_NullableValueTypes_TestData()
{
yield return new object[] { typeof(bool?) };
yield return new object[] { typeof(byte?) };
yield return new object[] { typeof(char?) };
yield return new object[] { typeof(DateTime?) };
yield return new object[] { typeof(decimal?) };
yield return new object[] { typeof(double?) };
yield return new object[] { typeof(float?) };
yield return new object[] { typeof(int?) };
yield return new object[] { typeof(long?) };
yield return new object[] { typeof(sbyte?) };
yield return new object[] { typeof(short?) };
yield return new object[] { typeof(uint?) };
yield return new object[] { typeof(ulong?) };
yield return new object[] { typeof(UserDefinedStruct?) };
yield return new object[] { typeof(ushort?) };
}
public static IEnumerable<object[]> SetConstant_ValueTypes_TestData()
{
yield return new object[] { typeof(bool) };
yield return new object[] { typeof(byte) };
yield return new object[] { typeof(char) };
yield return new object[] { typeof(DateTime) };
yield return new object[] { typeof(decimal) };
yield return new object[] { typeof(double) };
yield return new object[] { typeof(float) };
yield return new object[] { typeof(int) };
yield return new object[] { typeof(long) };
yield return new object[] { typeof(sbyte) };
yield return new object[] { typeof(short) };
yield return new object[] { typeof(uint) };
yield return new object[] { typeof(ulong) };
yield return new object[] { typeof(UserDefinedStruct) };
yield return new object[] { typeof(ushort) };
}
[Theory]
[MemberData(nameof(SetConstant_ReferenceTypes_TestData))]
[MemberData(nameof(SetConstant_NullableValueTypes_TestData))]
[MemberData(nameof(SetConstant_ValueTypes_TestData))]
public void SetConstant_Null_fully_supported(Type parameterType)
{
SetConstant_Null(parameterType);
}
[Theory]
[InlineData(typeof(AttributeTargets?), AttributeTargets.All, (int)AttributeTargets.All)]
[InlineData(typeof(AttributeTargets?), (int)AttributeTargets.All, (int)AttributeTargets.All)]
public void SetConstant_NonNull_on_nullable_enum(Type parameterType, object valueToWrite, object expectedValueWhenRead)
{
SetConstant(parameterType, valueToWrite, expectedValueWhenRead);
}
private void SetConstant_Null(Type parameterType)
{
SetConstant(parameterType, null, null);
}
private void SetConstant(Type parameterType, object valueToWrite, object expectedValueWhenRead)
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Interface | TypeAttributes.Abstract);
MethodBuilder method = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(void), new Type[] { parameterType });
ParameterBuilder parameter = method.DefineParameter(1, ParameterAttributes.Optional | ParameterAttributes.HasDefault, "arg");
parameter.SetConstant(valueToWrite);
ParameterInfo createdParameter = GetCreatedParameter(type, "TestMethod", 1);
Assert.True(createdParameter.HasDefaultValue);
Assert.Equal(expectedValueWhenRead, createdParameter.DefaultValue);
}
private static ParameterInfo GetCreatedParameter(TypeBuilder type, string methodName, int parameterIndex)
{
Type createdType = type.CreateTypeInfo().AsType();
MethodInfo createdMethod = createdType.GetMethod(methodName);
if (parameterIndex > 0)
{
return createdMethod.GetParameters()[parameterIndex - 1];
}
else
{
return createdMethod.ReturnParameter;
}
}
private class UserDefinedClass
{
}
private struct UserDefinedStruct
{
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./docs/project/breaking-change-process.md | # Breaking change process
Breaking changes make it difficult for people to adopt new versions of .NET. We strive to avoid making them. In the rare case when a breaking change is unavoidable or the best option when all factors are considered, you should follow the process outlined in this document. The intent of the process is to get feedback. This might result in previously unseen opportunities to achieve your goals without breaks, clever ways to limit breaks to more niche scenarios, and (most importantly) better understand the scope of impact to .NET users.
This process does not result in approval or denial of a breaking change request. It results in feedback, which might be varied or uniform. In the best case, the feedback is a call to action to you, that provides a direction on how you should proceed. The people that are responsible for reviewing your PR are expected to use the information collected by this process as part of their determination of whether your change is appropriate to merge.
You should start this process as soon as possible, preferably before any code is written, in the design phase. This isn't always possible, since the change in behavior might not be discovered until you're almost done building a feature. In the case of a significant breaking change, you should provide reviewers with a design document so that they can understand the broader scope, goals and constraints of your change.
There are people on the team that can help you work through a breaking change, if you want to engage with them before starting this more formal process. They are part of the [dotnet/compat team](https://github.com/orgs/dotnet/teams/compat) . Feel free to @mention them on issues to start a dialogue.
## Process
1. Create or link to an issue that describes the breaking change, including the following information:
* Mark with the [breaking-change](https://github.com/dotnet/runtime/labels/breaking-change) label
* Goals and motivation for the change
* Pre-change behavior
* Post-change behavior
* Versions of the product this change affects
* Errors or other behavior you can expect when running old code that breaks
* Workarounds and mitigations, including [AppContext switches](https://docs.microsoft.com/dotnet/api/system.appcontext)
* Link to the issue for the feature or bug fix that the breaking change is associated with.
* Reference this issue from associated PRs.
2. Share your issue with whomever you see as stakeholders
* Please @mention [dotnet/compat team](https://github.com/orgs/dotnet/teams/compat) team
* Engage with people commenting on the issue, with the goal of deriving the most feedback on your proposed breaking change
* This may involve significant explanation on your part. A well-written design doc can ease the burden here.
3. Mark associated PRs with the [breaking-change](https://github.com/dotnet/runtime/labels/breaking-change) label, and link to your breaking change issue.
4. Once the PR is merged, create a [docs issue](https://github.com/dotnet/docs/issues/new?template=dotnet-breaking-change.md).
* Clarify which .NET preview the break will be first released in.
5. Breaking change issues can be closed at any time after the PR is merged. Best practice is waiting until the change has been released in a public preview.
Notes:
* We add quirk switches to .NET Core re-actively, only once we get feedback that they are really needed for something important. We do not add them proactively like in .NET Framework just because they might be needed in theory.
* In terms of product versions that the change affects, consider both .NET Core and .NET Framework (see: [.NET Framework compatibility mode](https://docs.microsoft.com/dotnet/standard/net-standard#net-framework-compatibility-mode)). Consider source and binary compatibility.
## Examples
The following are good examples of breaking change issues
* https://github.com/dotnet/runtime/issues/28788
* https://github.com/dotnet/runtime/issues/37672
## Resources
There are additional documents that you should consult about breaking changes:
* [Breaking changes](https://github.com/dotnet/runtime/blob/main/docs/coding-guidelines/breaking-changes.md)
* [Breaking change definitions](https://github.com/dotnet/runtime/blob/main/docs/coding-guidelines/breaking-change-definitions.md)
* [Breaking change rules](https://github.com/dotnet/runtime/blob/main/docs/coding-guidelines/breaking-change-rules.md)
| # Breaking change process
Breaking changes make it difficult for people to adopt new versions of .NET. We strive to avoid making them. In the rare case when a breaking change is unavoidable or the best option when all factors are considered, you should follow the process outlined in this document. The intent of the process is to get feedback. This might result in previously unseen opportunities to achieve your goals without breaks, clever ways to limit breaks to more niche scenarios, and (most importantly) better understand the scope of impact to .NET users.
This process does not result in approval or denial of a breaking change request. It results in feedback, which might be varied or uniform. In the best case, the feedback is a call to action to you, that provides a direction on how you should proceed. The people that are responsible for reviewing your PR are expected to use the information collected by this process as part of their determination of whether your change is appropriate to merge.
You should start this process as soon as possible, preferably before any code is written, in the design phase. This isn't always possible, since the change in behavior might not be discovered until you're almost done building a feature. In the case of a significant breaking change, you should provide reviewers with a design document so that they can understand the broader scope, goals and constraints of your change.
There are people on the team that can help you work through a breaking change, if you want to engage with them before starting this more formal process. They are part of the [dotnet/compat team](https://github.com/orgs/dotnet/teams/compat) . Feel free to @mention them on issues to start a dialogue.
## Process
1. Create or link to an issue that describes the breaking change, including the following information:
* Mark with the [breaking-change](https://github.com/dotnet/runtime/labels/breaking-change) label
* Goals and motivation for the change
* Pre-change behavior
* Post-change behavior
* Versions of the product this change affects
* Errors or other behavior you can expect when running old code that breaks
* Workarounds and mitigations, including [AppContext switches](https://docs.microsoft.com/dotnet/api/system.appcontext)
* Link to the issue for the feature or bug fix that the breaking change is associated with.
* Reference this issue from associated PRs.
2. Share your issue with whomever you see as stakeholders
* Please @mention [dotnet/compat team](https://github.com/orgs/dotnet/teams/compat) team
* Engage with people commenting on the issue, with the goal of deriving the most feedback on your proposed breaking change
* This may involve significant explanation on your part. A well-written design doc can ease the burden here.
3. Mark associated PRs with the [breaking-change](https://github.com/dotnet/runtime/labels/breaking-change) label, and link to your breaking change issue.
4. Once the PR is merged, create a [docs issue](https://github.com/dotnet/docs/issues/new?template=dotnet-breaking-change.md).
* Clarify which .NET preview the break will be first released in.
5. Breaking change issues can be closed at any time after the PR is merged. Best practice is waiting until the change has been released in a public preview.
Notes:
* We add quirk switches to .NET Core re-actively, only once we get feedback that they are really needed for something important. We do not add them proactively like in .NET Framework just because they might be needed in theory.
* In terms of product versions that the change affects, consider both .NET Core and .NET Framework (see: [.NET Framework compatibility mode](https://docs.microsoft.com/dotnet/standard/net-standard#net-framework-compatibility-mode)). Consider source and binary compatibility.
## Examples
The following are good examples of breaking change issues
* https://github.com/dotnet/runtime/issues/28788
* https://github.com/dotnet/runtime/issues/37672
## Resources
There are additional documents that you should consult about breaking changes:
* [Breaking changes](https://github.com/dotnet/runtime/blob/main/docs/coding-guidelines/breaking-changes.md)
* [Breaking change definitions](https://github.com/dotnet/runtime/blob/main/docs/coding-guidelines/breaking-change-definitions.md)
* [Breaking change rules](https://github.com/dotnet/runtime/blob/main/docs/coding-guidelines/breaking-change-rules.md)
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Runtime.Serialization.Xml/tests/System.Runtime.Serialization.Xml.Tests.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>$(NetCoreAppCurrent)</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(TestSourceFolder)DataContractSerializerStressTests.cs" />
<Compile Include="$(TestSourceFolder)SerializationTypes.cs" />
<Compile Include="$(TestSourceFolder)SerializationTypes.RuntimeOnly.cs" />
<Compile Include="$(TestSourceFolder)DataContractSerializer.cs" />
<Compile Include="$(TestSourceFolder)MyResolver.cs" />
<Compile Include="$(TestSourceFolder)XmlDictionaryReaderTests.cs" />
<Compile Include="$(TestSourceFolder)XmlDictionaryWriterTest.cs" />
<Compile Include="$(TestSourceFolder)SerializationTestTypes\ComparisonHelper.cs" />
<Compile Include="$(TestSourceFolder)SerializationTestTypes\DataContractResolverLibrary.cs" />
<Compile Include="$(TestSourceFolder)SerializationTestTypes\DCRSampleType.cs" />
<Compile Include="$(TestSourceFolder)SerializationTestTypes\DCRTypeLibrary.cs" />
<Compile Include="$(TestSourceFolder)SerializationTestTypes\Primitives.cs" />
<Compile Include="$(CommonTestPath)System\IO\TempFile.cs" Link="Common\System\IO\TempFile.cs" />
<Compile Include="$(CommonTestPath)System\Runtime\Serialization\DataContractSerializerHelper.cs" Link="Common\System\Runtime\Serialization\DataContractSerializerHelper.cs" />
<Compile Include="$(CommonTestPath)System\Runtime\Serialization\Utils.cs" />
<Compile Include="$(TestSourceFolder)SerializationTestTypes\ObjRefSample.cs" />
<Compile Include="SerializationTestTypes\Collections.cs" />
<Compile Include="SerializationTestTypes\DataContract.cs" />
<Compile Include="SerializationTestTypes\DCRImplVariations.cs" />
<Compile Include="SerializationTestTypes\InheritenceCases.cs" />
<Compile Include="SerializationTestTypes\InheritenceObjectRef.cs" />
<Compile Include="SerializationTestTypes\SampleIObjectRef.cs" />
<Compile Include="SerializationTestTypes\SampleTypes.cs" />
<Compile Include="SerializationTestTypes\SelfRefAndCycles.cs" />
<Compile Include="XmlSerializerTests.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(LibrariesProjectRoot)System.CodeDom\src\System.CodeDom.csproj" />
<TrimmerRootDescriptor Include="$(ILLinkDescriptorsPath)ILLink.Descriptors.Serialization.xml" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>$(NetCoreAppCurrent)</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(TestSourceFolder)DataContractSerializerStressTests.cs" />
<Compile Include="$(TestSourceFolder)SerializationTypes.cs" />
<Compile Include="$(TestSourceFolder)SerializationTypes.RuntimeOnly.cs" />
<Compile Include="$(TestSourceFolder)DataContractSerializer.cs" />
<Compile Include="$(TestSourceFolder)MyResolver.cs" />
<Compile Include="$(TestSourceFolder)XmlDictionaryReaderTests.cs" />
<Compile Include="$(TestSourceFolder)XmlDictionaryWriterTest.cs" />
<Compile Include="$(TestSourceFolder)SerializationTestTypes\ComparisonHelper.cs" />
<Compile Include="$(TestSourceFolder)SerializationTestTypes\DataContractResolverLibrary.cs" />
<Compile Include="$(TestSourceFolder)SerializationTestTypes\DCRSampleType.cs" />
<Compile Include="$(TestSourceFolder)SerializationTestTypes\DCRTypeLibrary.cs" />
<Compile Include="$(TestSourceFolder)SerializationTestTypes\Primitives.cs" />
<Compile Include="$(CommonTestPath)System\IO\TempFile.cs" Link="Common\System\IO\TempFile.cs" />
<Compile Include="$(CommonTestPath)System\Runtime\Serialization\DataContractSerializerHelper.cs" Link="Common\System\Runtime\Serialization\DataContractSerializerHelper.cs" />
<Compile Include="$(CommonTestPath)System\Runtime\Serialization\Utils.cs" />
<Compile Include="$(TestSourceFolder)SerializationTestTypes\ObjRefSample.cs" />
<Compile Include="SerializationTestTypes\Collections.cs" />
<Compile Include="SerializationTestTypes\DataContract.cs" />
<Compile Include="SerializationTestTypes\DCRImplVariations.cs" />
<Compile Include="SerializationTestTypes\InheritenceCases.cs" />
<Compile Include="SerializationTestTypes\InheritenceObjectRef.cs" />
<Compile Include="SerializationTestTypes\SampleIObjectRef.cs" />
<Compile Include="SerializationTestTypes\SampleTypes.cs" />
<Compile Include="SerializationTestTypes\SelfRefAndCycles.cs" />
<Compile Include="XmlSerializerTests.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(LibrariesProjectRoot)System.CodeDom\src\System.CodeDom.csproj" />
<TrimmerRootDescriptor Include="$(ILLinkDescriptorsPath)ILLink.Descriptors.Serialization.xml" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Linq/tests/ConsistencyTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Linq.Tests
{
public class ConsistencyTests
{
[Fact]
public static void MatchSequencePattern()
{
MethodInfo enumerableNotInQueryable = GetMissingExtensionMethod(typeof(Enumerable), typeof(Queryable), GetExcludedMethods());
Assert.True(enumerableNotInQueryable == null, string.Format("Enumerable method {0} not defined by Queryable", enumerableNotInQueryable));
MethodInfo queryableNotInEnumerable = GetMissingExtensionMethod(
typeof(Queryable),
typeof(Enumerable),
new[] {
nameof(Queryable.AsQueryable)
}
);
Assert.True(queryableNotInEnumerable == null, string.Format("Queryable method {0} not defined by Enumerable", queryableNotInEnumerable));
}
// If a change to Enumerable has required a change to the exception list in this test
// make the same change at src/System.Linq.Queryable/tests/Queryable.cs.
private static IEnumerable<string> GetExcludedMethods()
{
IEnumerable<string> result = new[]
{
nameof(Enumerable.ToLookup),
nameof(Enumerable.ToDictionary),
nameof(Enumerable.ToArray),
nameof(Enumerable.AsEnumerable),
nameof(Enumerable.ToList),
nameof(Enumerable.ToHashSet),
nameof(Enumerable.TryGetNonEnumeratedCount),
"Fold",
"LeftJoin",
};
return result;
}
private static MethodInfo GetMissingExtensionMethod(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type a,
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type b,
IEnumerable<string> excludedMethods)
{
var dex = new HashSet<string>(excludedMethods);
var aMethods =
a.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(m => m.CustomAttributes.Any(c => c.AttributeType == typeof(ExtensionAttribute)))
.ToLookup(m => m.Name);
MethodComparer mc = new MethodComparer();
var bMethods = b.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(m => m.CustomAttributes.Any(c => c.AttributeType == typeof(ExtensionAttribute)))
.ToLookup(m => m, mc);
foreach (var group in aMethods.Where(g => !dex.Contains(g.Key)))
{
foreach (MethodInfo m in group)
{
if (!bMethods.Contains(m))
return m;
}
}
return null;
}
private class MethodComparer : IEqualityComparer<MethodInfo>
{
public int GetHashCode(MethodInfo m) => m.Name.GetHashCode();
public bool Equals(MethodInfo a, MethodInfo b)
{
if (a.Name != b.Name)
return false;
ParameterInfo[] pas = a.GetParameters();
ParameterInfo[] pbs = b.GetParameters();
if (pas.Length != pbs.Length)
return false;
Type[] aArgs = a.GetGenericArguments();
Type[] bArgs = b.GetGenericArguments();
for (int i = 0, n = pas.Length; i < n; i++)
{
ParameterInfo pa = pas[i];
ParameterInfo pb = pbs[i];
Type ta = Strip(pa.ParameterType);
Type tb = Strip(pb.ParameterType);
if (ta.GetTypeInfo().IsGenericType && tb.GetTypeInfo().IsGenericType)
{
if (ta.GetGenericTypeDefinition() != tb.GetGenericTypeDefinition())
{
return false;
}
}
else if (ta.IsGenericParameter && tb.IsGenericParameter)
{
return Array.IndexOf(aArgs, ta) == Array.IndexOf(bArgs, tb);
}
else if (ta != tb)
{
return false;
}
}
return true;
}
private Type Strip(Type t)
{
if (t.GetTypeInfo().IsGenericType)
{
Type g = t;
if (!g.GetTypeInfo().IsGenericTypeDefinition)
{
g = t.GetGenericTypeDefinition();
}
if (g == typeof(IQueryable<>) || g == typeof(IEnumerable<>))
{
return typeof(IEnumerable);
}
if (g == typeof(Expression<>))
{
return t.GetGenericArguments()[0];
}
if (g == typeof(IOrderedEnumerable<>) || g == typeof(IOrderedQueryable<>))
{
return typeof(IOrderedQueryable);
}
}
else
{
if (t == typeof(IQueryable))
{
return typeof(IEnumerable);
}
}
return t;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Linq.Tests
{
public class ConsistencyTests
{
[Fact]
public static void MatchSequencePattern()
{
MethodInfo enumerableNotInQueryable = GetMissingExtensionMethod(typeof(Enumerable), typeof(Queryable), GetExcludedMethods());
Assert.True(enumerableNotInQueryable == null, string.Format("Enumerable method {0} not defined by Queryable", enumerableNotInQueryable));
MethodInfo queryableNotInEnumerable = GetMissingExtensionMethod(
typeof(Queryable),
typeof(Enumerable),
new[] {
nameof(Queryable.AsQueryable)
}
);
Assert.True(queryableNotInEnumerable == null, string.Format("Queryable method {0} not defined by Enumerable", queryableNotInEnumerable));
}
// If a change to Enumerable has required a change to the exception list in this test
// make the same change at src/System.Linq.Queryable/tests/Queryable.cs.
private static IEnumerable<string> GetExcludedMethods()
{
IEnumerable<string> result = new[]
{
nameof(Enumerable.ToLookup),
nameof(Enumerable.ToDictionary),
nameof(Enumerable.ToArray),
nameof(Enumerable.AsEnumerable),
nameof(Enumerable.ToList),
nameof(Enumerable.ToHashSet),
nameof(Enumerable.TryGetNonEnumeratedCount),
"Fold",
"LeftJoin",
};
return result;
}
private static MethodInfo GetMissingExtensionMethod(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type a,
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type b,
IEnumerable<string> excludedMethods)
{
var dex = new HashSet<string>(excludedMethods);
var aMethods =
a.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(m => m.CustomAttributes.Any(c => c.AttributeType == typeof(ExtensionAttribute)))
.ToLookup(m => m.Name);
MethodComparer mc = new MethodComparer();
var bMethods = b.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(m => m.CustomAttributes.Any(c => c.AttributeType == typeof(ExtensionAttribute)))
.ToLookup(m => m, mc);
foreach (var group in aMethods.Where(g => !dex.Contains(g.Key)))
{
foreach (MethodInfo m in group)
{
if (!bMethods.Contains(m))
return m;
}
}
return null;
}
private class MethodComparer : IEqualityComparer<MethodInfo>
{
public int GetHashCode(MethodInfo m) => m.Name.GetHashCode();
public bool Equals(MethodInfo a, MethodInfo b)
{
if (a.Name != b.Name)
return false;
ParameterInfo[] pas = a.GetParameters();
ParameterInfo[] pbs = b.GetParameters();
if (pas.Length != pbs.Length)
return false;
Type[] aArgs = a.GetGenericArguments();
Type[] bArgs = b.GetGenericArguments();
for (int i = 0, n = pas.Length; i < n; i++)
{
ParameterInfo pa = pas[i];
ParameterInfo pb = pbs[i];
Type ta = Strip(pa.ParameterType);
Type tb = Strip(pb.ParameterType);
if (ta.GetTypeInfo().IsGenericType && tb.GetTypeInfo().IsGenericType)
{
if (ta.GetGenericTypeDefinition() != tb.GetGenericTypeDefinition())
{
return false;
}
}
else if (ta.IsGenericParameter && tb.IsGenericParameter)
{
return Array.IndexOf(aArgs, ta) == Array.IndexOf(bArgs, tb);
}
else if (ta != tb)
{
return false;
}
}
return true;
}
private Type Strip(Type t)
{
if (t.GetTypeInfo().IsGenericType)
{
Type g = t;
if (!g.GetTypeInfo().IsGenericTypeDefinition)
{
g = t.GetGenericTypeDefinition();
}
if (g == typeof(IQueryable<>) || g == typeof(IEnumerable<>))
{
return typeof(IEnumerable);
}
if (g == typeof(Expression<>))
{
return t.GetGenericArguments()[0];
}
if (g == typeof(IOrderedEnumerable<>) || g == typeof(IOrderedQueryable<>))
{
return typeof(IOrderedQueryable);
}
}
else
{
if (t == typeof(IQueryable))
{
return typeof(IEnumerable);
}
}
return t;
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/jit64/valuetypes/nullable/castclass/interface/castclass-interface015.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 ulong 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((ulong)(IComparable)o, Helper.Create(default(ulong)));
}
private static bool BoxUnboxToQ(object o)
{
return Helper.Compare((ulong?)(IComparable)o, Helper.Create(default(ulong)));
}
private static int Main()
{
ulong? s = Helper.Create(default(ulong));
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 ulong 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((ulong)(IComparable)o, Helper.Create(default(ulong)));
}
private static bool BoxUnboxToQ(object o)
{
return Helper.Compare((ulong?)(IComparable)o, Helper.Create(default(ulong)));
}
private static int Main()
{
ulong? s = Helper.Create(default(ulong));
if (BoxUnboxToNQ(s) && BoxUnboxToQ(s))
return ExitCode.Passed;
else
return ExitCode.Failed;
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/baseservices/threading/regressions/whidbey_m3/200176.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
<!-- Test unsupported outside of windows -->
<CLRTestTargetUnsupported Condition="'$(TargetsWindows)' != 'true'">true</CLRTestTargetUnsupported>
</PropertyGroup>
<ItemGroup>
<Compile Include="200176.cs" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
<!-- Test unsupported outside of windows -->
<CLRTestTargetUnsupported Condition="'$(TargetsWindows)' != 'true'">true</CLRTestTargetUnsupported>
</PropertyGroup>
<ItemGroup>
<Compile Include="200176.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./docs/project/api-review-process.md | # API Review Process
.NET has a long standing history of taking API usability extremely seriously. Thus, we generally review every single API that is added to the product. This page discusses how we conduct design reviews for components that are open sourced.
## Which APIs should be reviewed?
The rule of thumb is that we (**dotnet/runtime**) review every API that is being added to the `System.*` namespaces. In some cases, we also review APIs that are added to other namespaces, such as `Microsoft.*`. We mostly do this for high impact APIs, such as Roslyn, and when both the owner of the technology and we feel there is win-win for both sides if we review the APIs. However, we can't scale to review all APIs being added to .NET.
## Process
```mermaid
sequenceDiagram
participant R as Requester
participant O as Runtime Owners
participant F as API review board <br> (FXDC)
R ->> O: Files issue under dotnet/runtime
note over O: Assigns owner
note over R, O: Discussion
O ->> F: Label api-ready-for-review
note over F: Performs review
alt is accepted
F ->> R: Label api-approved
else is work needed
F ->> O: Label api-needs-work
else is rejected
F ->> R: Issue is closed
end
```
## Steps
1. **Requester files an issue**. The issue description should contain a speclet that represents a sketch of the new APIs, including samples on how the APIs are being used. The goal isn't to get a complete API list, but a good handle on how the new APIs would roughly look like and in what scenarios they are being used. Please use [this template](https://github.com/dotnet/runtime/issues/new?assignees=&labels=api-suggestion&template=02_api_proposal.yml&title=%5BAPI+Proposal%5D%3A+). The issue should have the label `api-suggestion`. Here is [a good example](https://github.com/dotnet/runtime/issues/38344) of an issue following that template.
2. **We assign an owner**. We'll assign a dedicated owner from our side that
sponsors the issue. This is usually [the area owner](issue-guide.md#areas) for which the API proposal or design change request was filed for.
3. **Discussion**. The goal of the discussion is to help the assignee to make a
decision whether we want to pursue the proposal or not. In this phase, the goal
isn't necessarily to perform an in-depth review; rather, we want to make sure
that the proposal is actionable, i.e. has a concrete design, a sketch of the
APIs and some code samples that show how it should be used. If changes are necessary, the owner will set the label `api-needs-work`. To make the changes, the requester should edit the top-most issue description. This allows folks joining later to understand the most recent proposal. To avoid confusion, the requester can maintain a tiny change log, like a bolded "Updates:" followed by a bullet point list of the updates that were being made. When the feedback is addressed, the requester should notify the owner to re-review the changes.
4. **Owner makes decision**. When the owner believes enough information is available to make a decision, they will update the issue accordingly:
* **Mark for review**. If the owner believes the proposal is actionable, they will label the issue with `api-ready-for-review`. [Here is a good example](https://github.com/dotnet/runtime/issues/15725) of a strong API proposal.
* **Close as not actionable**. In case the issue didn't get enough traction to be distilled into a concrete proposal, the owner will close the issue.
* **Close as won't fix as proposed**. Sometimes, the issue that is raised is a good one but the owner thinks the concrete proposal is not the right way to tackle the problem. In most cases, the owner will try to steer the discussion in a direction that results in a design that we believe is appropriate. However, for some proposals the problem is at the heart of the design which can't easily be changed without starting a new proposal. In those cases, the owner will close the issue and explain the issue the design has.
* **Close as won't fix**. Similarly, if proposal is taking the product in a direction we simply don't want to go, the issue might also get closed. In that case, the problem isn't the proposed design but in the issue itself.
5. **API gets reviewed**. The group conducting the review is called *FXDC*, which stands for *framework design core*. In the review, we'll take notes and provide feedback. Reviews are streamed live on [YouTube](https://www.youtube.com/playlist?list=PL1rZQsJPBU2S49OQPjupSJF-qeIEz9_ju). After the review, we'll publish the notes in the [API Review repository](https://github.com/dotnet/apireviews) and at the end of the relevant issue. A good example is the [review of immutable collections](https://github.com/dotnet/apireviews/tree/master/2015/01-07-immutable). Multiple outcomes are possible:
* **Approved**. In this case the label `api-ready-for-review` is replaced
with `api-approved`.
* **Needs work**. In case we believe the proposal isn't ready yet, we'll
replace the label `api-ready-for-review` with `api-needs-work`.
* **Rejected**. In case we believe the proposal isn't a direction we want to go after, we simply write a comment and close the issue.
## Review schedule
There are three methods to get an API review:
* **Get into the backlog**. Generally speaking, filing an issue in `dotnet/runtime` and applying the label `api-ready-for-review` on it will make your issue show up during API reviews. The downside is that we generally walk the backlog oldest-newest, so your issue might not be looked at for a while. Progress of issues can be tracked via https://aka.ms/ready-for-api-review.
* **Fast track**. If you need to bypass the backlog apply both `api-ready-for-review` and `blocking`. All blocking issues are looked at before we walk the backlog.
* **Dedicated review**. This only applies to area owners. If an issue you are the area owner for needs an hour or longer, send an email to FXDC and we book dedicated time. Rule of thumb: if the API proposal has more than a dozen APIs and/or the APIs have complex policy, then you need 60 min or more. When in doubt, send mail to FXDC.
Unfortunately, we have throughput issues and try our best to get more stuff done. We normally have one two-hour slot per week, but we're currently operating at three two hour slots.
## Pull requests
Pull requests against **dotnet/runtime** shouldn't be submitted before getting approval. Also, we don't want to get work in progress (WIP) PR's. The reason being that we want to reduce the number pending PRs so that we can focus on the work the community expects we take action on.
If you want to collaborate with other people on the design, feel free to perform the work in a branch in your own fork. If you want to track your TODOs in the description of a PR, you can always submit a PR against your own fork. Also, feel free to advertise your PR by linking it from the issue you filed against **dotnet/runtime** in the first step above.
## API Design Guidelines
The .NET design guidelines are captured in the famous book [Framework Design Guidelines](https://www.amazon.com/dp/0135896460) by Krzysztof Cwalina, Jeremy Barton and Brad Abrams.
A digest with the most important guidelines are available in our [documentation](../coding-guidelines/framework-design-guidelines-digest.md). Long term, we'd like to publish the individual guidelines in standalone repo on which we can also accept PRs and -- more importantly for API reviews -- link to.
## API Review Notes
The API review notes are being published in [API Review repository](https://github.com/dotnet/apireviews).
| # API Review Process
.NET has a long standing history of taking API usability extremely seriously. Thus, we generally review every single API that is added to the product. This page discusses how we conduct design reviews for components that are open sourced.
## Which APIs should be reviewed?
The rule of thumb is that we (**dotnet/runtime**) review every API that is being added to the `System.*` namespaces. In some cases, we also review APIs that are added to other namespaces, such as `Microsoft.*`. We mostly do this for high impact APIs, such as Roslyn, and when both the owner of the technology and we feel there is win-win for both sides if we review the APIs. However, we can't scale to review all APIs being added to .NET.
## Process
```mermaid
sequenceDiagram
participant R as Requester
participant O as Runtime Owners
participant F as API review board <br> (FXDC)
R ->> O: Files issue under dotnet/runtime
note over O: Assigns owner
note over R, O: Discussion
O ->> F: Label api-ready-for-review
note over F: Performs review
alt is accepted
F ->> R: Label api-approved
else is work needed
F ->> O: Label api-needs-work
else is rejected
F ->> R: Issue is closed
end
```
## Steps
1. **Requester files an issue**. The issue description should contain a speclet that represents a sketch of the new APIs, including samples on how the APIs are being used. The goal isn't to get a complete API list, but a good handle on how the new APIs would roughly look like and in what scenarios they are being used. Please use [this template](https://github.com/dotnet/runtime/issues/new?assignees=&labels=api-suggestion&template=02_api_proposal.yml&title=%5BAPI+Proposal%5D%3A+). The issue should have the label `api-suggestion`. Here is [a good example](https://github.com/dotnet/runtime/issues/38344) of an issue following that template.
2. **We assign an owner**. We'll assign a dedicated owner from our side that
sponsors the issue. This is usually [the area owner](issue-guide.md#areas) for which the API proposal or design change request was filed for.
3. **Discussion**. The goal of the discussion is to help the assignee to make a
decision whether we want to pursue the proposal or not. In this phase, the goal
isn't necessarily to perform an in-depth review; rather, we want to make sure
that the proposal is actionable, i.e. has a concrete design, a sketch of the
APIs and some code samples that show how it should be used. If changes are necessary, the owner will set the label `api-needs-work`. To make the changes, the requester should edit the top-most issue description. This allows folks joining later to understand the most recent proposal. To avoid confusion, the requester can maintain a tiny change log, like a bolded "Updates:" followed by a bullet point list of the updates that were being made. When the feedback is addressed, the requester should notify the owner to re-review the changes.
4. **Owner makes decision**. When the owner believes enough information is available to make a decision, they will update the issue accordingly:
* **Mark for review**. If the owner believes the proposal is actionable, they will label the issue with `api-ready-for-review`. [Here is a good example](https://github.com/dotnet/runtime/issues/15725) of a strong API proposal.
* **Close as not actionable**. In case the issue didn't get enough traction to be distilled into a concrete proposal, the owner will close the issue.
* **Close as won't fix as proposed**. Sometimes, the issue that is raised is a good one but the owner thinks the concrete proposal is not the right way to tackle the problem. In most cases, the owner will try to steer the discussion in a direction that results in a design that we believe is appropriate. However, for some proposals the problem is at the heart of the design which can't easily be changed without starting a new proposal. In those cases, the owner will close the issue and explain the issue the design has.
* **Close as won't fix**. Similarly, if proposal is taking the product in a direction we simply don't want to go, the issue might also get closed. In that case, the problem isn't the proposed design but in the issue itself.
5. **API gets reviewed**. The group conducting the review is called *FXDC*, which stands for *framework design core*. In the review, we'll take notes and provide feedback. Reviews are streamed live on [YouTube](https://www.youtube.com/playlist?list=PL1rZQsJPBU2S49OQPjupSJF-qeIEz9_ju). After the review, we'll publish the notes in the [API Review repository](https://github.com/dotnet/apireviews) and at the end of the relevant issue. A good example is the [review of immutable collections](https://github.com/dotnet/apireviews/tree/master/2015/01-07-immutable). Multiple outcomes are possible:
* **Approved**. In this case the label `api-ready-for-review` is replaced
with `api-approved`.
* **Needs work**. In case we believe the proposal isn't ready yet, we'll
replace the label `api-ready-for-review` with `api-needs-work`.
* **Rejected**. In case we believe the proposal isn't a direction we want to go after, we simply write a comment and close the issue.
## Review schedule
There are three methods to get an API review:
* **Get into the backlog**. Generally speaking, filing an issue in `dotnet/runtime` and applying the label `api-ready-for-review` on it will make your issue show up during API reviews. The downside is that we generally walk the backlog oldest-newest, so your issue might not be looked at for a while. Progress of issues can be tracked via https://aka.ms/ready-for-api-review.
* **Fast track**. If you need to bypass the backlog apply both `api-ready-for-review` and `blocking`. All blocking issues are looked at before we walk the backlog.
* **Dedicated review**. This only applies to area owners. If an issue you are the area owner for needs an hour or longer, send an email to FXDC and we book dedicated time. Rule of thumb: if the API proposal has more than a dozen APIs and/or the APIs have complex policy, then you need 60 min or more. When in doubt, send mail to FXDC.
Unfortunately, we have throughput issues and try our best to get more stuff done. We normally have one two-hour slot per week, but we're currently operating at three two hour slots.
## Pull requests
Pull requests against **dotnet/runtime** shouldn't be submitted before getting approval. Also, we don't want to get work in progress (WIP) PR's. The reason being that we want to reduce the number pending PRs so that we can focus on the work the community expects we take action on.
If you want to collaborate with other people on the design, feel free to perform the work in a branch in your own fork. If you want to track your TODOs in the description of a PR, you can always submit a PR against your own fork. Also, feel free to advertise your PR by linking it from the issue you filed against **dotnet/runtime** in the first step above.
## API Design Guidelines
The .NET design guidelines are captured in the famous book [Framework Design Guidelines](https://www.amazon.com/dp/0135896460) by Krzysztof Cwalina, Jeremy Barton and Brad Abrams.
A digest with the most important guidelines are available in our [documentation](../coding-guidelines/framework-design-guidelines-digest.md). Long term, we'd like to publish the individual guidelines in standalone repo on which we can also accept PRs and -- more importantly for API reviews -- link to.
## API Review Notes
The API review notes are being published in [API Review repository](https://github.com/dotnet/apireviews).
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Versioning;
using System.Text;
namespace System.Data.Common
{
internal partial class DbConnectionOptions
{
// instances of this class are intended to be immutable, i.e readonly
// used by pooling classes so it is much easier to verify correctness
// when not worried about the class being modified during execution
internal readonly bool _hasUserIdKeyword;
// differences between OleDb and Odbc
// ODBC:
// https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqldriverconnect-function
// do not support == -> = in keywords
// first key-value pair wins
// quote values using \{ and \}, only driver= and pwd= appear to generically allow quoting
// do not strip quotes from value, or add quotes except for driver keyword
// OLEDB:
// https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-string-syntax#oledb-connection-string-syntax
// support == -> = in keywords
// last key-value pair wins
// quote values using \" or \'
// strip quotes from value
internal readonly bool _useOdbcRules;
// called by derived classes that may cache based on connectionString
public DbConnectionOptions(string connectionString)
: this(connectionString, null, false)
{
}
// synonyms hashtable is meant to be read-only translation of parsed string
// keywords/synonyms to a known keyword string
public DbConnectionOptions(string connectionString, Dictionary<string, string>? synonyms, bool useOdbcRules)
{
_useOdbcRules = useOdbcRules;
_parsetable = new Dictionary<string, string?>();
_usersConnectionString = ((null != connectionString) ? connectionString : "");
// first pass on parsing, initial syntax check
if (0 < _usersConnectionString.Length)
{
_keyChain = ParseInternal(_parsetable, _usersConnectionString, true, synonyms, _useOdbcRules);
_hasPasswordKeyword = (_parsetable.ContainsKey(KEY.Password) || _parsetable.ContainsKey(SYNONYM.Pwd));
_hasUserIdKeyword = (_parsetable.ContainsKey(KEY.User_ID) || _parsetable.ContainsKey(SYNONYM.UID));
}
}
protected DbConnectionOptions(DbConnectionOptions connectionOptions)
{ // Clone used by SqlConnectionString
_usersConnectionString = connectionOptions._usersConnectionString;
_hasPasswordKeyword = connectionOptions._hasPasswordKeyword;
_hasUserIdKeyword = connectionOptions._hasUserIdKeyword;
_useOdbcRules = connectionOptions._useOdbcRules;
_parsetable = connectionOptions._parsetable;
_keyChain = connectionOptions._keyChain;
}
internal string UsersConnectionStringForTrace()
{
return UsersConnectionString(true, true);
}
internal bool HasBlankPassword
{
get
{
if (!ConvertValueToIntegratedSecurity())
{
if (_parsetable.ContainsKey(KEY.Password))
{
return string.IsNullOrEmpty(_parsetable[KEY.Password]);
}
else
if (_parsetable.ContainsKey(SYNONYM.Pwd))
{
return string.IsNullOrEmpty(_parsetable[SYNONYM.Pwd]); // MDAC 83097
}
else
{
return ((_parsetable.ContainsKey(KEY.User_ID) && !string.IsNullOrEmpty(_parsetable[KEY.User_ID])) || (_parsetable.ContainsKey(SYNONYM.UID) && !string.IsNullOrEmpty(_parsetable[SYNONYM.UID])));
}
}
return false;
}
}
public bool IsEmpty
{
get { return (null == _keyChain); }
}
internal Dictionary<string, string?> Parsetable
{
get { return _parsetable; }
}
public ICollection Keys
{
get { return _parsetable.Keys; }
}
public string? this[string keyword]
{
get { return _parsetable[keyword]; }
}
internal static void AppendKeyValuePairBuilder(StringBuilder builder, string keyName, string? keyValue, bool useOdbcRules)
{
ADP.CheckArgumentNull(builder, nameof(builder));
ADP.CheckArgumentLength(keyName, nameof(keyName));
if ((null == keyName) || !s_connectionStringValidKeyRegex.IsMatch(keyName))
{
throw ADP.InvalidKeyname(keyName);
}
if ((null != keyValue) && !IsValueValidInternal(keyValue))
{
throw ADP.InvalidValue(keyName);
}
if ((0 < builder.Length) && (';' != builder[builder.Length - 1]))
{
builder.Append(';');
}
if (useOdbcRules)
{
builder.Append(keyName);
}
else
{
builder.Append(keyName.Replace("=", "=="));
}
builder.Append('=');
if (null != keyValue)
{ // else <keyword>=;
if (useOdbcRules)
{
if ((0 < keyValue.Length) &&
// string.Contains(char) is .NetCore2.1+ specific
(('{' == keyValue[0]) || (0 <= keyValue.IndexOf(';')) || (string.Equals(DbConnectionStringKeywords.Driver, keyName, StringComparison.OrdinalIgnoreCase))) &&
!s_connectionStringQuoteOdbcValueRegex.IsMatch(keyValue))
{
// always quote Driver value (required for ODBC Version 2.65 and earlier)
// always quote values that contain a ';'
builder.Append('{').Append(keyValue.Replace("}", "}}")).Append('}');
}
else
{
builder.Append(keyValue);
}
}
else if (s_connectionStringQuoteValueRegex.IsMatch(keyValue))
{
// <value> -> <value>
builder.Append(keyValue);
}
// string.Contains(char) is .NetCore2.1+ specific
else if ((-1 != keyValue.IndexOf('\"')) && (-1 == keyValue.IndexOf('\'')))
{
// <val"ue> -> <'val"ue'>
builder.Append('\'');
builder.Append(keyValue);
builder.Append('\'');
}
else
{
// <val'ue> -> <"val'ue">
// <=value> -> <"=value">
// <;value> -> <";value">
// < value> -> <" value">
// <va lue> -> <"va lue">
// <va'"lue> -> <"va'""lue">
builder.Append('\"');
builder.Append(keyValue.Replace("\"", "\"\""));
builder.Append('\"');
}
}
}
// same as Boolean, but with SSPI thrown in as valid yes
public bool ConvertValueToIntegratedSecurity()
{
object? value = _parsetable[KEY.Integrated_Security];
if (null == value)
{
return false;
}
return ConvertValueToIntegratedSecurityInternal((string)value);
}
internal bool ConvertValueToIntegratedSecurityInternal(string stringValue)
{
if (CompareInsensitiveInvariant(stringValue, "sspi") || CompareInsensitiveInvariant(stringValue, "true") || CompareInsensitiveInvariant(stringValue, "yes"))
return true;
else if (CompareInsensitiveInvariant(stringValue, "false") || CompareInsensitiveInvariant(stringValue, "no"))
return false;
else
{
string tmp = stringValue.Trim(); // Remove leading & trailing white space.
if (CompareInsensitiveInvariant(tmp, "sspi") || CompareInsensitiveInvariant(tmp, "true") || CompareInsensitiveInvariant(tmp, "yes"))
return true;
else if (CompareInsensitiveInvariant(tmp, "false") || CompareInsensitiveInvariant(tmp, "no"))
return false;
else
{
throw ADP.InvalidConnectionOptionValue(KEY.Integrated_Security);
}
}
}
public int ConvertValueToInt32(string keyName, int defaultValue)
{
object? value = _parsetable[keyName];
if (null == value)
{
return defaultValue;
}
return ConvertToInt32Internal(keyName, (string)value);
}
internal static int ConvertToInt32Internal(string keyname, string stringValue)
{
try
{
return int.Parse(stringValue, System.Globalization.NumberStyles.Integer, CultureInfo.InvariantCulture);
}
catch (FormatException e)
{
throw ADP.InvalidConnectionOptionValue(keyname, e);
}
catch (OverflowException e)
{
throw ADP.InvalidConnectionOptionValue(keyname, e);
}
}
public string ConvertValueToString(string keyName, string defaultValue)
{
string? value = _parsetable[keyName];
return ((null != value) ? value : defaultValue);
}
public bool ContainsKey(string keyword)
{
return _parsetable.ContainsKey(keyword);
}
// SxS notes:
// * this method queries "DataDirectory" value from the current AppDomain.
// This string is used for to replace "!DataDirectory!" values in the connection string, it is not considered as an "exposed resource".
// * This method uses GetFullPath to validate that root path is valid, the result is not exposed out.
internal static string? ExpandDataDirectory(string keyword, string? value, ref string? datadir)
{
string? fullPath = null;
if ((null != value) && value.StartsWith(DataDirectory, StringComparison.OrdinalIgnoreCase))
{
string? rootFolderPath = datadir;
if (null == rootFolderPath)
{
// find the replacement path
object? rootFolderObject = AppDomain.CurrentDomain.GetData("DataDirectory");
rootFolderPath = (rootFolderObject as string);
if ((null != rootFolderObject) && (null == rootFolderPath))
{
throw ADP.InvalidDataDirectory();
}
else if (string.IsNullOrEmpty(rootFolderPath))
{
rootFolderPath = AppDomain.CurrentDomain.BaseDirectory;
}
if (null == rootFolderPath)
{
rootFolderPath = "";
}
// cache the |DataDir| for ExpandDataDirectories
datadir = rootFolderPath;
}
// We don't know if rootFolderpath ends with '\', and we don't know if the given name starts with onw
int fileNamePosition = DataDirectory.Length; // filename starts right after the '|datadirectory|' keyword
bool rootFolderEndsWith = (0 < rootFolderPath.Length) && rootFolderPath[rootFolderPath.Length - 1] == '\\';
bool fileNameStartsWith = (fileNamePosition < value.Length) && value[fileNamePosition] == '\\';
// replace |datadirectory| with root folder path
if (!rootFolderEndsWith && !fileNameStartsWith)
{
// need to insert '\'
fullPath = rootFolderPath + '\\' + value.Substring(fileNamePosition);
}
else if (rootFolderEndsWith && fileNameStartsWith)
{
// need to strip one out
fullPath = rootFolderPath + value.Substring(fileNamePosition + 1);
}
else
{
// simply concatenate the strings
fullPath = rootFolderPath + value.Substring(fileNamePosition);
}
// verify root folder path is a real path without unexpected "..\"
if (!ADP.GetFullPath(fullPath).StartsWith(rootFolderPath, StringComparison.Ordinal))
{
throw ADP.InvalidConnectionOptionValue(keyword);
}
}
return fullPath;
}
internal string? ExpandDataDirectories(ref string? filename, ref int position)
{
string? value;
StringBuilder builder = new StringBuilder(_usersConnectionString.Length);
string? datadir = null;
int copyPosition = 0;
bool expanded = false;
for (NameValuePair? current = _keyChain; null != current; current = current.Next)
{
value = current.Value;
// remove duplicate keyswords from connectionstring
//if ((object)this[current.Name] != (object)value) {
// expanded = true;
// copyPosition += current.Length;
// continue;
//}
// There is a set of keywords we explictly do NOT want to expand |DataDirectory| on
if (_useOdbcRules)
{
switch (current.Name)
{
case DbConnectionOptionKeywords.Driver:
case DbConnectionOptionKeywords.Pwd:
case DbConnectionOptionKeywords.UID:
break;
default:
value = ExpandDataDirectory(current.Name, value, ref datadir);
break;
}
}
else
{
switch (current.Name)
{
case DbConnectionOptionKeywords.Provider:
case DbConnectionOptionKeywords.DataProvider:
case DbConnectionOptionKeywords.RemoteProvider:
case DbConnectionOptionKeywords.ExtendedProperties:
case DbConnectionOptionKeywords.UserID:
case DbConnectionOptionKeywords.Password:
case DbConnectionOptionKeywords.UID:
case DbConnectionOptionKeywords.Pwd:
break;
default:
value = ExpandDataDirectory(current.Name, value, ref datadir);
break;
}
}
if (null == value)
{
value = current.Value;
}
if (_useOdbcRules || (DbConnectionOptionKeywords.FileName != current.Name))
{
if (value != current.Value)
{
expanded = true;
AppendKeyValuePairBuilder(builder, current.Name, value, _useOdbcRules);
builder.Append(';');
}
else
{
builder.Append(_usersConnectionString, copyPosition, current.Length);
}
}
else
{
// strip out 'File Name=myconnection.udl' for OleDb
// remembering is value for which UDL file to open
// and where to insert the strnig
expanded = true;
filename = value;
position = builder.Length;
}
copyPosition += current.Length;
}
if (expanded)
{
value = builder.ToString();
}
else
{
value = null;
}
return value;
}
internal string ExpandKeyword(string keyword, string replacementValue)
{
// preserve duplicates, updated keyword value with replacement value
// if keyword not specified, append to end of the string
bool expanded = false;
int copyPosition = 0;
StringBuilder builder = new StringBuilder(_usersConnectionString.Length);
for (NameValuePair? current = _keyChain; null != current; current = current.Next)
{
if ((current.Name == keyword) && (current.Value == this[keyword]))
{
// only replace the parse end-result value instead of all values
// so that when duplicate-keywords occur other original values remain in place
AppendKeyValuePairBuilder(builder, current.Name, replacementValue, _useOdbcRules);
builder.Append(';');
expanded = true;
}
else
{
builder.Append(_usersConnectionString, copyPosition, current.Length);
}
copyPosition += current.Length;
}
if (!expanded)
{
//
Debug.Assert(!_useOdbcRules, "ExpandKeyword not ready for Odbc");
AppendKeyValuePairBuilder(builder, keyword, replacementValue, _useOdbcRules);
}
return builder.ToString();
}
internal static void ValidateKeyValuePair(string keyword, string value)
{
if ((null == keyword) || !s_connectionStringValidKeyRegex.IsMatch(keyword))
{
throw ADP.InvalidKeyname(keyword);
}
if ((null != value) && !s_connectionStringValidValueRegex.IsMatch(value))
{
throw ADP.InvalidValue(keyword);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Versioning;
using System.Text;
namespace System.Data.Common
{
internal partial class DbConnectionOptions
{
// instances of this class are intended to be immutable, i.e readonly
// used by pooling classes so it is much easier to verify correctness
// when not worried about the class being modified during execution
internal readonly bool _hasUserIdKeyword;
// differences between OleDb and Odbc
// ODBC:
// https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqldriverconnect-function
// do not support == -> = in keywords
// first key-value pair wins
// quote values using \{ and \}, only driver= and pwd= appear to generically allow quoting
// do not strip quotes from value, or add quotes except for driver keyword
// OLEDB:
// https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-string-syntax#oledb-connection-string-syntax
// support == -> = in keywords
// last key-value pair wins
// quote values using \" or \'
// strip quotes from value
internal readonly bool _useOdbcRules;
// called by derived classes that may cache based on connectionString
public DbConnectionOptions(string connectionString)
: this(connectionString, null, false)
{
}
// synonyms hashtable is meant to be read-only translation of parsed string
// keywords/synonyms to a known keyword string
public DbConnectionOptions(string connectionString, Dictionary<string, string>? synonyms, bool useOdbcRules)
{
_useOdbcRules = useOdbcRules;
_parsetable = new Dictionary<string, string?>();
_usersConnectionString = ((null != connectionString) ? connectionString : "");
// first pass on parsing, initial syntax check
if (0 < _usersConnectionString.Length)
{
_keyChain = ParseInternal(_parsetable, _usersConnectionString, true, synonyms, _useOdbcRules);
_hasPasswordKeyword = (_parsetable.ContainsKey(KEY.Password) || _parsetable.ContainsKey(SYNONYM.Pwd));
_hasUserIdKeyword = (_parsetable.ContainsKey(KEY.User_ID) || _parsetable.ContainsKey(SYNONYM.UID));
}
}
protected DbConnectionOptions(DbConnectionOptions connectionOptions)
{ // Clone used by SqlConnectionString
_usersConnectionString = connectionOptions._usersConnectionString;
_hasPasswordKeyword = connectionOptions._hasPasswordKeyword;
_hasUserIdKeyword = connectionOptions._hasUserIdKeyword;
_useOdbcRules = connectionOptions._useOdbcRules;
_parsetable = connectionOptions._parsetable;
_keyChain = connectionOptions._keyChain;
}
internal string UsersConnectionStringForTrace()
{
return UsersConnectionString(true, true);
}
internal bool HasBlankPassword
{
get
{
if (!ConvertValueToIntegratedSecurity())
{
if (_parsetable.ContainsKey(KEY.Password))
{
return string.IsNullOrEmpty(_parsetable[KEY.Password]);
}
else
if (_parsetable.ContainsKey(SYNONYM.Pwd))
{
return string.IsNullOrEmpty(_parsetable[SYNONYM.Pwd]); // MDAC 83097
}
else
{
return ((_parsetable.ContainsKey(KEY.User_ID) && !string.IsNullOrEmpty(_parsetable[KEY.User_ID])) || (_parsetable.ContainsKey(SYNONYM.UID) && !string.IsNullOrEmpty(_parsetable[SYNONYM.UID])));
}
}
return false;
}
}
public bool IsEmpty
{
get { return (null == _keyChain); }
}
internal Dictionary<string, string?> Parsetable
{
get { return _parsetable; }
}
public ICollection Keys
{
get { return _parsetable.Keys; }
}
public string? this[string keyword]
{
get { return _parsetable[keyword]; }
}
internal static void AppendKeyValuePairBuilder(StringBuilder builder, string keyName, string? keyValue, bool useOdbcRules)
{
ADP.CheckArgumentNull(builder, nameof(builder));
ADP.CheckArgumentLength(keyName, nameof(keyName));
if ((null == keyName) || !s_connectionStringValidKeyRegex.IsMatch(keyName))
{
throw ADP.InvalidKeyname(keyName);
}
if ((null != keyValue) && !IsValueValidInternal(keyValue))
{
throw ADP.InvalidValue(keyName);
}
if ((0 < builder.Length) && (';' != builder[builder.Length - 1]))
{
builder.Append(';');
}
if (useOdbcRules)
{
builder.Append(keyName);
}
else
{
builder.Append(keyName.Replace("=", "=="));
}
builder.Append('=');
if (null != keyValue)
{ // else <keyword>=;
if (useOdbcRules)
{
if ((0 < keyValue.Length) &&
// string.Contains(char) is .NetCore2.1+ specific
(('{' == keyValue[0]) || (0 <= keyValue.IndexOf(';')) || (string.Equals(DbConnectionStringKeywords.Driver, keyName, StringComparison.OrdinalIgnoreCase))) &&
!s_connectionStringQuoteOdbcValueRegex.IsMatch(keyValue))
{
// always quote Driver value (required for ODBC Version 2.65 and earlier)
// always quote values that contain a ';'
builder.Append('{').Append(keyValue.Replace("}", "}}")).Append('}');
}
else
{
builder.Append(keyValue);
}
}
else if (s_connectionStringQuoteValueRegex.IsMatch(keyValue))
{
// <value> -> <value>
builder.Append(keyValue);
}
// string.Contains(char) is .NetCore2.1+ specific
else if ((-1 != keyValue.IndexOf('\"')) && (-1 == keyValue.IndexOf('\'')))
{
// <val"ue> -> <'val"ue'>
builder.Append('\'');
builder.Append(keyValue);
builder.Append('\'');
}
else
{
// <val'ue> -> <"val'ue">
// <=value> -> <"=value">
// <;value> -> <";value">
// < value> -> <" value">
// <va lue> -> <"va lue">
// <va'"lue> -> <"va'""lue">
builder.Append('\"');
builder.Append(keyValue.Replace("\"", "\"\""));
builder.Append('\"');
}
}
}
// same as Boolean, but with SSPI thrown in as valid yes
public bool ConvertValueToIntegratedSecurity()
{
object? value = _parsetable[KEY.Integrated_Security];
if (null == value)
{
return false;
}
return ConvertValueToIntegratedSecurityInternal((string)value);
}
internal bool ConvertValueToIntegratedSecurityInternal(string stringValue)
{
if (CompareInsensitiveInvariant(stringValue, "sspi") || CompareInsensitiveInvariant(stringValue, "true") || CompareInsensitiveInvariant(stringValue, "yes"))
return true;
else if (CompareInsensitiveInvariant(stringValue, "false") || CompareInsensitiveInvariant(stringValue, "no"))
return false;
else
{
string tmp = stringValue.Trim(); // Remove leading & trailing white space.
if (CompareInsensitiveInvariant(tmp, "sspi") || CompareInsensitiveInvariant(tmp, "true") || CompareInsensitiveInvariant(tmp, "yes"))
return true;
else if (CompareInsensitiveInvariant(tmp, "false") || CompareInsensitiveInvariant(tmp, "no"))
return false;
else
{
throw ADP.InvalidConnectionOptionValue(KEY.Integrated_Security);
}
}
}
public int ConvertValueToInt32(string keyName, int defaultValue)
{
object? value = _parsetable[keyName];
if (null == value)
{
return defaultValue;
}
return ConvertToInt32Internal(keyName, (string)value);
}
internal static int ConvertToInt32Internal(string keyname, string stringValue)
{
try
{
return int.Parse(stringValue, System.Globalization.NumberStyles.Integer, CultureInfo.InvariantCulture);
}
catch (FormatException e)
{
throw ADP.InvalidConnectionOptionValue(keyname, e);
}
catch (OverflowException e)
{
throw ADP.InvalidConnectionOptionValue(keyname, e);
}
}
public string ConvertValueToString(string keyName, string defaultValue)
{
string? value = _parsetable[keyName];
return ((null != value) ? value : defaultValue);
}
public bool ContainsKey(string keyword)
{
return _parsetable.ContainsKey(keyword);
}
// SxS notes:
// * this method queries "DataDirectory" value from the current AppDomain.
// This string is used for to replace "!DataDirectory!" values in the connection string, it is not considered as an "exposed resource".
// * This method uses GetFullPath to validate that root path is valid, the result is not exposed out.
internal static string? ExpandDataDirectory(string keyword, string? value, ref string? datadir)
{
string? fullPath = null;
if ((null != value) && value.StartsWith(DataDirectory, StringComparison.OrdinalIgnoreCase))
{
string? rootFolderPath = datadir;
if (null == rootFolderPath)
{
// find the replacement path
object? rootFolderObject = AppDomain.CurrentDomain.GetData("DataDirectory");
rootFolderPath = (rootFolderObject as string);
if ((null != rootFolderObject) && (null == rootFolderPath))
{
throw ADP.InvalidDataDirectory();
}
else if (string.IsNullOrEmpty(rootFolderPath))
{
rootFolderPath = AppDomain.CurrentDomain.BaseDirectory;
}
if (null == rootFolderPath)
{
rootFolderPath = "";
}
// cache the |DataDir| for ExpandDataDirectories
datadir = rootFolderPath;
}
// We don't know if rootFolderpath ends with '\', and we don't know if the given name starts with onw
int fileNamePosition = DataDirectory.Length; // filename starts right after the '|datadirectory|' keyword
bool rootFolderEndsWith = (0 < rootFolderPath.Length) && rootFolderPath[rootFolderPath.Length - 1] == '\\';
bool fileNameStartsWith = (fileNamePosition < value.Length) && value[fileNamePosition] == '\\';
// replace |datadirectory| with root folder path
if (!rootFolderEndsWith && !fileNameStartsWith)
{
// need to insert '\'
fullPath = rootFolderPath + '\\' + value.Substring(fileNamePosition);
}
else if (rootFolderEndsWith && fileNameStartsWith)
{
// need to strip one out
fullPath = rootFolderPath + value.Substring(fileNamePosition + 1);
}
else
{
// simply concatenate the strings
fullPath = rootFolderPath + value.Substring(fileNamePosition);
}
// verify root folder path is a real path without unexpected "..\"
if (!ADP.GetFullPath(fullPath).StartsWith(rootFolderPath, StringComparison.Ordinal))
{
throw ADP.InvalidConnectionOptionValue(keyword);
}
}
return fullPath;
}
internal string? ExpandDataDirectories(ref string? filename, ref int position)
{
string? value;
StringBuilder builder = new StringBuilder(_usersConnectionString.Length);
string? datadir = null;
int copyPosition = 0;
bool expanded = false;
for (NameValuePair? current = _keyChain; null != current; current = current.Next)
{
value = current.Value;
// remove duplicate keyswords from connectionstring
//if ((object)this[current.Name] != (object)value) {
// expanded = true;
// copyPosition += current.Length;
// continue;
//}
// There is a set of keywords we explictly do NOT want to expand |DataDirectory| on
if (_useOdbcRules)
{
switch (current.Name)
{
case DbConnectionOptionKeywords.Driver:
case DbConnectionOptionKeywords.Pwd:
case DbConnectionOptionKeywords.UID:
break;
default:
value = ExpandDataDirectory(current.Name, value, ref datadir);
break;
}
}
else
{
switch (current.Name)
{
case DbConnectionOptionKeywords.Provider:
case DbConnectionOptionKeywords.DataProvider:
case DbConnectionOptionKeywords.RemoteProvider:
case DbConnectionOptionKeywords.ExtendedProperties:
case DbConnectionOptionKeywords.UserID:
case DbConnectionOptionKeywords.Password:
case DbConnectionOptionKeywords.UID:
case DbConnectionOptionKeywords.Pwd:
break;
default:
value = ExpandDataDirectory(current.Name, value, ref datadir);
break;
}
}
if (null == value)
{
value = current.Value;
}
if (_useOdbcRules || (DbConnectionOptionKeywords.FileName != current.Name))
{
if (value != current.Value)
{
expanded = true;
AppendKeyValuePairBuilder(builder, current.Name, value, _useOdbcRules);
builder.Append(';');
}
else
{
builder.Append(_usersConnectionString, copyPosition, current.Length);
}
}
else
{
// strip out 'File Name=myconnection.udl' for OleDb
// remembering is value for which UDL file to open
// and where to insert the strnig
expanded = true;
filename = value;
position = builder.Length;
}
copyPosition += current.Length;
}
if (expanded)
{
value = builder.ToString();
}
else
{
value = null;
}
return value;
}
internal string ExpandKeyword(string keyword, string replacementValue)
{
// preserve duplicates, updated keyword value with replacement value
// if keyword not specified, append to end of the string
bool expanded = false;
int copyPosition = 0;
StringBuilder builder = new StringBuilder(_usersConnectionString.Length);
for (NameValuePair? current = _keyChain; null != current; current = current.Next)
{
if ((current.Name == keyword) && (current.Value == this[keyword]))
{
// only replace the parse end-result value instead of all values
// so that when duplicate-keywords occur other original values remain in place
AppendKeyValuePairBuilder(builder, current.Name, replacementValue, _useOdbcRules);
builder.Append(';');
expanded = true;
}
else
{
builder.Append(_usersConnectionString, copyPosition, current.Length);
}
copyPosition += current.Length;
}
if (!expanded)
{
//
Debug.Assert(!_useOdbcRules, "ExpandKeyword not ready for Odbc");
AppendKeyValuePairBuilder(builder, keyword, replacementValue, _useOdbcRules);
}
return builder.ToString();
}
internal static void ValidateKeyValuePair(string keyword, string value)
{
if ((null == keyword) || !s_connectionStringValidKeyRegex.IsMatch(keyword))
{
throw ADP.InvalidKeyname(keyword);
}
if ((null != value) && !s_connectionStringValidValueRegex.IsMatch(value))
{
throw ADP.InvalidValue(keyword);
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/Microsoft.Extensions.Logging.Debug/src/DebugLoggerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Microsoft.Extensions.Logging.Debug
{
/// <summary>
/// The provider for the <see cref="DebugLogger"/>.
/// </summary>
[ProviderAlias("Debug")]
public class DebugLoggerProvider : ILoggerProvider
{
/// <inheritdoc />
public ILogger CreateLogger(string name)
{
return new DebugLogger(name);
}
public void Dispose()
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Microsoft.Extensions.Logging.Debug
{
/// <summary>
/// The provider for the <see cref="DebugLogger"/>.
/// </summary>
[ProviderAlias("Debug")]
public class DebugLoggerProvider : ILoggerProvider
{
/// <inheritdoc />
public ILogger CreateLogger(string name)
{
return new DebugLogger(name);
}
public void Dispose()
{
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/GC/Regressions/v3.0/25252/25252.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).cs" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/Loader/classloader/DictionaryExpansion/DictionaryExpansion.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).cs" />
<ProjectReference Include="$(TestSourceDir)Common/CoreCLRTestLibrary/CoreCLRTestLibrary.csproj" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).cs" />
<ProjectReference Include="$(TestSourceDir)Common/CoreCLRTestLibrary/CoreCLRTestLibrary.csproj" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionDependency.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.Composition.Hosting.Util;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace System.Composition.Hosting.Core
{
/// <summary>
/// Describes a dependency that a part must have in order to fulfill an
/// <see cref="ExportDescriptorPromise"/>. Used by the composition engine during
/// initialization to determine whether the composition can be made, and if not,
/// what error to provide.
/// </summary>
public class CompositionDependency
{
private readonly ExportDescriptorPromise _target;
private readonly bool _isPrerequisite;
private readonly object _site;
private readonly CompositionContract _contract;
// Carrying some information to later use in error messages -
// it may be better to just store the message.
private readonly ExportDescriptorPromise[] _oversuppliedTargets;
/// <summary>
/// Construct a dependency on the specified target.
/// </summary>
/// <param name="target">The export descriptor promise from another part
/// that this part is dependent on.</param>
/// <param name="isPrerequisite">True if the dependency is a prerequisite
/// that must be satisfied before any exports can be retrieved from the dependent
/// part; otherwise, false.</param>
/// <param name="site">A marker used to identify the individual dependency among
/// those on the dependent part.</param>
/// <param name="contract">The contract required by the dependency.</param>
public static CompositionDependency Satisfied(CompositionContract contract!!, ExportDescriptorPromise target!!, bool isPrerequisite, object site!!)
{
return new CompositionDependency(contract, target, isPrerequisite, site);
}
/// <summary>
/// Construct a placeholder for a missing dependency. Note that this is different
/// from an optional dependency - a missing dependency is an error.
/// </summary>
/// <param name="site">A marker used to identify the individual dependency among
/// those on the dependent part.</param>
/// <param name="contract">The contract required by the dependency.</param>
public static CompositionDependency Missing(CompositionContract contract!!, object site!!)
{
return new CompositionDependency(contract, site);
}
/// <summary>
/// Construct a placeholder for an "exactly one" dependency that cannot be
/// configured because multiple target implementations exist.
/// </summary>
/// <param name="site">A marker used to identify the individual dependency among
/// those on the dependent part.</param>
/// <param name="targets">The targets found when expecting only one.</param>
/// <param name="contract">The contract required by the dependency.</param>
public static CompositionDependency Oversupplied(CompositionContract contract!!, IEnumerable<ExportDescriptorPromise> targets!!, object site!!)
{
return new CompositionDependency(contract, targets, site);
}
private CompositionDependency(CompositionContract contract, ExportDescriptorPromise target, bool isPrerequisite, object site)
{
_target = target;
_isPrerequisite = isPrerequisite;
_site = site;
_contract = contract;
}
private CompositionDependency(CompositionContract contract, object site)
{
_contract = contract;
_site = site;
}
private CompositionDependency(CompositionContract contract, IEnumerable<ExportDescriptorPromise> targets, object site)
{
_oversuppliedTargets = targets.ToArray();
_site = site;
_contract = contract;
}
/// <summary>
/// The export descriptor promise from another part
/// that this part is dependent on.
/// </summary>
public ExportDescriptorPromise Target { get { return _target; } }
/// <summary>
/// True if the dependency is a prerequisite
/// that must be satisfied before any exports can be retrieved from the dependent
/// part; otherwise, false.
/// </summary>
public bool IsPrerequisite { get { return _isPrerequisite; } }
/// <summary>
/// A marker used to identify the individual dependency among
/// those on the dependent part.
/// </summary>
public object Site { get { return _site; } }
/// <summary>
/// The contract required by the dependency.
/// </summary>
public CompositionContract Contract { get { return _contract; } }
/// <summary>
/// Creates a human-readable explanation of the dependency.
/// </summary>
/// <returns>The dependency represented as a string.</returns>
public override string ToString()
{
if (IsError)
return Site.ToString();
return SR.Format(SR.Dependency_ToStringFormat, Site, Target.Contract, Target.Origin);
}
internal bool IsError { get { return _target == null; } }
internal void DescribeError(StringBuilder message)
{
Debug.Assert(IsError, "Should be in error state.");
if (_oversuppliedTargets != null)
{
var list = Formatters.ReadableList(_oversuppliedTargets.Select(t => SR.Format(SR.Dependency_QuoteParameter, t.Origin)));
message.AppendFormat(SR.Dependency_TooManyExports, Contract, list);
}
else
{
message.AppendFormat(SR.Dependency_ExportNotFound, Contract);
}
}
}
}
| // 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.Composition.Hosting.Util;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace System.Composition.Hosting.Core
{
/// <summary>
/// Describes a dependency that a part must have in order to fulfill an
/// <see cref="ExportDescriptorPromise"/>. Used by the composition engine during
/// initialization to determine whether the composition can be made, and if not,
/// what error to provide.
/// </summary>
public class CompositionDependency
{
private readonly ExportDescriptorPromise _target;
private readonly bool _isPrerequisite;
private readonly object _site;
private readonly CompositionContract _contract;
// Carrying some information to later use in error messages -
// it may be better to just store the message.
private readonly ExportDescriptorPromise[] _oversuppliedTargets;
/// <summary>
/// Construct a dependency on the specified target.
/// </summary>
/// <param name="target">The export descriptor promise from another part
/// that this part is dependent on.</param>
/// <param name="isPrerequisite">True if the dependency is a prerequisite
/// that must be satisfied before any exports can be retrieved from the dependent
/// part; otherwise, false.</param>
/// <param name="site">A marker used to identify the individual dependency among
/// those on the dependent part.</param>
/// <param name="contract">The contract required by the dependency.</param>
public static CompositionDependency Satisfied(CompositionContract contract!!, ExportDescriptorPromise target!!, bool isPrerequisite, object site!!)
{
return new CompositionDependency(contract, target, isPrerequisite, site);
}
/// <summary>
/// Construct a placeholder for a missing dependency. Note that this is different
/// from an optional dependency - a missing dependency is an error.
/// </summary>
/// <param name="site">A marker used to identify the individual dependency among
/// those on the dependent part.</param>
/// <param name="contract">The contract required by the dependency.</param>
public static CompositionDependency Missing(CompositionContract contract!!, object site!!)
{
return new CompositionDependency(contract, site);
}
/// <summary>
/// Construct a placeholder for an "exactly one" dependency that cannot be
/// configured because multiple target implementations exist.
/// </summary>
/// <param name="site">A marker used to identify the individual dependency among
/// those on the dependent part.</param>
/// <param name="targets">The targets found when expecting only one.</param>
/// <param name="contract">The contract required by the dependency.</param>
public static CompositionDependency Oversupplied(CompositionContract contract!!, IEnumerable<ExportDescriptorPromise> targets!!, object site!!)
{
return new CompositionDependency(contract, targets, site);
}
private CompositionDependency(CompositionContract contract, ExportDescriptorPromise target, bool isPrerequisite, object site)
{
_target = target;
_isPrerequisite = isPrerequisite;
_site = site;
_contract = contract;
}
private CompositionDependency(CompositionContract contract, object site)
{
_contract = contract;
_site = site;
}
private CompositionDependency(CompositionContract contract, IEnumerable<ExportDescriptorPromise> targets, object site)
{
_oversuppliedTargets = targets.ToArray();
_site = site;
_contract = contract;
}
/// <summary>
/// The export descriptor promise from another part
/// that this part is dependent on.
/// </summary>
public ExportDescriptorPromise Target { get { return _target; } }
/// <summary>
/// True if the dependency is a prerequisite
/// that must be satisfied before any exports can be retrieved from the dependent
/// part; otherwise, false.
/// </summary>
public bool IsPrerequisite { get { return _isPrerequisite; } }
/// <summary>
/// A marker used to identify the individual dependency among
/// those on the dependent part.
/// </summary>
public object Site { get { return _site; } }
/// <summary>
/// The contract required by the dependency.
/// </summary>
public CompositionContract Contract { get { return _contract; } }
/// <summary>
/// Creates a human-readable explanation of the dependency.
/// </summary>
/// <returns>The dependency represented as a string.</returns>
public override string ToString()
{
if (IsError)
return Site.ToString();
return SR.Format(SR.Dependency_ToStringFormat, Site, Target.Contract, Target.Origin);
}
internal bool IsError { get { return _target == null; } }
internal void DescribeError(StringBuilder message)
{
Debug.Assert(IsError, "Should be in error state.");
if (_oversuppliedTargets != null)
{
var list = Formatters.ReadableList(_oversuppliedTargets.Select(t => SR.Format(SR.Dependency_QuoteParameter, t.Origin)));
message.AppendFormat(SR.Dependency_TooManyExports, Contract, list);
}
else
{
message.AppendFormat(SR.Dependency_ExportNotFound, Contract);
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/Interop/StructMarshalling/ReversePInvoke/MarshalExpStruct/ReversePInvokeManaged/ReversePInvokeTest.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<!-- Test unsupported outside of windows -->
<CLRTestTargetUnsupported Condition="'$(TargetsWindows)' != 'true'">true</CLRTestTargetUnsupported>
</PropertyGroup>
<ItemGroup>
<Compile Include="ReversePInvokeTest.cs" />
<Compile Include="..\..\Helper.cs" />
<Compile Include="..\..\Struct.cs" />
</ItemGroup>
<ItemGroup>
<CMakeProjectReference Include="..\CMakeLists.txt" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<!-- Test unsupported outside of windows -->
<CLRTestTargetUnsupported Condition="'$(TargetsWindows)' != 'true'">true</CLRTestTargetUnsupported>
</PropertyGroup>
<ItemGroup>
<Compile Include="ReversePInvokeTest.cs" />
<Compile Include="..\..\Helper.cs" />
<Compile Include="..\..\Struct.cs" />
</ItemGroup>
<ItemGroup>
<CMakeProjectReference Include="..\CMakeLists.txt" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Globalization.Extensions/tests/GetStringComparerTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Globalization.Tests
{
public class GetStringComparerTests
{
[Fact]
public void GetStringComparer_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("compareInfo", () => ((CompareInfo)null).GetStringComparer(CompareOptions.None));
AssertExtensions.Throws<ArgumentException>("options", () => new CultureInfo("tr-TR").CompareInfo.GetStringComparer((CompareOptions)0xFFFF));
AssertExtensions.Throws<ArgumentException>("options", () => new CultureInfo("tr-TR").CompareInfo.GetStringComparer(CompareOptions.Ordinal | CompareOptions.IgnoreCase));
AssertExtensions.Throws<ArgumentException>("options", () => new CultureInfo("tr-TR").CompareInfo.GetStringComparer(CompareOptions.OrdinalIgnoreCase | CompareOptions.IgnoreCase));
}
[Theory]
[InlineData("hello", "hello", "fr-FR", CompareOptions.IgnoreCase, 0, 0)]
[InlineData("hello", "HELLo", "fr-FR", CompareOptions.IgnoreCase, 0, 0)]
[InlineData("hello", null, "fr-FR", CompareOptions.IgnoreCase, 1, 1)]
[InlineData(null, "hello", "fr-FR", CompareOptions.IgnoreCase, -1, -1)]
[InlineData(null, null, "fr-FR", CompareOptions.IgnoreCase, 0, 0)]
[InlineData("abc", "def", "fr-FR", CompareOptions.IgnoreCase, -1, -1)]
[InlineData("abc", "ABC", "fr-FR", CompareOptions.IgnoreCase, 0, 0)]
[InlineData("def", "ABC", "fr-FR", CompareOptions.IgnoreCase, 1, 1)]
[InlineData("abc", "ABC", "en-US", CompareOptions.Ordinal, 1, 1)]
[InlineData("abc", "ABC", "en-US", CompareOptions.OrdinalIgnoreCase, 0, 0)]
[InlineData("Cot\u00E9", "cot\u00E9", "fr-FR", CompareOptions.IgnoreCase, 0, 0)]
[InlineData("cot\u00E9", "c\u00F4te", "fr-FR", CompareOptions.None, 1, -1)]
public static void Compare(string x, string y, string cultureName, CompareOptions options, int expectedNls, int expectedICU)
{
int expected = PlatformDetection.IsNlsGlobalization ? expectedNls : expectedICU;
StringComparer comparer = new CultureInfo(cultureName).CompareInfo.GetStringComparer(options);
Assert.Equal(expected, Math.Sign(comparer.Compare(x, y)));
Assert.Equal((expected == 0), comparer.Equals(x, y));
if (x != null && y != null)
{
Assert.Equal((expected == 0), comparer.GetHashCode(x).Equals(comparer.GetHashCode(y)));
}
}
[Fact]
public void GetHashCode_Null_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("obj", () => new CultureInfo("tr-TR").CompareInfo.GetStringComparer(CompareOptions.None).GetHashCode(null));
}
[Theory]
[InlineData("en-US", CompareOptions.IgnoreCase, "en-US", CompareOptions.IgnoreCase, true)]
[InlineData("en-US", CompareOptions.IgnoreCase, "en-US", CompareOptions.IgnoreSymbols, false)]
[InlineData("en-US", CompareOptions.IgnoreCase, "fr-FR", CompareOptions.IgnoreCase, false)]
[InlineData("en-US", CompareOptions.IgnoreCase, "fr-FR", CompareOptions.Ordinal, false)]
public void EqualsTest(string cultureName1, CompareOptions options1, string cultureName2, CompareOptions options2, bool expected)
{
StringComparer comparer1 = new CultureInfo(cultureName1).CompareInfo.GetStringComparer(options1);
StringComparer comparer2 = new CultureInfo(cultureName2).CompareInfo.GetStringComparer(options2);
Assert.Equal(expected, comparer1.Equals(comparer2));
Assert.Equal(expected, comparer1.GetHashCode().Equals(comparer2.GetHashCode()));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Globalization.Tests
{
public class GetStringComparerTests
{
[Fact]
public void GetStringComparer_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("compareInfo", () => ((CompareInfo)null).GetStringComparer(CompareOptions.None));
AssertExtensions.Throws<ArgumentException>("options", () => new CultureInfo("tr-TR").CompareInfo.GetStringComparer((CompareOptions)0xFFFF));
AssertExtensions.Throws<ArgumentException>("options", () => new CultureInfo("tr-TR").CompareInfo.GetStringComparer(CompareOptions.Ordinal | CompareOptions.IgnoreCase));
AssertExtensions.Throws<ArgumentException>("options", () => new CultureInfo("tr-TR").CompareInfo.GetStringComparer(CompareOptions.OrdinalIgnoreCase | CompareOptions.IgnoreCase));
}
[Theory]
[InlineData("hello", "hello", "fr-FR", CompareOptions.IgnoreCase, 0, 0)]
[InlineData("hello", "HELLo", "fr-FR", CompareOptions.IgnoreCase, 0, 0)]
[InlineData("hello", null, "fr-FR", CompareOptions.IgnoreCase, 1, 1)]
[InlineData(null, "hello", "fr-FR", CompareOptions.IgnoreCase, -1, -1)]
[InlineData(null, null, "fr-FR", CompareOptions.IgnoreCase, 0, 0)]
[InlineData("abc", "def", "fr-FR", CompareOptions.IgnoreCase, -1, -1)]
[InlineData("abc", "ABC", "fr-FR", CompareOptions.IgnoreCase, 0, 0)]
[InlineData("def", "ABC", "fr-FR", CompareOptions.IgnoreCase, 1, 1)]
[InlineData("abc", "ABC", "en-US", CompareOptions.Ordinal, 1, 1)]
[InlineData("abc", "ABC", "en-US", CompareOptions.OrdinalIgnoreCase, 0, 0)]
[InlineData("Cot\u00E9", "cot\u00E9", "fr-FR", CompareOptions.IgnoreCase, 0, 0)]
[InlineData("cot\u00E9", "c\u00F4te", "fr-FR", CompareOptions.None, 1, -1)]
public static void Compare(string x, string y, string cultureName, CompareOptions options, int expectedNls, int expectedICU)
{
int expected = PlatformDetection.IsNlsGlobalization ? expectedNls : expectedICU;
StringComparer comparer = new CultureInfo(cultureName).CompareInfo.GetStringComparer(options);
Assert.Equal(expected, Math.Sign(comparer.Compare(x, y)));
Assert.Equal((expected == 0), comparer.Equals(x, y));
if (x != null && y != null)
{
Assert.Equal((expected == 0), comparer.GetHashCode(x).Equals(comparer.GetHashCode(y)));
}
}
[Fact]
public void GetHashCode_Null_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("obj", () => new CultureInfo("tr-TR").CompareInfo.GetStringComparer(CompareOptions.None).GetHashCode(null));
}
[Theory]
[InlineData("en-US", CompareOptions.IgnoreCase, "en-US", CompareOptions.IgnoreCase, true)]
[InlineData("en-US", CompareOptions.IgnoreCase, "en-US", CompareOptions.IgnoreSymbols, false)]
[InlineData("en-US", CompareOptions.IgnoreCase, "fr-FR", CompareOptions.IgnoreCase, false)]
[InlineData("en-US", CompareOptions.IgnoreCase, "fr-FR", CompareOptions.Ordinal, false)]
public void EqualsTest(string cultureName1, CompareOptions options1, string cultureName2, CompareOptions options2, bool expected)
{
StringComparer comparer1 = new CultureInfo(cultureName1).CompareInfo.GetStringComparer(options1);
StringComparer comparer2 = new CultureInfo(cultureName2).CompareInfo.GetStringComparer(options2);
Assert.Equal(expected, comparer1.Equals(comparer2));
Assert.Equal(expected, comparer1.GetHashCode().Equals(comparer2.GetHashCode()));
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Console/ref/System.Console.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ------------------------------------------------------------------------------
// Changes to this file must follow the https://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System
{
public static partial class Console
{
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static System.ConsoleColor BackgroundColor { get { throw null; } set { } }
public static int BufferHeight { [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")] get { throw null; } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] set { } }
public static int BufferWidth { [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")] get { throw null; } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] set { } }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public static bool CapsLock { get { throw null; } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static int CursorLeft { get { throw null; } set { } }
public static int CursorSize { [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")] get { throw null; } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] set { } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static int CursorTop { get { throw null; } set { } }
public static bool CursorVisible { [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] get { throw null; } [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")] set { } }
public static System.IO.TextWriter Error { get { throw null; } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static System.ConsoleColor ForegroundColor { get { throw null; } set { } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static System.IO.TextReader In { get { throw null; } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static System.Text.Encoding InputEncoding { get { throw null; } set { } }
public static bool IsErrorRedirected { get { throw null; } }
public static bool IsInputRedirected { get { throw null; } }
public static bool IsOutputRedirected { get { throw null; } }
public static bool KeyAvailable { get { throw null; } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static int LargestWindowHeight { get { throw null; } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static int LargestWindowWidth { get { throw null; } }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public static bool NumberLock { get { throw null; } }
public static System.IO.TextWriter Out { get { throw null; } }
public static System.Text.Encoding OutputEncoding { get { throw null; } [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")] set { } }
public static string Title { [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] get { throw null; } [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")] set { } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static bool TreatControlCAsInput { get { throw null; } set { } }
public static int WindowHeight { [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")] get { throw null; } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] set { } }
public static int WindowLeft { get { throw null; } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] set { } }
public static int WindowTop { get { throw null; } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] set { } }
public static int WindowWidth { [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")] get { throw null; } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] set { } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static event System.ConsoleCancelEventHandler? CancelKeyPress { add { } remove { } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static void Beep() { }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public static void Beep(int frequency, int duration) { }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static void Clear() { }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static (int Left, int Top) GetCursorPosition() { throw null; }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop) { }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, System.ConsoleColor sourceForeColor, System.ConsoleColor sourceBackColor) { }
public static System.IO.Stream OpenStandardError() { throw null; }
public static System.IO.Stream OpenStandardError(int bufferSize) { throw null; }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static System.IO.Stream OpenStandardInput() { throw null; }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
public static System.IO.Stream OpenStandardInput(int bufferSize) { throw null; }
public static System.IO.Stream OpenStandardOutput() { throw null; }
public static System.IO.Stream OpenStandardOutput(int bufferSize) { throw null; }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
public static int Read() { throw null; }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static System.ConsoleKeyInfo ReadKey() { throw null; }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static System.ConsoleKeyInfo ReadKey(bool intercept) { throw null; }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
public static string? ReadLine() { throw null; }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static void ResetColor() { }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public static void SetBufferSize(int width, int height) { }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static void SetCursorPosition(int left, int top) { }
public static void SetError(System.IO.TextWriter newError) { }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static void SetIn(System.IO.TextReader newIn) { }
public static void SetOut(System.IO.TextWriter newOut) { }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public static void SetWindowPosition(int left, int top) { }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public static void SetWindowSize(int width, int height) { }
public static void Write(bool value) { }
public static void Write(char value) { }
public static void Write(char[]? buffer) { }
public static void Write(char[] buffer, int index, int count) { }
public static void Write(decimal value) { }
public static void Write(double value) { }
public static void Write(int value) { }
public static void Write(long value) { }
public static void Write(object? value) { }
public static void Write(float value) { }
public static void Write(string? value) { }
public static void Write(string format, object? arg0) { }
public static void Write(string format, object? arg0, object? arg1) { }
public static void Write(string format, object? arg0, object? arg1, object? arg2) { }
public static void Write(string format, params object?[]? arg) { }
[System.CLSCompliantAttribute(false)]
public static void Write(uint value) { }
[System.CLSCompliantAttribute(false)]
public static void Write(ulong value) { }
public static void WriteLine() { }
public static void WriteLine(bool value) { }
public static void WriteLine(char value) { }
public static void WriteLine(char[]? buffer) { }
public static void WriteLine(char[] buffer, int index, int count) { }
public static void WriteLine(decimal value) { }
public static void WriteLine(double value) { }
public static void WriteLine(int value) { }
public static void WriteLine(long value) { }
public static void WriteLine(object? value) { }
public static void WriteLine(float value) { }
public static void WriteLine(string? value) { }
public static void WriteLine(string format, object? arg0) { }
public static void WriteLine(string format, object? arg0, object? arg1) { }
public static void WriteLine(string format, object? arg0, object? arg1, object? arg2) { }
public static void WriteLine(string format, params object?[]? arg) { }
[System.CLSCompliantAttribute(false)]
public static void WriteLine(uint value) { }
[System.CLSCompliantAttribute(false)]
public static void WriteLine(ulong value) { }
}
public sealed partial class ConsoleCancelEventArgs : System.EventArgs
{
internal ConsoleCancelEventArgs() { }
public bool Cancel { get { throw null; } set { } }
public System.ConsoleSpecialKey SpecialKey { get { throw null; } }
}
public delegate void ConsoleCancelEventHandler(object? sender, System.ConsoleCancelEventArgs e);
public enum ConsoleColor
{
Black = 0,
DarkBlue = 1,
DarkGreen = 2,
DarkCyan = 3,
DarkRed = 4,
DarkMagenta = 5,
DarkYellow = 6,
Gray = 7,
DarkGray = 8,
Blue = 9,
Green = 10,
Cyan = 11,
Red = 12,
Magenta = 13,
Yellow = 14,
White = 15,
}
public enum ConsoleKey
{
Backspace = 8,
Tab = 9,
Clear = 12,
Enter = 13,
Pause = 19,
Escape = 27,
Spacebar = 32,
PageUp = 33,
PageDown = 34,
End = 35,
Home = 36,
LeftArrow = 37,
UpArrow = 38,
RightArrow = 39,
DownArrow = 40,
Select = 41,
Print = 42,
Execute = 43,
PrintScreen = 44,
Insert = 45,
Delete = 46,
Help = 47,
D0 = 48,
D1 = 49,
D2 = 50,
D3 = 51,
D4 = 52,
D5 = 53,
D6 = 54,
D7 = 55,
D8 = 56,
D9 = 57,
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
LeftWindows = 91,
RightWindows = 92,
Applications = 93,
Sleep = 95,
NumPad0 = 96,
NumPad1 = 97,
NumPad2 = 98,
NumPad3 = 99,
NumPad4 = 100,
NumPad5 = 101,
NumPad6 = 102,
NumPad7 = 103,
NumPad8 = 104,
NumPad9 = 105,
Multiply = 106,
Add = 107,
Separator = 108,
Subtract = 109,
Decimal = 110,
Divide = 111,
F1 = 112,
F2 = 113,
F3 = 114,
F4 = 115,
F5 = 116,
F6 = 117,
F7 = 118,
F8 = 119,
F9 = 120,
F10 = 121,
F11 = 122,
F12 = 123,
F13 = 124,
F14 = 125,
F15 = 126,
F16 = 127,
F17 = 128,
F18 = 129,
F19 = 130,
F20 = 131,
F21 = 132,
F22 = 133,
F23 = 134,
F24 = 135,
BrowserBack = 166,
BrowserForward = 167,
BrowserRefresh = 168,
BrowserStop = 169,
BrowserSearch = 170,
BrowserFavorites = 171,
BrowserHome = 172,
VolumeMute = 173,
VolumeDown = 174,
VolumeUp = 175,
MediaNext = 176,
MediaPrevious = 177,
MediaStop = 178,
MediaPlay = 179,
LaunchMail = 180,
LaunchMediaSelect = 181,
LaunchApp1 = 182,
LaunchApp2 = 183,
Oem1 = 186,
OemPlus = 187,
OemComma = 188,
OemMinus = 189,
OemPeriod = 190,
Oem2 = 191,
Oem3 = 192,
Oem4 = 219,
Oem5 = 220,
Oem6 = 221,
Oem7 = 222,
Oem8 = 223,
Oem102 = 226,
Process = 229,
Packet = 231,
Attention = 246,
CrSel = 247,
ExSel = 248,
EraseEndOfFile = 249,
Play = 250,
Zoom = 251,
NoName = 252,
Pa1 = 253,
OemClear = 254,
}
public readonly partial struct ConsoleKeyInfo : System.IEquatable<System.ConsoleKeyInfo>
{
private readonly int _dummyPrimitive;
public ConsoleKeyInfo(char keyChar, System.ConsoleKey key, bool shift, bool alt, bool control) { throw null; }
public System.ConsoleKey Key { get { throw null; } }
public char KeyChar { get { throw null; } }
public System.ConsoleModifiers Modifiers { get { throw null; } }
public bool Equals(System.ConsoleKeyInfo obj) { throw null; }
public override bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] object? value) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.ConsoleKeyInfo a, System.ConsoleKeyInfo b) { throw null; }
public static bool operator !=(System.ConsoleKeyInfo a, System.ConsoleKeyInfo b) { throw null; }
}
[System.FlagsAttribute]
public enum ConsoleModifiers
{
Alt = 1,
Shift = 2,
Control = 4,
}
public enum ConsoleSpecialKey
{
ControlC = 0,
ControlBreak = 1,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ------------------------------------------------------------------------------
// Changes to this file must follow the https://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System
{
public static partial class Console
{
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static System.ConsoleColor BackgroundColor { get { throw null; } set { } }
public static int BufferHeight { [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")] get { throw null; } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] set { } }
public static int BufferWidth { [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")] get { throw null; } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] set { } }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public static bool CapsLock { get { throw null; } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static int CursorLeft { get { throw null; } set { } }
public static int CursorSize { [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")] get { throw null; } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] set { } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static int CursorTop { get { throw null; } set { } }
public static bool CursorVisible { [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] get { throw null; } [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")] set { } }
public static System.IO.TextWriter Error { get { throw null; } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static System.ConsoleColor ForegroundColor { get { throw null; } set { } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static System.IO.TextReader In { get { throw null; } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static System.Text.Encoding InputEncoding { get { throw null; } set { } }
public static bool IsErrorRedirected { get { throw null; } }
public static bool IsInputRedirected { get { throw null; } }
public static bool IsOutputRedirected { get { throw null; } }
public static bool KeyAvailable { get { throw null; } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static int LargestWindowHeight { get { throw null; } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static int LargestWindowWidth { get { throw null; } }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public static bool NumberLock { get { throw null; } }
public static System.IO.TextWriter Out { get { throw null; } }
public static System.Text.Encoding OutputEncoding { get { throw null; } [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")] set { } }
public static string Title { [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] get { throw null; } [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")] set { } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static bool TreatControlCAsInput { get { throw null; } set { } }
public static int WindowHeight { [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")] get { throw null; } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] set { } }
public static int WindowLeft { get { throw null; } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] set { } }
public static int WindowTop { get { throw null; } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] set { } }
public static int WindowWidth { [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios"), System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")] get { throw null; } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] set { } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static event System.ConsoleCancelEventHandler? CancelKeyPress { add { } remove { } }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static void Beep() { }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public static void Beep(int frequency, int duration) { }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static void Clear() { }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static (int Left, int Top) GetCursorPosition() { throw null; }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop) { }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, System.ConsoleColor sourceForeColor, System.ConsoleColor sourceBackColor) { }
public static System.IO.Stream OpenStandardError() { throw null; }
public static System.IO.Stream OpenStandardError(int bufferSize) { throw null; }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static System.IO.Stream OpenStandardInput() { throw null; }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
public static System.IO.Stream OpenStandardInput(int bufferSize) { throw null; }
public static System.IO.Stream OpenStandardOutput() { throw null; }
public static System.IO.Stream OpenStandardOutput(int bufferSize) { throw null; }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
public static int Read() { throw null; }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static System.ConsoleKeyInfo ReadKey() { throw null; }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static System.ConsoleKeyInfo ReadKey(bool intercept) { throw null; }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
public static string? ReadLine() { throw null; }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static void ResetColor() { }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public static void SetBufferSize(int width, int height) { }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static void SetCursorPosition(int left, int top) { }
public static void SetError(System.IO.TextWriter newError) { }
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("android")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatformAttribute("tvos")]
public static void SetIn(System.IO.TextReader newIn) { }
public static void SetOut(System.IO.TextWriter newOut) { }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public static void SetWindowPosition(int left, int top) { }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public static void SetWindowSize(int width, int height) { }
public static void Write(bool value) { }
public static void Write(char value) { }
public static void Write(char[]? buffer) { }
public static void Write(char[] buffer, int index, int count) { }
public static void Write(decimal value) { }
public static void Write(double value) { }
public static void Write(int value) { }
public static void Write(long value) { }
public static void Write(object? value) { }
public static void Write(float value) { }
public static void Write(string? value) { }
public static void Write(string format, object? arg0) { }
public static void Write(string format, object? arg0, object? arg1) { }
public static void Write(string format, object? arg0, object? arg1, object? arg2) { }
public static void Write(string format, params object?[]? arg) { }
[System.CLSCompliantAttribute(false)]
public static void Write(uint value) { }
[System.CLSCompliantAttribute(false)]
public static void Write(ulong value) { }
public static void WriteLine() { }
public static void WriteLine(bool value) { }
public static void WriteLine(char value) { }
public static void WriteLine(char[]? buffer) { }
public static void WriteLine(char[] buffer, int index, int count) { }
public static void WriteLine(decimal value) { }
public static void WriteLine(double value) { }
public static void WriteLine(int value) { }
public static void WriteLine(long value) { }
public static void WriteLine(object? value) { }
public static void WriteLine(float value) { }
public static void WriteLine(string? value) { }
public static void WriteLine(string format, object? arg0) { }
public static void WriteLine(string format, object? arg0, object? arg1) { }
public static void WriteLine(string format, object? arg0, object? arg1, object? arg2) { }
public static void WriteLine(string format, params object?[]? arg) { }
[System.CLSCompliantAttribute(false)]
public static void WriteLine(uint value) { }
[System.CLSCompliantAttribute(false)]
public static void WriteLine(ulong value) { }
}
public sealed partial class ConsoleCancelEventArgs : System.EventArgs
{
internal ConsoleCancelEventArgs() { }
public bool Cancel { get { throw null; } set { } }
public System.ConsoleSpecialKey SpecialKey { get { throw null; } }
}
public delegate void ConsoleCancelEventHandler(object? sender, System.ConsoleCancelEventArgs e);
public enum ConsoleColor
{
Black = 0,
DarkBlue = 1,
DarkGreen = 2,
DarkCyan = 3,
DarkRed = 4,
DarkMagenta = 5,
DarkYellow = 6,
Gray = 7,
DarkGray = 8,
Blue = 9,
Green = 10,
Cyan = 11,
Red = 12,
Magenta = 13,
Yellow = 14,
White = 15,
}
public enum ConsoleKey
{
Backspace = 8,
Tab = 9,
Clear = 12,
Enter = 13,
Pause = 19,
Escape = 27,
Spacebar = 32,
PageUp = 33,
PageDown = 34,
End = 35,
Home = 36,
LeftArrow = 37,
UpArrow = 38,
RightArrow = 39,
DownArrow = 40,
Select = 41,
Print = 42,
Execute = 43,
PrintScreen = 44,
Insert = 45,
Delete = 46,
Help = 47,
D0 = 48,
D1 = 49,
D2 = 50,
D3 = 51,
D4 = 52,
D5 = 53,
D6 = 54,
D7 = 55,
D8 = 56,
D9 = 57,
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
LeftWindows = 91,
RightWindows = 92,
Applications = 93,
Sleep = 95,
NumPad0 = 96,
NumPad1 = 97,
NumPad2 = 98,
NumPad3 = 99,
NumPad4 = 100,
NumPad5 = 101,
NumPad6 = 102,
NumPad7 = 103,
NumPad8 = 104,
NumPad9 = 105,
Multiply = 106,
Add = 107,
Separator = 108,
Subtract = 109,
Decimal = 110,
Divide = 111,
F1 = 112,
F2 = 113,
F3 = 114,
F4 = 115,
F5 = 116,
F6 = 117,
F7 = 118,
F8 = 119,
F9 = 120,
F10 = 121,
F11 = 122,
F12 = 123,
F13 = 124,
F14 = 125,
F15 = 126,
F16 = 127,
F17 = 128,
F18 = 129,
F19 = 130,
F20 = 131,
F21 = 132,
F22 = 133,
F23 = 134,
F24 = 135,
BrowserBack = 166,
BrowserForward = 167,
BrowserRefresh = 168,
BrowserStop = 169,
BrowserSearch = 170,
BrowserFavorites = 171,
BrowserHome = 172,
VolumeMute = 173,
VolumeDown = 174,
VolumeUp = 175,
MediaNext = 176,
MediaPrevious = 177,
MediaStop = 178,
MediaPlay = 179,
LaunchMail = 180,
LaunchMediaSelect = 181,
LaunchApp1 = 182,
LaunchApp2 = 183,
Oem1 = 186,
OemPlus = 187,
OemComma = 188,
OemMinus = 189,
OemPeriod = 190,
Oem2 = 191,
Oem3 = 192,
Oem4 = 219,
Oem5 = 220,
Oem6 = 221,
Oem7 = 222,
Oem8 = 223,
Oem102 = 226,
Process = 229,
Packet = 231,
Attention = 246,
CrSel = 247,
ExSel = 248,
EraseEndOfFile = 249,
Play = 250,
Zoom = 251,
NoName = 252,
Pa1 = 253,
OemClear = 254,
}
public readonly partial struct ConsoleKeyInfo : System.IEquatable<System.ConsoleKeyInfo>
{
private readonly int _dummyPrimitive;
public ConsoleKeyInfo(char keyChar, System.ConsoleKey key, bool shift, bool alt, bool control) { throw null; }
public System.ConsoleKey Key { get { throw null; } }
public char KeyChar { get { throw null; } }
public System.ConsoleModifiers Modifiers { get { throw null; } }
public bool Equals(System.ConsoleKeyInfo obj) { throw null; }
public override bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] object? value) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.ConsoleKeyInfo a, System.ConsoleKeyInfo b) { throw null; }
public static bool operator !=(System.ConsoleKeyInfo a, System.ConsoleKeyInfo b) { throw null; }
}
[System.FlagsAttribute]
public enum ConsoleModifiers
{
Alt = 1,
Shift = 2,
Control = 4,
}
public enum ConsoleSpecialKey
{
ControlC = 0,
ControlBreak = 1,
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/X86/Sse2/Min.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\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 MinByte()
{
var test = new SimpleBinaryOpTest__MinByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MinByte
{
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(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, 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<Byte> _fld1;
public Vector128<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__MinByte testClass)
{
var result = Sse2.Min(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__MinByte testClass)
{
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = Sse2.Min(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(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<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__MinByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public SimpleBinaryOpTest__MinByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.Min(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.Min(
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.Min(
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.Min(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector128<Byte>* pClsVar2 = &_clsVar2)
{
var result = Sse2.Min(
Sse2.LoadVector128((Byte*)(pClsVar1)),
Sse2.LoadVector128((Byte*)(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<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Sse2.Min(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.Min(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.Min(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__MinByte();
var result = Sse2.Min(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__MinByte();
fixed (Vector128<Byte>* pFld1 = &test._fld1)
fixed (Vector128<Byte>* pFld2 = &test._fld2)
{
var result = Sse2.Min(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.Min(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = Sse2.Min(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.Min(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.Min(
Sse2.LoadVector128((Byte*)(&test._fld1)),
Sse2.LoadVector128((Byte*)(&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<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (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(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Math.Min(left[0], right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (Math.Min(left[i], right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Min)}<Byte>(Vector128<Byte>, Vector128<Byte>): {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 MinByte()
{
var test = new SimpleBinaryOpTest__MinByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MinByte
{
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(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, 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<Byte> _fld1;
public Vector128<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__MinByte testClass)
{
var result = Sse2.Min(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__MinByte testClass)
{
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = Sse2.Min(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(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<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__MinByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public SimpleBinaryOpTest__MinByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.Min(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.Min(
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.Min(
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.Min(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector128<Byte>* pClsVar2 = &_clsVar2)
{
var result = Sse2.Min(
Sse2.LoadVector128((Byte*)(pClsVar1)),
Sse2.LoadVector128((Byte*)(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<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Sse2.Min(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.Min(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.Min(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__MinByte();
var result = Sse2.Min(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__MinByte();
fixed (Vector128<Byte>* pFld1 = &test._fld1)
fixed (Vector128<Byte>* pFld2 = &test._fld2)
{
var result = Sse2.Min(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.Min(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = Sse2.Min(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.Min(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.Min(
Sse2.LoadVector128((Byte*)(&test._fld1)),
Sse2.LoadVector128((Byte*)(&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<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (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(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Math.Min(left[0], right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (Math.Min(left[i], right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Min)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Data.Common/src/System/Data/Common/SqlUDTStorage.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Data.SqlTypes;
using System.Xml;
using System.IO;
using System.Xml.Serialization;
using System.Collections;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Collections.Concurrent;
using System.Reflection;
using System.Diagnostics.CodeAnalysis;
namespace System.Data.Common
{
internal sealed class SqlUdtStorage : DataStorage
{
private object[] _values = default!; // Late-initialized
private readonly bool _implementsIXmlSerializable;
private readonly bool _implementsIComparable;
private static readonly ConcurrentDictionary<Type, object> s_typeToNull = new ConcurrentDictionary<Type, object>();
public SqlUdtStorage(DataColumn column, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicFields)] Type type)
: this(column, type, GetStaticNullForUdtType(type))
{
}
private SqlUdtStorage(DataColumn column, Type type, object nullValue)
: base(column, type, nullValue, nullValue, typeof(ICloneable).IsAssignableFrom(type), GetStorageType(type))
{
_implementsIXmlSerializable = typeof(IXmlSerializable).IsAssignableFrom(type);
_implementsIComparable = typeof(IComparable).IsAssignableFrom(type);
}
// to support oracle types and other INUllable types that have static Null as field
internal static object GetStaticNullForUdtType([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicFields)] Type type) => s_typeToNull.GetOrAdd(type, t => GetStaticNullForUdtTypeCore(t));
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern",
Justification = "The only callsite is marked with DynamicallyAccessedMembers. Workaround for https://github.com/mono/linker/issues/1981")]
private static object GetStaticNullForUdtTypeCore(Type type)
{
// TODO: Is it OK for the null value of a UDT to be null? For now annotating is non-nullable.
PropertyInfo? propInfo = type.GetProperty("Null", BindingFlags.Public | BindingFlags.Static);
if (propInfo != null)
{
return propInfo.GetValue(null, null)!;
}
FieldInfo fieldInfo = type.GetField("Null", BindingFlags.Public | BindingFlags.Static)!;
if (fieldInfo != null)
{
return fieldInfo.GetValue(null)!;
}
throw ExceptionBuilder.INullableUDTwithoutStaticNull(type.AssemblyQualifiedName!);
}
public override bool IsNull(int record)
{
return (((INullable)_values[record]).IsNull);
}
public override object Aggregate(int[] records, AggregateType kind)
{
throw ExceptionBuilder.AggregateException(kind, _dataType);
}
public override int Compare(int recordNo1, int recordNo2)
{
return (CompareValueTo(recordNo1, _values[recordNo2]));
}
public override int CompareValueTo(int recordNo1, object? value)
{
if (DBNull.Value == value)
{
// it is not meaningful compare UDT with DBNull.Value
value = _nullValue;
}
if (_implementsIComparable)
{
IComparable comparable = (IComparable)_values[recordNo1];
return comparable.CompareTo(value);
}
else if (_nullValue == value)
{
INullable nullableValue = (INullable)_values[recordNo1];
return nullableValue.IsNull ? 0 : 1; // left may be null, right is null
}
throw ExceptionBuilder.IComparableNotImplemented(_dataType.AssemblyQualifiedName!);
}
public override void Copy(int recordNo1, int recordNo2)
{
CopyBits(recordNo1, recordNo2);
_values[recordNo2] = _values[recordNo1];
}
public override object Get(int recordNo)
{
return (_values[recordNo]);
}
public override void Set(int recordNo, object value)
{
if (DBNull.Value == value)
{
_values[recordNo] = _nullValue;
SetNullBit(recordNo, true);
}
else if (null == value)
{
if (_isValueType)
{
throw ExceptionBuilder.StorageSetFailed();
}
else
{
_values[recordNo] = _nullValue;
SetNullBit(recordNo, true);
}
}
else if (!_dataType.IsInstanceOfType(value))
{
throw ExceptionBuilder.StorageSetFailed();
}
else
{
// do not clone the value
_values[recordNo] = value;
SetNullBit(recordNo, false);
}
}
public override void SetCapacity(int capacity)
{
object[] newValues = new object[capacity];
if (_values != null)
{
Array.Copy(_values, newValues, Math.Min(capacity, _values.Length));
}
_values = newValues;
base.SetCapacity(capacity);
}
// Prevent inlining so that reflection calls are not moved to caller that may be in a different assembly that may have a different grant set.
[MethodImpl(MethodImplOptions.NoInlining)]
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
public override object ConvertXmlToObject(string s)
{
if (_implementsIXmlSerializable)
{
object Obj = System.Activator.CreateInstance(_dataType, true)!;
string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader
StringReader strReader = new StringReader(tempStr);
using (XmlTextReader xmlTextReader = new XmlTextReader(strReader))
{
((IXmlSerializable)Obj).ReadXml(xmlTextReader);
}
return Obj;
}
StringReader strreader = new StringReader(s);
XmlSerializer deserializerWithOutRootAttribute = ObjectStorage.GetXmlSerializer(_dataType);
return (deserializerWithOutRootAttribute.Deserialize(strreader))!;
}
// Prevent inlining so that reflection calls are not moved to caller that may be in a different assembly that may have a different grant set.
[MethodImpl(MethodImplOptions.NoInlining)]
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
public override object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute? xmlAttrib)
{
if (null == xmlAttrib)
{
string? typeName = xmlReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.MSDNS);
if (typeName == null)
{
string? xsdTypeName = xmlReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.XSINS); // this xsd type
if (null != xsdTypeName)
{
typeName = XSDSchema.XsdtoClr(xsdTypeName).FullName!;
}
}
Type type = (typeName == null) ? _dataType : Type.GetType(typeName)!;
object Obj = System.Activator.CreateInstance(type, true)!;
Debug.Assert(xmlReader is DataTextReader, "Invalid DataTextReader is being passed to customer");
((IXmlSerializable)Obj).ReadXml(xmlReader);
return Obj;
}
else
{
XmlSerializer deserializerWithRootAttribute = ObjectStorage.GetXmlSerializer(_dataType, xmlAttrib);
return (deserializerWithRootAttribute.Deserialize(xmlReader))!;
}
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
public override string ConvertObjectToXml(object value)
{
StringWriter strwriter = new StringWriter(FormatProvider);
if (_implementsIXmlSerializable)
{
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(strwriter))
{
((IXmlSerializable)value).WriteXml(xmlTextWriter);
}
}
else
{
XmlSerializer serializerWithOutRootAttribute = ObjectStorage.GetXmlSerializer(value.GetType());
serializerWithOutRootAttribute.Serialize(strwriter, value);
}
return (strwriter.ToString());
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
public override void ConvertObjectToXml(object value, XmlWriter xmlWriter, XmlRootAttribute? xmlAttrib)
{
if (null == xmlAttrib)
{
Debug.Assert(xmlWriter is DataTextWriter, "Invalid DataTextWriter is being passed to customer");
((IXmlSerializable)value).WriteXml(xmlWriter);
}
else
{
// we support polymorphism only for types that implements IXmlSerializable.
// Assumption: value is the same type as DataType
XmlSerializer serializerWithRootAttribute = ObjectStorage.GetXmlSerializer(_dataType, xmlAttrib);
serializerWithRootAttribute.Serialize(xmlWriter, value);
}
}
protected override object GetEmptyStorage(int recordCount)
{
return new object[recordCount];
}
protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex)
{
object[] typedStore = (object[])store;
typedStore[storeIndex] = _values[record];
nullbits.Set(storeIndex, IsNull(record));
}
protected override void SetStorage(object store, BitArray nullbits)
{
_values = (object[])store;
//SetNullStorage(nullbits);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Data.SqlTypes;
using System.Xml;
using System.IO;
using System.Xml.Serialization;
using System.Collections;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Collections.Concurrent;
using System.Reflection;
using System.Diagnostics.CodeAnalysis;
namespace System.Data.Common
{
internal sealed class SqlUdtStorage : DataStorage
{
private object[] _values = default!; // Late-initialized
private readonly bool _implementsIXmlSerializable;
private readonly bool _implementsIComparable;
private static readonly ConcurrentDictionary<Type, object> s_typeToNull = new ConcurrentDictionary<Type, object>();
public SqlUdtStorage(DataColumn column, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicFields)] Type type)
: this(column, type, GetStaticNullForUdtType(type))
{
}
private SqlUdtStorage(DataColumn column, Type type, object nullValue)
: base(column, type, nullValue, nullValue, typeof(ICloneable).IsAssignableFrom(type), GetStorageType(type))
{
_implementsIXmlSerializable = typeof(IXmlSerializable).IsAssignableFrom(type);
_implementsIComparable = typeof(IComparable).IsAssignableFrom(type);
}
// to support oracle types and other INUllable types that have static Null as field
internal static object GetStaticNullForUdtType([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicFields)] Type type) => s_typeToNull.GetOrAdd(type, t => GetStaticNullForUdtTypeCore(t));
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern",
Justification = "The only callsite is marked with DynamicallyAccessedMembers. Workaround for https://github.com/mono/linker/issues/1981")]
private static object GetStaticNullForUdtTypeCore(Type type)
{
// TODO: Is it OK for the null value of a UDT to be null? For now annotating is non-nullable.
PropertyInfo? propInfo = type.GetProperty("Null", BindingFlags.Public | BindingFlags.Static);
if (propInfo != null)
{
return propInfo.GetValue(null, null)!;
}
FieldInfo fieldInfo = type.GetField("Null", BindingFlags.Public | BindingFlags.Static)!;
if (fieldInfo != null)
{
return fieldInfo.GetValue(null)!;
}
throw ExceptionBuilder.INullableUDTwithoutStaticNull(type.AssemblyQualifiedName!);
}
public override bool IsNull(int record)
{
return (((INullable)_values[record]).IsNull);
}
public override object Aggregate(int[] records, AggregateType kind)
{
throw ExceptionBuilder.AggregateException(kind, _dataType);
}
public override int Compare(int recordNo1, int recordNo2)
{
return (CompareValueTo(recordNo1, _values[recordNo2]));
}
public override int CompareValueTo(int recordNo1, object? value)
{
if (DBNull.Value == value)
{
// it is not meaningful compare UDT with DBNull.Value
value = _nullValue;
}
if (_implementsIComparable)
{
IComparable comparable = (IComparable)_values[recordNo1];
return comparable.CompareTo(value);
}
else if (_nullValue == value)
{
INullable nullableValue = (INullable)_values[recordNo1];
return nullableValue.IsNull ? 0 : 1; // left may be null, right is null
}
throw ExceptionBuilder.IComparableNotImplemented(_dataType.AssemblyQualifiedName!);
}
public override void Copy(int recordNo1, int recordNo2)
{
CopyBits(recordNo1, recordNo2);
_values[recordNo2] = _values[recordNo1];
}
public override object Get(int recordNo)
{
return (_values[recordNo]);
}
public override void Set(int recordNo, object value)
{
if (DBNull.Value == value)
{
_values[recordNo] = _nullValue;
SetNullBit(recordNo, true);
}
else if (null == value)
{
if (_isValueType)
{
throw ExceptionBuilder.StorageSetFailed();
}
else
{
_values[recordNo] = _nullValue;
SetNullBit(recordNo, true);
}
}
else if (!_dataType.IsInstanceOfType(value))
{
throw ExceptionBuilder.StorageSetFailed();
}
else
{
// do not clone the value
_values[recordNo] = value;
SetNullBit(recordNo, false);
}
}
public override void SetCapacity(int capacity)
{
object[] newValues = new object[capacity];
if (_values != null)
{
Array.Copy(_values, newValues, Math.Min(capacity, _values.Length));
}
_values = newValues;
base.SetCapacity(capacity);
}
// Prevent inlining so that reflection calls are not moved to caller that may be in a different assembly that may have a different grant set.
[MethodImpl(MethodImplOptions.NoInlining)]
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
public override object ConvertXmlToObject(string s)
{
if (_implementsIXmlSerializable)
{
object Obj = System.Activator.CreateInstance(_dataType, true)!;
string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader
StringReader strReader = new StringReader(tempStr);
using (XmlTextReader xmlTextReader = new XmlTextReader(strReader))
{
((IXmlSerializable)Obj).ReadXml(xmlTextReader);
}
return Obj;
}
StringReader strreader = new StringReader(s);
XmlSerializer deserializerWithOutRootAttribute = ObjectStorage.GetXmlSerializer(_dataType);
return (deserializerWithOutRootAttribute.Deserialize(strreader))!;
}
// Prevent inlining so that reflection calls are not moved to caller that may be in a different assembly that may have a different grant set.
[MethodImpl(MethodImplOptions.NoInlining)]
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
public override object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute? xmlAttrib)
{
if (null == xmlAttrib)
{
string? typeName = xmlReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.MSDNS);
if (typeName == null)
{
string? xsdTypeName = xmlReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.XSINS); // this xsd type
if (null != xsdTypeName)
{
typeName = XSDSchema.XsdtoClr(xsdTypeName).FullName!;
}
}
Type type = (typeName == null) ? _dataType : Type.GetType(typeName)!;
object Obj = System.Activator.CreateInstance(type, true)!;
Debug.Assert(xmlReader is DataTextReader, "Invalid DataTextReader is being passed to customer");
((IXmlSerializable)Obj).ReadXml(xmlReader);
return Obj;
}
else
{
XmlSerializer deserializerWithRootAttribute = ObjectStorage.GetXmlSerializer(_dataType, xmlAttrib);
return (deserializerWithRootAttribute.Deserialize(xmlReader))!;
}
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
public override string ConvertObjectToXml(object value)
{
StringWriter strwriter = new StringWriter(FormatProvider);
if (_implementsIXmlSerializable)
{
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(strwriter))
{
((IXmlSerializable)value).WriteXml(xmlTextWriter);
}
}
else
{
XmlSerializer serializerWithOutRootAttribute = ObjectStorage.GetXmlSerializer(value.GetType());
serializerWithOutRootAttribute.Serialize(strwriter, value);
}
return (strwriter.ToString());
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
public override void ConvertObjectToXml(object value, XmlWriter xmlWriter, XmlRootAttribute? xmlAttrib)
{
if (null == xmlAttrib)
{
Debug.Assert(xmlWriter is DataTextWriter, "Invalid DataTextWriter is being passed to customer");
((IXmlSerializable)value).WriteXml(xmlWriter);
}
else
{
// we support polymorphism only for types that implements IXmlSerializable.
// Assumption: value is the same type as DataType
XmlSerializer serializerWithRootAttribute = ObjectStorage.GetXmlSerializer(_dataType, xmlAttrib);
serializerWithRootAttribute.Serialize(xmlWriter, value);
}
}
protected override object GetEmptyStorage(int recordCount)
{
return new object[recordCount];
}
protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex)
{
object[] typedStore = (object[])store;
typedStore[storeIndex] = _values[record];
nullbits.Set(storeIndex, IsNull(record));
}
protected override void SetStorage(object store, BitArray nullbits)
{
_values = (object[])store;
//SetNullStorage(nullbits);
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Providers/Constants.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.Composition.Hosting.Providers
{
/// <summary>
/// Metadata keys used to tie programming model entities into their back-end hosting implementations.
/// </summary>
internal static class Constants
{
/// <summary>
/// The sharing boundary implemented by an import.
/// </summary>
public const string SharingBoundaryImportMetadataConstraintName = "SharingBoundaryNames";
/// <summary>
/// Marks an import as "many".
/// </summary>
public const string ImportManyImportMetadataConstraintName = "IsImportMany";
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Composition.Hosting.Providers
{
/// <summary>
/// Metadata keys used to tie programming model entities into their back-end hosting implementations.
/// </summary>
internal static class Constants
{
/// <summary>
/// The sharing boundary implemented by an import.
/// </summary>
public const string SharingBoundaryImportMetadataConstraintName = "SharingBoundaryNames";
/// <summary>
/// Marks an import as "many".
/// </summary>
public const string ImportManyImportMetadataConstraintName = "IsImportMany";
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/mono/mono/tests/xdomain-threads.cs | using System;
using System.Threading;
using System.Runtime.Remoting;
// Does a foreign domain's thread object persist (in .NET) even if it
// hasn't been started?
//
// Insubstantial, because it can't be "moved" to another domain.
// Can we start a foreign domain's thread (i.e. does the thread then
// switch to the foreign domain and execute the start method there)?
//
// No, we can't start it from another domain, because we can't bring
// to another domain.
// What if we start a foreign domain's thread if the domain is gone?
//
// See above.
public class Test : MarshalByRefObject {
public Thread thread;
public String str;
public void setThread () {
Console.WriteLine ("setting thread");
thread = Thread.CurrentThread;
thread.Name = "foo";
}
public void setStr (string s) {
Console.WriteLine ("setting str");
str = s;
}
public void callSetThread (Test t) {
Thread thread = new Thread (new ThreadStart (t.setThread));
thread.Start ();
thread.Join ();
t.setStr ("a" + "b");
}
}
public class main {
public static int Main (string [] args) {
AppDomain domain = AppDomain.CreateDomain ("newdomain");
Test myTest = new Test ();
Test otherTest = (Test) domain.CreateInstanceAndUnwrap (typeof (Test).Assembly.FullName, typeof (Test).FullName);
otherTest.callSetThread (myTest);
if (myTest.thread.GetType () == Thread.CurrentThread.GetType ())
Console.WriteLine ("same type");
else {
Console.WriteLine ("different type");
return 1;
}
AppDomain.Unload (domain);
GC.Collect ();
GC.WaitForPendingFinalizers ();
Console.WriteLine ("thread " + myTest.thread);
Console.WriteLine ("str " + myTest.str);
if (!myTest.thread.Name.Equals("foo"))
return 1;
return 0;
}
}
| using System;
using System.Threading;
using System.Runtime.Remoting;
// Does a foreign domain's thread object persist (in .NET) even if it
// hasn't been started?
//
// Insubstantial, because it can't be "moved" to another domain.
// Can we start a foreign domain's thread (i.e. does the thread then
// switch to the foreign domain and execute the start method there)?
//
// No, we can't start it from another domain, because we can't bring
// to another domain.
// What if we start a foreign domain's thread if the domain is gone?
//
// See above.
public class Test : MarshalByRefObject {
public Thread thread;
public String str;
public void setThread () {
Console.WriteLine ("setting thread");
thread = Thread.CurrentThread;
thread.Name = "foo";
}
public void setStr (string s) {
Console.WriteLine ("setting str");
str = s;
}
public void callSetThread (Test t) {
Thread thread = new Thread (new ThreadStart (t.setThread));
thread.Start ();
thread.Join ();
t.setStr ("a" + "b");
}
}
public class main {
public static int Main (string [] args) {
AppDomain domain = AppDomain.CreateDomain ("newdomain");
Test myTest = new Test ();
Test otherTest = (Test) domain.CreateInstanceAndUnwrap (typeof (Test).Assembly.FullName, typeof (Test).FullName);
otherTest.callSetThread (myTest);
if (myTest.thread.GetType () == Thread.CurrentThread.GetType ())
Console.WriteLine ("same type");
else {
Console.WriteLine ("different type");
return 1;
}
AppDomain.Unload (domain);
GC.Collect ();
GC.WaitForPendingFinalizers ();
Console.WriteLine ("thread " + myTest.thread);
Console.WriteLine ("str " + myTest.str);
if (!myTest.thread.Name.Equals("foo"))
return 1;
return 0;
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Drawing.Common/src/System/Drawing/Internal/GPStream.NoCOMWrappers.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;
namespace System.Drawing.Internal
{
internal sealed partial class GPStream : Interop.Ole32.IStream
{
public Interop.Ole32.IStream Clone()
{
// The cloned object should have the same current "position"
return new GPStream(_dataStream)
{
_virtualPosition = _virtualPosition
};
}
public unsafe void CopyTo(Interop.Ole32.IStream pstm, ulong cb, ulong* pcbRead, ulong* pcbWritten)
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(4096);
ulong remaining = cb;
ulong totalWritten = 0;
ulong totalRead = 0;
fixed (byte* b = buffer)
{
while (remaining > 0)
{
uint read = remaining < (ulong)buffer.Length ? (uint)remaining : (uint)buffer.Length;
Read(b, read, &read);
remaining -= read;
totalRead += read;
if (read == 0)
{
break;
}
uint written;
pstm.Write(b, read, &written);
totalWritten += written;
}
}
ArrayPool<byte>.Shared.Return(buffer);
if (pcbRead != null)
*pcbRead = totalRead;
if (pcbWritten != null)
*pcbWritten = totalWritten;
}
}
}
| // 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;
namespace System.Drawing.Internal
{
internal sealed partial class GPStream : Interop.Ole32.IStream
{
public Interop.Ole32.IStream Clone()
{
// The cloned object should have the same current "position"
return new GPStream(_dataStream)
{
_virtualPosition = _virtualPosition
};
}
public unsafe void CopyTo(Interop.Ole32.IStream pstm, ulong cb, ulong* pcbRead, ulong* pcbWritten)
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(4096);
ulong remaining = cb;
ulong totalWritten = 0;
ulong totalRead = 0;
fixed (byte* b = buffer)
{
while (remaining > 0)
{
uint read = remaining < (ulong)buffer.Length ? (uint)remaining : (uint)buffer.Length;
Read(b, read, &read);
remaining -= read;
totalRead += read;
if (read == 0)
{
break;
}
uint written;
pstm.Write(b, read, &written);
totalWritten += written;
}
}
ArrayPool<byte>.Shared.Return(buffer);
if (pcbRead != null)
*pcbRead = totalRead;
if (pcbWritten != null)
*pcbWritten = totalWritten;
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Net.Requests/src/System/Net/ExceptionHelper.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.Net
{
internal static class ExceptionHelper
{
internal static NotSupportedException PropertyNotSupportedException => new NotSupportedException(SR.net_PropertyNotSupportedException);
internal static WebException RequestAbortedException => new WebException(SR.net_reqaborted);
internal static WebException TimeoutException => new WebException(SR.net_timeout);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Net
{
internal static class ExceptionHelper
{
internal static NotSupportedException PropertyNotSupportedException => new NotSupportedException(SR.net_PropertyNotSupportedException);
internal static WebException RequestAbortedException => new WebException(SR.net_reqaborted);
internal static WebException TimeoutException => new WebException(SR.net_timeout);
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Security.Permissions/tests/MembershipConditionTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.Serialization;
using System.Security.Policy;
using Xunit;
namespace System.Security.Permissions.Tests
{
public class MembershipConditionTests
{
[Fact]
public static void AllMembershipConditionCallMethods()
{
AllMembershipCondition amc = new AllMembershipCondition();
bool check = amc.Check(new Evidence());
IMembershipCondition imc = amc.Copy();
check = amc.Equals(new object());
int hash = amc.GetHashCode();
string str = amc.ToString();
SecurityElement se = new SecurityElement("");
PolicyLevel pl = (PolicyLevel)FormatterServices.GetUninitializedObject(typeof(PolicyLevel));
amc.FromXml(se);
amc.FromXml(se, pl);
se = amc.ToXml();
se = amc.ToXml(pl);
}
[Fact]
public static void ApplicationDirectoryMembershipConditionCallMethods()
{
ApplicationDirectoryMembershipCondition admc = new ApplicationDirectoryMembershipCondition();
bool check = admc.Check(new Evidence());
IMembershipCondition obj = admc.Copy();
check = admc.Equals(new object());
int hash = admc.GetHashCode();
string str = admc.ToString();
SecurityElement se = new SecurityElement("");
PolicyLevel pl = (PolicyLevel)FormatterServices.GetUninitializedObject(typeof(PolicyLevel));
admc.FromXml(se);
admc.FromXml(se, pl);
se = admc.ToXml();
se = admc.ToXml(pl);
}
[Fact]
public static void GacMembershipConditionCallMethods()
{
GacMembershipCondition gmc = new GacMembershipCondition();
bool check = gmc.Check(new Evidence());
IMembershipCondition obj = gmc.Copy();
check = gmc.Equals(new object());
int hash = gmc.GetHashCode();
string str = gmc.ToString();
SecurityElement se = new SecurityElement("");
PolicyLevel pl = (PolicyLevel)FormatterServices.GetUninitializedObject(typeof(PolicyLevel));
gmc.FromXml(se);
gmc.FromXml(se, pl);
se = gmc.ToXml();
se = gmc.ToXml(pl);
}
[Fact]
[SkipOnPlatform(TestPlatforms.Browser, "System.Security.Cryptography.Algorithms is not supported on this platform.")]
public static void HashMembershipConditionCallMethods()
{
HashMembershipCondition hmc = new HashMembershipCondition(Cryptography.SHA1.Create(), new byte[1]);
bool check = hmc.Check(new Evidence());
IMembershipCondition obj = hmc.Copy();
check = hmc.Equals(new object());
int hash = hmc.GetHashCode();
string str = hmc.ToString();
SecurityElement se = new SecurityElement("");
PolicyLevel pl = (PolicyLevel)FormatterServices.GetUninitializedObject(typeof(PolicyLevel));
hmc.FromXml(se);
hmc.FromXml(se, pl);
se = hmc.ToXml();
se = hmc.ToXml(pl);
}
[Fact]
[SkipOnPlatform(TestPlatforms.Browser, "System.Security.Cryptography.X509Certificates is not supported on this platform.")]
public static void PublisherMembershipConditionCallMethods()
{
PublisherMembershipCondition pmc = new PublisherMembershipCondition(new System.Security.Cryptography.X509Certificates.X509Certificate2(stackalloc byte[0]));
bool check = pmc.Check(new Evidence());
IMembershipCondition obj = pmc.Copy();
check = pmc.Equals(new object());
int hash = pmc.GetHashCode();
string str = pmc.ToString();
SecurityElement se = new SecurityElement("");
PolicyLevel pl = (PolicyLevel)FormatterServices.GetUninitializedObject(typeof(PolicyLevel));
pmc.FromXml(se);
pmc.FromXml(se, pl);
se = pmc.ToXml();
se = pmc.ToXml(pl);
}
[Fact]
public static void SiteMembershipConditionCallMethods()
{
SiteMembershipCondition smc = new SiteMembershipCondition("test");
bool check = smc.Check(new Evidence());
IMembershipCondition obj = smc.Copy();
check = smc.Equals(new object());
int hash = smc.GetHashCode();
string str = smc.ToString();
SecurityElement se = new SecurityElement("");
PolicyLevel pl = (PolicyLevel)FormatterServices.GetUninitializedObject(typeof(PolicyLevel));
smc.FromXml(se);
smc.FromXml(se, pl);
se = smc.ToXml();
se = smc.ToXml(pl);
}
[Fact]
public static void StrongNameMembershipConditionCallMethods()
{
StrongNameMembershipCondition snmc = new StrongNameMembershipCondition(new StrongNamePublicKeyBlob(new byte[1]), "test", new Version(0, 1));
bool check = snmc.Check(new Evidence());
IMembershipCondition obj = snmc.Copy();
check = snmc.Equals(new object());
int hash = snmc.GetHashCode();
string str = snmc.ToString();
SecurityElement se = new SecurityElement("");
PolicyLevel pl = (PolicyLevel)FormatterServices.GetUninitializedObject(typeof(PolicyLevel));
snmc.FromXml(se);
snmc.FromXml(se, pl);
se = snmc.ToXml();
se = snmc.ToXml(pl);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.Serialization;
using System.Security.Policy;
using Xunit;
namespace System.Security.Permissions.Tests
{
public class MembershipConditionTests
{
[Fact]
public static void AllMembershipConditionCallMethods()
{
AllMembershipCondition amc = new AllMembershipCondition();
bool check = amc.Check(new Evidence());
IMembershipCondition imc = amc.Copy();
check = amc.Equals(new object());
int hash = amc.GetHashCode();
string str = amc.ToString();
SecurityElement se = new SecurityElement("");
PolicyLevel pl = (PolicyLevel)FormatterServices.GetUninitializedObject(typeof(PolicyLevel));
amc.FromXml(se);
amc.FromXml(se, pl);
se = amc.ToXml();
se = amc.ToXml(pl);
}
[Fact]
public static void ApplicationDirectoryMembershipConditionCallMethods()
{
ApplicationDirectoryMembershipCondition admc = new ApplicationDirectoryMembershipCondition();
bool check = admc.Check(new Evidence());
IMembershipCondition obj = admc.Copy();
check = admc.Equals(new object());
int hash = admc.GetHashCode();
string str = admc.ToString();
SecurityElement se = new SecurityElement("");
PolicyLevel pl = (PolicyLevel)FormatterServices.GetUninitializedObject(typeof(PolicyLevel));
admc.FromXml(se);
admc.FromXml(se, pl);
se = admc.ToXml();
se = admc.ToXml(pl);
}
[Fact]
public static void GacMembershipConditionCallMethods()
{
GacMembershipCondition gmc = new GacMembershipCondition();
bool check = gmc.Check(new Evidence());
IMembershipCondition obj = gmc.Copy();
check = gmc.Equals(new object());
int hash = gmc.GetHashCode();
string str = gmc.ToString();
SecurityElement se = new SecurityElement("");
PolicyLevel pl = (PolicyLevel)FormatterServices.GetUninitializedObject(typeof(PolicyLevel));
gmc.FromXml(se);
gmc.FromXml(se, pl);
se = gmc.ToXml();
se = gmc.ToXml(pl);
}
[Fact]
[SkipOnPlatform(TestPlatforms.Browser, "System.Security.Cryptography.Algorithms is not supported on this platform.")]
public static void HashMembershipConditionCallMethods()
{
HashMembershipCondition hmc = new HashMembershipCondition(Cryptography.SHA1.Create(), new byte[1]);
bool check = hmc.Check(new Evidence());
IMembershipCondition obj = hmc.Copy();
check = hmc.Equals(new object());
int hash = hmc.GetHashCode();
string str = hmc.ToString();
SecurityElement se = new SecurityElement("");
PolicyLevel pl = (PolicyLevel)FormatterServices.GetUninitializedObject(typeof(PolicyLevel));
hmc.FromXml(se);
hmc.FromXml(se, pl);
se = hmc.ToXml();
se = hmc.ToXml(pl);
}
[Fact]
[SkipOnPlatform(TestPlatforms.Browser, "System.Security.Cryptography.X509Certificates is not supported on this platform.")]
public static void PublisherMembershipConditionCallMethods()
{
PublisherMembershipCondition pmc = new PublisherMembershipCondition(new System.Security.Cryptography.X509Certificates.X509Certificate2(stackalloc byte[0]));
bool check = pmc.Check(new Evidence());
IMembershipCondition obj = pmc.Copy();
check = pmc.Equals(new object());
int hash = pmc.GetHashCode();
string str = pmc.ToString();
SecurityElement se = new SecurityElement("");
PolicyLevel pl = (PolicyLevel)FormatterServices.GetUninitializedObject(typeof(PolicyLevel));
pmc.FromXml(se);
pmc.FromXml(se, pl);
se = pmc.ToXml();
se = pmc.ToXml(pl);
}
[Fact]
public static void SiteMembershipConditionCallMethods()
{
SiteMembershipCondition smc = new SiteMembershipCondition("test");
bool check = smc.Check(new Evidence());
IMembershipCondition obj = smc.Copy();
check = smc.Equals(new object());
int hash = smc.GetHashCode();
string str = smc.ToString();
SecurityElement se = new SecurityElement("");
PolicyLevel pl = (PolicyLevel)FormatterServices.GetUninitializedObject(typeof(PolicyLevel));
smc.FromXml(se);
smc.FromXml(se, pl);
se = smc.ToXml();
se = smc.ToXml(pl);
}
[Fact]
public static void StrongNameMembershipConditionCallMethods()
{
StrongNameMembershipCondition snmc = new StrongNameMembershipCondition(new StrongNamePublicKeyBlob(new byte[1]), "test", new Version(0, 1));
bool check = snmc.Check(new Evidence());
IMembershipCondition obj = snmc.Copy();
check = snmc.Equals(new object());
int hash = snmc.GetHashCode();
string str = snmc.ToString();
SecurityElement se = new SecurityElement("");
PolicyLevel pl = (PolicyLevel)FormatterServices.GetUninitializedObject(typeof(PolicyLevel));
snmc.FromXml(se);
snmc.FromXml(se, pl);
se = snmc.ToXml();
se = snmc.ToXml(pl);
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/ICollectData.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.Diagnostics
{
/// <internalonly/>
[ComImport, Guid("73386977-D6FD-11D2-BED5-00C04F79E3AE"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
public interface ICollectData
{
[return: MarshalAs(UnmanagedType.I4)]
void CollectData(
[In, MarshalAs(UnmanagedType.I4 )]
int id,
[In, MarshalAs(UnmanagedType.SysInt )]
IntPtr valueName,
[In, MarshalAs(UnmanagedType.SysInt )]
IntPtr data,
[In, MarshalAs(UnmanagedType.I4 )]
int totalBytes,
[Out, MarshalAs(UnmanagedType.SysInt)]
out IntPtr res);
void CloseData();
}
}
| // 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.Diagnostics
{
/// <internalonly/>
[ComImport, Guid("73386977-D6FD-11D2-BED5-00C04F79E3AE"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
public interface ICollectData
{
[return: MarshalAs(UnmanagedType.I4)]
void CollectData(
[In, MarshalAs(UnmanagedType.I4 )]
int id,
[In, MarshalAs(UnmanagedType.SysInt )]
IntPtr valueName,
[In, MarshalAs(UnmanagedType.SysInt )]
IntPtr data,
[In, MarshalAs(UnmanagedType.I4 )]
int totalBytes,
[Out, MarshalAs(UnmanagedType.SysInt)]
out IntPtr res);
void CloseData();
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/General/Vector256_1/op_Inequality.Int64.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void op_InequalityInt64()
{
var test = new VectorBooleanBinaryOpTest__op_InequalityInt64();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBooleanBinaryOpTest__op_InequalityInt64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Int64[] inArray1, Int64[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>();
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<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Int64> _fld1;
public Vector256<Int64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
return testStruct;
}
public void RunStructFldScenario(VectorBooleanBinaryOpTest__op_InequalityInt64 testClass)
{
var result = _fld1 != _fld2;
testClass.ValidateResult(_fld1, _fld2, result);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static Int64[] _data1 = new Int64[Op1ElementCount];
private static Int64[] _data2 = new Int64[Op2ElementCount];
private static Vector256<Int64> _clsVar1;
private static Vector256<Int64> _clsVar2;
private Vector256<Int64> _fld1;
private Vector256<Int64> _fld2;
private DataTable _dataTable;
static VectorBooleanBinaryOpTest__op_InequalityInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
}
public VectorBooleanBinaryOpTest__op_InequalityInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr) != Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Vector256<Int64>).GetMethod("op_Inequality", new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = _clsVar1 != _clsVar2;
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr);
var result = op1 != op2;
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBooleanBinaryOpTest__op_InequalityInt64();
var result = test._fld1 != test._fld2;
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = _fld1 != _fld2;
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = test._fld1 != test._fld2;
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector256<Int64> op1, Vector256<Int64> op2, bool result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int64>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int64[] left, Int64[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult |= (left[i] != right[i]);
}
succeeded = (expectedResult == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_Inequality<Int64>(Vector256<Int64>, Vector256<Int64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void op_InequalityInt64()
{
var test = new VectorBooleanBinaryOpTest__op_InequalityInt64();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBooleanBinaryOpTest__op_InequalityInt64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Int64[] inArray1, Int64[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>();
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<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Int64> _fld1;
public Vector256<Int64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
return testStruct;
}
public void RunStructFldScenario(VectorBooleanBinaryOpTest__op_InequalityInt64 testClass)
{
var result = _fld1 != _fld2;
testClass.ValidateResult(_fld1, _fld2, result);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static Int64[] _data1 = new Int64[Op1ElementCount];
private static Int64[] _data2 = new Int64[Op2ElementCount];
private static Vector256<Int64> _clsVar1;
private static Vector256<Int64> _clsVar2;
private Vector256<Int64> _fld1;
private Vector256<Int64> _fld2;
private DataTable _dataTable;
static VectorBooleanBinaryOpTest__op_InequalityInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
}
public VectorBooleanBinaryOpTest__op_InequalityInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr) != Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Vector256<Int64>).GetMethod("op_Inequality", new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = _clsVar1 != _clsVar2;
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr);
var result = op1 != op2;
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBooleanBinaryOpTest__op_InequalityInt64();
var result = test._fld1 != test._fld2;
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = _fld1 != _fld2;
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = test._fld1 != test._fld2;
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector256<Int64> op1, Vector256<Int64> op2, bool result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int64>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int64[] left, Int64[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult |= (left[i] != right[i]);
}
succeeded = (expectedResult == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_Inequality<Int64>(Vector256<Int64>, Vector256<Int64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/reflection/regression/manyStackArgs/manyStackArgs.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>None</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).cs" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>None</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Security.Permissions/src/System/Diagnostics/EventLogPermissionAttribute.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Security;
using System.Security.Permissions;
namespace System.Diagnostics
{
#if NETCOREAPP
[Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
#endif
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct
| AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Event, AllowMultiple = true, Inherited = false)]
public class EventLogPermissionAttribute : CodeAccessSecurityAttribute
{
public EventLogPermissionAttribute(SecurityAction action) : base(action) { }
public string MachineName { get { return null; } set { } }
public EventLogPermissionAccess PermissionAccess { get; set; }
public override IPermission CreatePermission() { return null; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Security;
using System.Security.Permissions;
namespace System.Diagnostics
{
#if NETCOREAPP
[Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
#endif
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct
| AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Event, AllowMultiple = true, Inherited = false)]
public class EventLogPermissionAttribute : CodeAccessSecurityAttribute
{
public EventLogPermissionAttribute(SecurityAction action) : base(action) { }
public string MachineName { get { return null; } set { } }
public EventLogPermissionAccess PermissionAccess { get; set; }
public override IPermission CreatePermission() { return null; }
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ShiftLogicalSaturate.Vector128.SByte.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void ShiftLogicalSaturate_Vector128_SByte()
{
var test = new SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_SByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_SByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(SByte[] inArray1, SByte[] inArray2, 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 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(SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_SByte testClass)
{
var result = AdvSimd.ShiftLogicalSaturate(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_SByte testClass)
{
fixed (Vector128<SByte>* pFld1 = &_fld1)
fixed (Vector128<SByte>* pFld2 = &_fld2)
{
var result = AdvSimd.ShiftLogicalSaturate(
AdvSimd.LoadVector128((SByte*)(pFld1)),
AdvSimd.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<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 SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_SByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
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 SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_SByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < 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 IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.ShiftLogicalSaturate(
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.ShiftLogicalSaturate(
AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLogicalSaturate), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.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 RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLogicalSaturate), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((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 = AdvSimd.ShiftLogicalSaturate(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<SByte>* pClsVar1 = &_clsVar1)
fixed (Vector128<SByte>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.ShiftLogicalSaturate(
AdvSimd.LoadVector128((SByte*)(pClsVar1)),
AdvSimd.LoadVector128((SByte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr);
var result = AdvSimd.ShiftLogicalSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr));
var result = AdvSimd.ShiftLogicalSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_SByte();
var result = AdvSimd.ShiftLogicalSaturate(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_SByte();
fixed (Vector128<SByte>* pFld1 = &test._fld1)
fixed (Vector128<SByte>* pFld2 = &test._fld2)
{
var result = AdvSimd.ShiftLogicalSaturate(
AdvSimd.LoadVector128((SByte*)(pFld1)),
AdvSimd.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.ShiftLogicalSaturate(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<SByte>* pFld1 = &_fld1)
fixed (Vector128<SByte>* pFld2 = &_fld2)
{
var result = AdvSimd.ShiftLogicalSaturate(
AdvSimd.LoadVector128((SByte*)(pFld1)),
AdvSimd.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.ShiftLogicalSaturate(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.ShiftLogicalSaturate(
AdvSimd.LoadVector128((SByte*)(&test._fld1)),
AdvSimd.LoadVector128((SByte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(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;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ShiftLogicalSaturate(left[i], right[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftLogicalSaturate)}<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.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void ShiftLogicalSaturate_Vector128_SByte()
{
var test = new SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_SByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_SByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(SByte[] inArray1, SByte[] inArray2, 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 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(SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_SByte testClass)
{
var result = AdvSimd.ShiftLogicalSaturate(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_SByte testClass)
{
fixed (Vector128<SByte>* pFld1 = &_fld1)
fixed (Vector128<SByte>* pFld2 = &_fld2)
{
var result = AdvSimd.ShiftLogicalSaturate(
AdvSimd.LoadVector128((SByte*)(pFld1)),
AdvSimd.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<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 SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_SByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
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 SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_SByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < 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 IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.ShiftLogicalSaturate(
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.ShiftLogicalSaturate(
AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLogicalSaturate), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.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 RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLogicalSaturate), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((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 = AdvSimd.ShiftLogicalSaturate(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<SByte>* pClsVar1 = &_clsVar1)
fixed (Vector128<SByte>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.ShiftLogicalSaturate(
AdvSimd.LoadVector128((SByte*)(pClsVar1)),
AdvSimd.LoadVector128((SByte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr);
var result = AdvSimd.ShiftLogicalSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr));
var result = AdvSimd.ShiftLogicalSaturate(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_SByte();
var result = AdvSimd.ShiftLogicalSaturate(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__ShiftLogicalSaturate_Vector128_SByte();
fixed (Vector128<SByte>* pFld1 = &test._fld1)
fixed (Vector128<SByte>* pFld2 = &test._fld2)
{
var result = AdvSimd.ShiftLogicalSaturate(
AdvSimd.LoadVector128((SByte*)(pFld1)),
AdvSimd.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.ShiftLogicalSaturate(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<SByte>* pFld1 = &_fld1)
fixed (Vector128<SByte>* pFld2 = &_fld2)
{
var result = AdvSimd.ShiftLogicalSaturate(
AdvSimd.LoadVector128((SByte*)(pFld1)),
AdvSimd.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.ShiftLogicalSaturate(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.ShiftLogicalSaturate(
AdvSimd.LoadVector128((SByte*)(&test._fld1)),
AdvSimd.LoadVector128((SByte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(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;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ShiftLogicalSaturate(left[i], right[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftLogicalSaturate)}<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 | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Private.CoreLib/src/System/Random.Xoshiro128StarStarImpl.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.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System
{
public partial class Random
{
/// <summary>
/// Provides an implementation of the xoshiro128** algorithm. This implementation is used
/// on 32-bit when no seed is specified and an instance of the base Random class is constructed.
/// As such, we are free to implement however we see fit, without back compat concerns around
/// the sequence of numbers generated or what methods call what other methods.
/// </summary>
internal sealed class XoshiroImpl : ImplBase
{
// NextUInt32 is based on the algorithm from http://prng.di.unimi.it/xoshiro128starstar.c:
//
// Written in 2018 by David Blackman and Sebastiano Vigna ([email protected])
//
// To the extent possible under law, the author has dedicated all copyright
// and related and neighboring rights to this software to the public domain
// worldwide. This software is distributed without any warranty.
//
// See <http://creativecommons.org/publicdomain/zero/1.0/>.
private uint _s0, _s1, _s2, _s3;
public unsafe XoshiroImpl()
{
uint* ptr = stackalloc uint[4];
do
{
Interop.GetRandomBytes((byte*)ptr, 4 * sizeof(uint));
_s0 = ptr[0];
_s1 = ptr[1];
_s2 = ptr[2];
_s3 = ptr[3];
}
while ((_s0 | _s1 | _s2 | _s3) == 0); // at least one value must be non-zero
}
/// <summary>Produces a value in the range [0, uint.MaxValue].</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] // small-ish hot path used by a handful of "next" methods
internal uint NextUInt32()
{
uint s0 = _s0, s1 = _s1, s2 = _s2, s3 = _s3;
uint result = BitOperations.RotateLeft(s1 * 5, 7) * 9;
uint t = s1 << 9;
s2 ^= s0;
s3 ^= s1;
s1 ^= s2;
s0 ^= s3;
s2 ^= t;
s3 = BitOperations.RotateLeft(s3, 11);
_s0 = s0;
_s1 = s1;
_s2 = s2;
_s3 = s3;
return result;
}
/// <summary>Produces a value in the range [0, ulong.MaxValue].</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] // small-ish hot path used by a handful of "next" methods
internal ulong NextUInt64() => (((ulong)NextUInt32()) << 32) | NextUInt32();
public override int Next()
{
while (true)
{
// Get top 31 bits to get a value in the range [0, int.MaxValue], but try again
// if the value is actually int.MaxValue, as the method is defined to return a value
// in the range [0, int.MaxValue).
uint result = NextUInt32() >> 1;
if (result != int.MaxValue)
{
return (int)result;
}
}
}
public override int Next(int maxValue)
{
if (maxValue > 1)
{
// Narrow down to the smallest range [0, 2^bits] that contains maxValue.
// Then repeatedly generate a value in that outer range until we get one within the inner range.
int bits = BitOperations.Log2Ceiling((uint)maxValue);
while (true)
{
uint result = NextUInt32() >> (sizeof(uint) * 8 - bits);
if (result < (uint)maxValue)
{
return (int)result;
}
}
}
Debug.Assert(maxValue == 0 || maxValue == 1);
return 0;
}
public override int Next(int minValue, int maxValue)
{
uint exclusiveRange = (uint)(maxValue - minValue);
if (exclusiveRange > 1)
{
// Narrow down to the smallest range [0, 2^bits] that contains maxValue.
// Then repeatedly generate a value in that outer range until we get one within the inner range.
int bits = BitOperations.Log2Ceiling(exclusiveRange);
while (true)
{
uint result = NextUInt32() >> (sizeof(uint) * 8 - bits);
if (result < exclusiveRange)
{
return (int)result + minValue;
}
}
}
Debug.Assert(minValue == maxValue || minValue + 1 == maxValue);
return minValue;
}
public override long NextInt64()
{
while (true)
{
// Get top 63 bits to get a value in the range [0, long.MaxValue], but try again
// if the value is actually long.MaxValue, as the method is defined to return a value
// in the range [0, long.MaxValue).
ulong result = NextUInt64() >> 1;
if (result != long.MaxValue)
{
return (long)result;
}
}
}
public override long NextInt64(long maxValue)
{
if (maxValue <= int.MaxValue)
{
return Next((int)maxValue);
}
if (maxValue > 1)
{
// Narrow down to the smallest range [0, 2^bits] that contains maxValue.
// Then repeatedly generate a value in that outer range until we get one within the inner range.
int bits = BitOperations.Log2Ceiling((ulong)maxValue);
while (true)
{
ulong result = NextUInt64() >> (sizeof(ulong) * 8 - bits);
if (result < (ulong)maxValue)
{
return (long)result;
}
}
}
Debug.Assert(maxValue == 0 || maxValue == 1);
return 0;
}
public override long NextInt64(long minValue, long maxValue)
{
ulong exclusiveRange = (ulong)(maxValue - minValue);
if (exclusiveRange <= int.MaxValue)
{
return Next((int)exclusiveRange) + minValue;
}
if (exclusiveRange > 1)
{
// Narrow down to the smallest range [0, 2^bits] that contains maxValue.
// Then repeatedly generate a value in that outer range until we get one within the inner range.
int bits = BitOperations.Log2Ceiling(exclusiveRange);
while (true)
{
ulong result = NextUInt64() >> (sizeof(ulong) * 8 - bits);
if (result < exclusiveRange)
{
return (long)result + minValue;
}
}
}
Debug.Assert(minValue == maxValue || minValue + 1 == maxValue);
return minValue;
}
public override void NextBytes(byte[] buffer) => NextBytes((Span<byte>)buffer);
public override unsafe void NextBytes(Span<byte> buffer)
{
uint s0 = _s0, s1 = _s1, s2 = _s2, s3 = _s3;
while (buffer.Length >= sizeof(uint))
{
Unsafe.WriteUnaligned(
ref MemoryMarshal.GetReference(buffer),
BitOperations.RotateLeft(s1 * 5, 7) * 9);
// Update PRNG state.
uint t = s1 << 9;
s2 ^= s0;
s3 ^= s1;
s1 ^= s2;
s0 ^= s3;
s2 ^= t;
s3 = BitOperations.RotateLeft(s3, 11);
buffer = buffer.Slice(sizeof(uint));
}
if (!buffer.IsEmpty)
{
uint next = BitOperations.RotateLeft(s1 * 5, 7) * 9;
byte* remainingBytes = (byte*)&next;
Debug.Assert(buffer.Length < sizeof(uint));
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = remainingBytes[i];
}
// Update PRNG state.
uint t = s1 << 9;
s2 ^= s0;
s3 ^= s1;
s1 ^= s2;
s0 ^= s3;
s2 ^= t;
s3 = BitOperations.RotateLeft(s3, 11);
}
_s0 = s0;
_s1 = s1;
_s2 = s2;
_s3 = s3;
}
public override double NextDouble() =>
// See comment in Xoshiro256StarStarImpl.
(NextUInt64() >> 11) * (1.0 / (1ul << 53));
public override float NextSingle() =>
// See comment in Xoshiro256StarStarImpl.
(NextUInt32() >> 8) * (1.0f / (1u << 24));
public override double Sample()
{
Debug.Fail("Not used or called for this implementation.");
throw new NotSupportedException();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System
{
public partial class Random
{
/// <summary>
/// Provides an implementation of the xoshiro128** algorithm. This implementation is used
/// on 32-bit when no seed is specified and an instance of the base Random class is constructed.
/// As such, we are free to implement however we see fit, without back compat concerns around
/// the sequence of numbers generated or what methods call what other methods.
/// </summary>
internal sealed class XoshiroImpl : ImplBase
{
// NextUInt32 is based on the algorithm from http://prng.di.unimi.it/xoshiro128starstar.c:
//
// Written in 2018 by David Blackman and Sebastiano Vigna ([email protected])
//
// To the extent possible under law, the author has dedicated all copyright
// and related and neighboring rights to this software to the public domain
// worldwide. This software is distributed without any warranty.
//
// See <http://creativecommons.org/publicdomain/zero/1.0/>.
private uint _s0, _s1, _s2, _s3;
public unsafe XoshiroImpl()
{
uint* ptr = stackalloc uint[4];
do
{
Interop.GetRandomBytes((byte*)ptr, 4 * sizeof(uint));
_s0 = ptr[0];
_s1 = ptr[1];
_s2 = ptr[2];
_s3 = ptr[3];
}
while ((_s0 | _s1 | _s2 | _s3) == 0); // at least one value must be non-zero
}
/// <summary>Produces a value in the range [0, uint.MaxValue].</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] // small-ish hot path used by a handful of "next" methods
internal uint NextUInt32()
{
uint s0 = _s0, s1 = _s1, s2 = _s2, s3 = _s3;
uint result = BitOperations.RotateLeft(s1 * 5, 7) * 9;
uint t = s1 << 9;
s2 ^= s0;
s3 ^= s1;
s1 ^= s2;
s0 ^= s3;
s2 ^= t;
s3 = BitOperations.RotateLeft(s3, 11);
_s0 = s0;
_s1 = s1;
_s2 = s2;
_s3 = s3;
return result;
}
/// <summary>Produces a value in the range [0, ulong.MaxValue].</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] // small-ish hot path used by a handful of "next" methods
internal ulong NextUInt64() => (((ulong)NextUInt32()) << 32) | NextUInt32();
public override int Next()
{
while (true)
{
// Get top 31 bits to get a value in the range [0, int.MaxValue], but try again
// if the value is actually int.MaxValue, as the method is defined to return a value
// in the range [0, int.MaxValue).
uint result = NextUInt32() >> 1;
if (result != int.MaxValue)
{
return (int)result;
}
}
}
public override int Next(int maxValue)
{
if (maxValue > 1)
{
// Narrow down to the smallest range [0, 2^bits] that contains maxValue.
// Then repeatedly generate a value in that outer range until we get one within the inner range.
int bits = BitOperations.Log2Ceiling((uint)maxValue);
while (true)
{
uint result = NextUInt32() >> (sizeof(uint) * 8 - bits);
if (result < (uint)maxValue)
{
return (int)result;
}
}
}
Debug.Assert(maxValue == 0 || maxValue == 1);
return 0;
}
public override int Next(int minValue, int maxValue)
{
uint exclusiveRange = (uint)(maxValue - minValue);
if (exclusiveRange > 1)
{
// Narrow down to the smallest range [0, 2^bits] that contains maxValue.
// Then repeatedly generate a value in that outer range until we get one within the inner range.
int bits = BitOperations.Log2Ceiling(exclusiveRange);
while (true)
{
uint result = NextUInt32() >> (sizeof(uint) * 8 - bits);
if (result < exclusiveRange)
{
return (int)result + minValue;
}
}
}
Debug.Assert(minValue == maxValue || minValue + 1 == maxValue);
return minValue;
}
public override long NextInt64()
{
while (true)
{
// Get top 63 bits to get a value in the range [0, long.MaxValue], but try again
// if the value is actually long.MaxValue, as the method is defined to return a value
// in the range [0, long.MaxValue).
ulong result = NextUInt64() >> 1;
if (result != long.MaxValue)
{
return (long)result;
}
}
}
public override long NextInt64(long maxValue)
{
if (maxValue <= int.MaxValue)
{
return Next((int)maxValue);
}
if (maxValue > 1)
{
// Narrow down to the smallest range [0, 2^bits] that contains maxValue.
// Then repeatedly generate a value in that outer range until we get one within the inner range.
int bits = BitOperations.Log2Ceiling((ulong)maxValue);
while (true)
{
ulong result = NextUInt64() >> (sizeof(ulong) * 8 - bits);
if (result < (ulong)maxValue)
{
return (long)result;
}
}
}
Debug.Assert(maxValue == 0 || maxValue == 1);
return 0;
}
public override long NextInt64(long minValue, long maxValue)
{
ulong exclusiveRange = (ulong)(maxValue - minValue);
if (exclusiveRange <= int.MaxValue)
{
return Next((int)exclusiveRange) + minValue;
}
if (exclusiveRange > 1)
{
// Narrow down to the smallest range [0, 2^bits] that contains maxValue.
// Then repeatedly generate a value in that outer range until we get one within the inner range.
int bits = BitOperations.Log2Ceiling(exclusiveRange);
while (true)
{
ulong result = NextUInt64() >> (sizeof(ulong) * 8 - bits);
if (result < exclusiveRange)
{
return (long)result + minValue;
}
}
}
Debug.Assert(minValue == maxValue || minValue + 1 == maxValue);
return minValue;
}
public override void NextBytes(byte[] buffer) => NextBytes((Span<byte>)buffer);
public override unsafe void NextBytes(Span<byte> buffer)
{
uint s0 = _s0, s1 = _s1, s2 = _s2, s3 = _s3;
while (buffer.Length >= sizeof(uint))
{
Unsafe.WriteUnaligned(
ref MemoryMarshal.GetReference(buffer),
BitOperations.RotateLeft(s1 * 5, 7) * 9);
// Update PRNG state.
uint t = s1 << 9;
s2 ^= s0;
s3 ^= s1;
s1 ^= s2;
s0 ^= s3;
s2 ^= t;
s3 = BitOperations.RotateLeft(s3, 11);
buffer = buffer.Slice(sizeof(uint));
}
if (!buffer.IsEmpty)
{
uint next = BitOperations.RotateLeft(s1 * 5, 7) * 9;
byte* remainingBytes = (byte*)&next;
Debug.Assert(buffer.Length < sizeof(uint));
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = remainingBytes[i];
}
// Update PRNG state.
uint t = s1 << 9;
s2 ^= s0;
s3 ^= s1;
s1 ^= s2;
s0 ^= s3;
s2 ^= t;
s3 = BitOperations.RotateLeft(s3, 11);
}
_s0 = s0;
_s1 = s1;
_s2 = s2;
_s3 = s3;
}
public override double NextDouble() =>
// See comment in Xoshiro256StarStarImpl.
(NextUInt64() >> 11) * (1.0 / (1ul << 53));
public override float NextSingle() =>
// See comment in Xoshiro256StarStarImpl.
(NextUInt32() >> 8) * (1.0f / (1u << 24));
public override double Sample()
{
Debug.Fail("Not used or called for this implementation.");
throw new NotSupportedException();
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Security.Cryptography.Pkcs/tests/EnvelopedCms/KeyTransRecipientInfoTests.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.Linq;
using System.Globalization;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
using Xunit;
using Test.Cryptography;
using System.Security.Cryptography.Pkcs.Tests;
namespace System.Security.Cryptography.Pkcs.EnvelopedCmsTests.Tests
{
public static partial class KeyTransRecipientInfoTests
{
[Fact]
public static void TestKeyTransVersion_RoundTrip()
{
KeyTransRecipientInfo recipient = EncodeKeyTransl();
Assert.Equal(0, recipient.Version);
}
[Fact]
public static void TestKeyTransVersion_FixedValue()
{
KeyTransRecipientInfo recipient = FixedValueKeyTrans1();
Assert.Equal(0, recipient.Version);
}
[Fact]
public static void TestKeyTransType_RoundTrip()
{
KeyTransRecipientInfo recipient = EncodeKeyTransl();
Assert.Equal(RecipientInfoType.KeyTransport, recipient.Type);
}
[Fact]
public static void TestKeyTransType_FixedValue()
{
KeyTransRecipientInfo recipient = FixedValueKeyTrans1();
Assert.Equal(RecipientInfoType.KeyTransport, recipient.Type);
}
[Fact]
public static void TestKeyTransRecipientIdType_RoundTrip()
{
KeyTransRecipientInfo recipient = EncodeKeyTransl();
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, subjectIdentifier.Type);
}
[Fact]
public static void TestKeyTransRecipientIdType_FixedValue()
{
KeyTransRecipientInfo recipient = FixedValueKeyTrans1();
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, subjectIdentifier.Type);
}
[Fact]
public static void TestKeyTransRecipientIdValue_RoundTrip()
{
KeyTransRecipientInfo recipient = EncodeKeyTransl();
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
object value = subjectIdentifier.Value;
Assert.True(value is X509IssuerSerial);
X509IssuerSerial xis = (X509IssuerSerial)value;
Assert.Equal("CN=RSAKeyTransfer1", xis.IssuerName);
Assert.Equal("31D935FB63E8CFAB48A0BF7B397B67C0", xis.SerialNumber);
}
[Fact]
public static void TestKeyTransRecipientIdValue_FixedValue()
{
KeyTransRecipientInfo recipient = FixedValueKeyTrans1();
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
object value = subjectIdentifier.Value;
Assert.True(value is X509IssuerSerial);
X509IssuerSerial xis = (X509IssuerSerial)value;
Assert.Equal("CN=RSAKeyTransfer1", xis.IssuerName);
Assert.Equal("31D935FB63E8CFAB48A0BF7B397B67C0", xis.SerialNumber);
}
[Fact]
public static void TestKeyTransRecipientIdType_Ski_RoundTrip()
{
KeyTransRecipientInfo recipient = EncodeKeyTransl(SubjectIdentifierType.SubjectKeyIdentifier);
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
Assert.Equal(SubjectIdentifierType.SubjectKeyIdentifier, subjectIdentifier.Type);
}
[Fact]
public static void TestKeyTransRecipientIdType_Ski_FixedValue()
{
KeyTransRecipientInfo recipient = FixedValueKeyTrans1(SubjectIdentifierType.SubjectKeyIdentifier);
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
Assert.Equal(SubjectIdentifierType.SubjectKeyIdentifier, subjectIdentifier.Type);
}
[Fact]
public static void TestKeyTransRecipientIdValue_Ski_RoundTrip()
{
KeyTransRecipientInfo recipient = EncodeKeyTransl(SubjectIdentifierType.SubjectKeyIdentifier);
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
object value = subjectIdentifier.Value;
Assert.True(value is string);
string ski = (string)value;
Assert.Equal("F2008AA9FA3742E8370CB1674CE1D1582921DCC3", ski);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void TestKeyTransRecipientIdValue_ExplicitSki_RoundTrip()
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
EnvelopedCms ecms = new EnvelopedCms(contentInfo);
using (X509Certificate2 cert = Certificates.RSAKeyTransfer_ExplicitSki.GetCertificate())
{
CmsRecipient cmsRecipient = new CmsRecipient(SubjectIdentifierType.SubjectKeyIdentifier, cert);
ecms.Encrypt(cmsRecipient);
}
byte[] encodedMessage = ecms.Encode();
EnvelopedCms ecms2 = new EnvelopedCms();
ecms2.Decode(encodedMessage);
RecipientInfoCollection recipients = ecms2.RecipientInfos;
Assert.Equal(1, recipients.Count);
RecipientInfo recipientInfo = recipients[0];
Assert.IsType<KeyTransRecipientInfo>(recipientInfo);
KeyTransRecipientInfo recipient = (KeyTransRecipientInfo)recipientInfo;
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
object value = subjectIdentifier.Value;
Assert.IsType<string>(value);
string ski = (string)value;
Assert.Equal("01952851C55DB594B0C6167F5863C5B6B67AEFE6", ski);
}
[Fact]
public static void TestKeyTransRecipientIdValue_Ski_FixedValue()
{
KeyTransRecipientInfo recipient = FixedValueKeyTrans1(SubjectIdentifierType.SubjectKeyIdentifier);
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
object value = subjectIdentifier.Value;
Assert.True(value is string);
string ski = (string)value;
Assert.Equal("F2008AA9FA3742E8370CB1674CE1D1582921DCC3", ski);
}
[Fact]
public static void TestKeyTransKeyEncryptionAlgorithm_RoundTrip()
{
KeyTransRecipientInfo recipient = EncodeKeyTransl();
AlgorithmIdentifier a = recipient.KeyEncryptionAlgorithm;
Assert.Equal(Oids.Rsa, a.Oid.Value);
Assert.Equal(0, a.KeyLength);
}
[Fact]
public static void TestKeyTransKeyEncryptionAlgorithm_FixedValue()
{
KeyTransRecipientInfo recipient = FixedValueKeyTrans1();
AlgorithmIdentifier a = recipient.KeyEncryptionAlgorithm;
Assert.Equal(Oids.Rsa, a.Oid.Value);
Assert.Equal(0, a.KeyLength);
}
[Fact]
public static void TestKeyTransEncryptedKey_RoundTrip()
{
KeyTransRecipientInfo recipient = EncodeKeyTransl();
byte[] encryptedKey = recipient.EncryptedKey;
Assert.Equal(128, encryptedKey.Length); // Since the content encryption key is randomly generated each time, we can only test the length.
}
[Fact]
public static void TestKeyTransEncryptedKey_FixedValue()
{
byte[] expectedEncryptedKey =
("5ebb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee5"
+ "0c25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160"
+ "c496726216e986869eed578bda652855c85604a056201538ee56b6c4").HexToByteArray();
KeyTransRecipientInfo recipient = FixedValueKeyTrans1();
byte[] encryptedKey = recipient.EncryptedKey;
Assert.Equal<byte>(expectedEncryptedKey, encryptedKey);
}
private static KeyTransRecipientInfo EncodeKeyTransl(SubjectIdentifierType type = SubjectIdentifierType.IssuerAndSerialNumber)
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
EnvelopedCms ecms = new EnvelopedCms(contentInfo);
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
{
CmsRecipient cmsRecipient = new CmsRecipient(type, cert);
ecms.Encrypt(cmsRecipient);
}
byte[] encodedMessage = ecms.Encode();
EnvelopedCms ecms2 = new EnvelopedCms();
ecms2.Decode(encodedMessage);
RecipientInfoCollection recipients = ecms2.RecipientInfos;
Assert.Equal(1, recipients.Count);
RecipientInfo recipientInfo = recipients[0];
Assert.IsType<KeyTransRecipientInfo>(recipientInfo);
return (KeyTransRecipientInfo)recipientInfo;
}
private static KeyTransRecipientInfo FixedValueKeyTrans1(SubjectIdentifierType type = SubjectIdentifierType.IssuerAndSerialNumber)
{
byte[] encodedMessage;
switch (type)
{
case SubjectIdentifierType.IssuerAndSerialNumber:
encodedMessage = s_KeyTransEncodedMessage;
break;
case SubjectIdentifierType.SubjectKeyIdentifier:
encodedMessage = s_KeyTransEncodedMessage_Ski;
break;
default:
throw new Exception("Bad SubjectIdentifierType.");
}
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
RecipientInfoCollection recipients = ecms.RecipientInfos;
Assert.Equal(1, recipients.Count);
RecipientInfo recipientInfo = recipients[0];
Assert.IsType<KeyTransRecipientInfo>(recipientInfo);
return (KeyTransRecipientInfo)recipientInfo;
}
private static byte[] s_KeyTransEncodedMessage =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e"
+ "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c"
+ "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4"
+ "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d"
+ "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray();
private static byte[] s_KeyTransEncodedMessage_Ski =
("3081f206092a864886f70d010703a081e43081e10201023181ae3081ab0201028014f2008aa9fa3742e8370cb1674ce1d158"
+ "2921dcc3300d06092a864886f70d01010105000481804336e978bc72ba2f5264cd854867fac438f36f2b3df6004528f2df83"
+ "4fb2113d6f7c07667e7296b029756222d6ced396a8fffed32be838eec7f2e54b9467fa80f85d097f7d1f0fbde57e07ab3d46"
+ "a60b31f37ef9844dcab2a8eef4fec5579fac5ec1e7ee82409898e17d30c3ac1a407fca15d23c9df2904a707294d78d4300ba"
+ "302b06092a864886f70d010701301406082a864886f70d03070408355c596e3e8540608008f1f811e862e51bbd").HexToByteArray();
}
}
| // 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.Linq;
using System.Globalization;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
using Xunit;
using Test.Cryptography;
using System.Security.Cryptography.Pkcs.Tests;
namespace System.Security.Cryptography.Pkcs.EnvelopedCmsTests.Tests
{
public static partial class KeyTransRecipientInfoTests
{
[Fact]
public static void TestKeyTransVersion_RoundTrip()
{
KeyTransRecipientInfo recipient = EncodeKeyTransl();
Assert.Equal(0, recipient.Version);
}
[Fact]
public static void TestKeyTransVersion_FixedValue()
{
KeyTransRecipientInfo recipient = FixedValueKeyTrans1();
Assert.Equal(0, recipient.Version);
}
[Fact]
public static void TestKeyTransType_RoundTrip()
{
KeyTransRecipientInfo recipient = EncodeKeyTransl();
Assert.Equal(RecipientInfoType.KeyTransport, recipient.Type);
}
[Fact]
public static void TestKeyTransType_FixedValue()
{
KeyTransRecipientInfo recipient = FixedValueKeyTrans1();
Assert.Equal(RecipientInfoType.KeyTransport, recipient.Type);
}
[Fact]
public static void TestKeyTransRecipientIdType_RoundTrip()
{
KeyTransRecipientInfo recipient = EncodeKeyTransl();
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, subjectIdentifier.Type);
}
[Fact]
public static void TestKeyTransRecipientIdType_FixedValue()
{
KeyTransRecipientInfo recipient = FixedValueKeyTrans1();
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, subjectIdentifier.Type);
}
[Fact]
public static void TestKeyTransRecipientIdValue_RoundTrip()
{
KeyTransRecipientInfo recipient = EncodeKeyTransl();
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
object value = subjectIdentifier.Value;
Assert.True(value is X509IssuerSerial);
X509IssuerSerial xis = (X509IssuerSerial)value;
Assert.Equal("CN=RSAKeyTransfer1", xis.IssuerName);
Assert.Equal("31D935FB63E8CFAB48A0BF7B397B67C0", xis.SerialNumber);
}
[Fact]
public static void TestKeyTransRecipientIdValue_FixedValue()
{
KeyTransRecipientInfo recipient = FixedValueKeyTrans1();
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
object value = subjectIdentifier.Value;
Assert.True(value is X509IssuerSerial);
X509IssuerSerial xis = (X509IssuerSerial)value;
Assert.Equal("CN=RSAKeyTransfer1", xis.IssuerName);
Assert.Equal("31D935FB63E8CFAB48A0BF7B397B67C0", xis.SerialNumber);
}
[Fact]
public static void TestKeyTransRecipientIdType_Ski_RoundTrip()
{
KeyTransRecipientInfo recipient = EncodeKeyTransl(SubjectIdentifierType.SubjectKeyIdentifier);
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
Assert.Equal(SubjectIdentifierType.SubjectKeyIdentifier, subjectIdentifier.Type);
}
[Fact]
public static void TestKeyTransRecipientIdType_Ski_FixedValue()
{
KeyTransRecipientInfo recipient = FixedValueKeyTrans1(SubjectIdentifierType.SubjectKeyIdentifier);
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
Assert.Equal(SubjectIdentifierType.SubjectKeyIdentifier, subjectIdentifier.Type);
}
[Fact]
public static void TestKeyTransRecipientIdValue_Ski_RoundTrip()
{
KeyTransRecipientInfo recipient = EncodeKeyTransl(SubjectIdentifierType.SubjectKeyIdentifier);
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
object value = subjectIdentifier.Value;
Assert.True(value is string);
string ski = (string)value;
Assert.Equal("F2008AA9FA3742E8370CB1674CE1D1582921DCC3", ski);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void TestKeyTransRecipientIdValue_ExplicitSki_RoundTrip()
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
EnvelopedCms ecms = new EnvelopedCms(contentInfo);
using (X509Certificate2 cert = Certificates.RSAKeyTransfer_ExplicitSki.GetCertificate())
{
CmsRecipient cmsRecipient = new CmsRecipient(SubjectIdentifierType.SubjectKeyIdentifier, cert);
ecms.Encrypt(cmsRecipient);
}
byte[] encodedMessage = ecms.Encode();
EnvelopedCms ecms2 = new EnvelopedCms();
ecms2.Decode(encodedMessage);
RecipientInfoCollection recipients = ecms2.RecipientInfos;
Assert.Equal(1, recipients.Count);
RecipientInfo recipientInfo = recipients[0];
Assert.IsType<KeyTransRecipientInfo>(recipientInfo);
KeyTransRecipientInfo recipient = (KeyTransRecipientInfo)recipientInfo;
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
object value = subjectIdentifier.Value;
Assert.IsType<string>(value);
string ski = (string)value;
Assert.Equal("01952851C55DB594B0C6167F5863C5B6B67AEFE6", ski);
}
[Fact]
public static void TestKeyTransRecipientIdValue_Ski_FixedValue()
{
KeyTransRecipientInfo recipient = FixedValueKeyTrans1(SubjectIdentifierType.SubjectKeyIdentifier);
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
object value = subjectIdentifier.Value;
Assert.True(value is string);
string ski = (string)value;
Assert.Equal("F2008AA9FA3742E8370CB1674CE1D1582921DCC3", ski);
}
[Fact]
public static void TestKeyTransKeyEncryptionAlgorithm_RoundTrip()
{
KeyTransRecipientInfo recipient = EncodeKeyTransl();
AlgorithmIdentifier a = recipient.KeyEncryptionAlgorithm;
Assert.Equal(Oids.Rsa, a.Oid.Value);
Assert.Equal(0, a.KeyLength);
}
[Fact]
public static void TestKeyTransKeyEncryptionAlgorithm_FixedValue()
{
KeyTransRecipientInfo recipient = FixedValueKeyTrans1();
AlgorithmIdentifier a = recipient.KeyEncryptionAlgorithm;
Assert.Equal(Oids.Rsa, a.Oid.Value);
Assert.Equal(0, a.KeyLength);
}
[Fact]
public static void TestKeyTransEncryptedKey_RoundTrip()
{
KeyTransRecipientInfo recipient = EncodeKeyTransl();
byte[] encryptedKey = recipient.EncryptedKey;
Assert.Equal(128, encryptedKey.Length); // Since the content encryption key is randomly generated each time, we can only test the length.
}
[Fact]
public static void TestKeyTransEncryptedKey_FixedValue()
{
byte[] expectedEncryptedKey =
("5ebb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee5"
+ "0c25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160"
+ "c496726216e986869eed578bda652855c85604a056201538ee56b6c4").HexToByteArray();
KeyTransRecipientInfo recipient = FixedValueKeyTrans1();
byte[] encryptedKey = recipient.EncryptedKey;
Assert.Equal<byte>(expectedEncryptedKey, encryptedKey);
}
private static KeyTransRecipientInfo EncodeKeyTransl(SubjectIdentifierType type = SubjectIdentifierType.IssuerAndSerialNumber)
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
EnvelopedCms ecms = new EnvelopedCms(contentInfo);
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
{
CmsRecipient cmsRecipient = new CmsRecipient(type, cert);
ecms.Encrypt(cmsRecipient);
}
byte[] encodedMessage = ecms.Encode();
EnvelopedCms ecms2 = new EnvelopedCms();
ecms2.Decode(encodedMessage);
RecipientInfoCollection recipients = ecms2.RecipientInfos;
Assert.Equal(1, recipients.Count);
RecipientInfo recipientInfo = recipients[0];
Assert.IsType<KeyTransRecipientInfo>(recipientInfo);
return (KeyTransRecipientInfo)recipientInfo;
}
private static KeyTransRecipientInfo FixedValueKeyTrans1(SubjectIdentifierType type = SubjectIdentifierType.IssuerAndSerialNumber)
{
byte[] encodedMessage;
switch (type)
{
case SubjectIdentifierType.IssuerAndSerialNumber:
encodedMessage = s_KeyTransEncodedMessage;
break;
case SubjectIdentifierType.SubjectKeyIdentifier:
encodedMessage = s_KeyTransEncodedMessage_Ski;
break;
default:
throw new Exception("Bad SubjectIdentifierType.");
}
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
RecipientInfoCollection recipients = ecms.RecipientInfos;
Assert.Equal(1, recipients.Count);
RecipientInfo recipientInfo = recipients[0];
Assert.IsType<KeyTransRecipientInfo>(recipientInfo);
return (KeyTransRecipientInfo)recipientInfo;
}
private static byte[] s_KeyTransEncodedMessage =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e"
+ "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c"
+ "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4"
+ "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d"
+ "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray();
private static byte[] s_KeyTransEncodedMessage_Ski =
("3081f206092a864886f70d010703a081e43081e10201023181ae3081ab0201028014f2008aa9fa3742e8370cb1674ce1d158"
+ "2921dcc3300d06092a864886f70d01010105000481804336e978bc72ba2f5264cd854867fac438f36f2b3df6004528f2df83"
+ "4fb2113d6f7c07667e7296b029756222d6ced396a8fffed32be838eec7f2e54b9467fa80f85d097f7d1f0fbde57e07ab3d46"
+ "a60b31f37ef9844dcab2a8eef4fec5579fac5ec1e7ee82409898e17d30c3ac1a407fca15d23c9df2904a707294d78d4300ba"
+ "302b06092a864886f70d010701301406082a864886f70d03070408355c596e3e8540608008f1f811e862e51bbd").HexToByteArray();
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.IO.Ports/tests/SerialPort/Open.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.IO.PortsTests;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class Open : PortsTest
{
[ConditionalFact(nameof(HasOneSerialPort))]
public void OpenDefault()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
com.Open();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
Debug.WriteLine("BytesToWrite={0}", com.BytesToWrite);
serPortProp.VerifyPropertiesAndPrint(com);
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void OpenTwice()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
Debug.WriteLine("Verifying after calling Open() twice");
com.Open();
Assert.Throws<InvalidOperationException>(() => com.Open());
serPortProp.VerifyPropertiesAndPrint(com);
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void OpenTwoInstances()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp1 = new SerialPortProperties();
SerialPortProperties serPortProp2 = new SerialPortProperties();
Debug.WriteLine("Verifying calling Open() on two instances of SerialPort");
serPortProp1.SetAllPropertiesToOpenDefaults();
serPortProp1.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
serPortProp2.SetAllPropertiesToDefaults();
serPortProp2.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
Assert.Throws<UnauthorizedAccessException>(() => com2.Open());
serPortProp1.VerifyPropertiesAndPrint(com1);
serPortProp2.VerifyPropertiesAndPrint(com2);
}
}
}
}
| // 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.IO.PortsTests;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class Open : PortsTest
{
[ConditionalFact(nameof(HasOneSerialPort))]
public void OpenDefault()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
com.Open();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
Debug.WriteLine("BytesToWrite={0}", com.BytesToWrite);
serPortProp.VerifyPropertiesAndPrint(com);
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void OpenTwice()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
Debug.WriteLine("Verifying after calling Open() twice");
com.Open();
Assert.Throws<InvalidOperationException>(() => com.Open());
serPortProp.VerifyPropertiesAndPrint(com);
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void OpenTwoInstances()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp1 = new SerialPortProperties();
SerialPortProperties serPortProp2 = new SerialPortProperties();
Debug.WriteLine("Verifying calling Open() on two instances of SerialPort");
serPortProp1.SetAllPropertiesToOpenDefaults();
serPortProp1.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
serPortProp2.SetAllPropertiesToDefaults();
serPortProp2.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
Assert.Throws<UnauthorizedAccessException>(() => com2.Open());
serPortProp1.VerifyPropertiesAndPrint(com1);
serPortProp2.VerifyPropertiesAndPrint(com2);
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Icu.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;
namespace System.Globalization
{
internal sealed partial class CultureData
{
// ICU constants
private const int ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY = 100; // max size of keyword or value
private const int ICU_ULOC_FULLNAME_CAPACITY = 157; // max size of locale name
/// <summary>
/// This method uses the sRealName field (which is initialized by the constructor before this is called) to
/// initialize the rest of the state of CultureData based on the underlying OS globalization library.
/// </summary>
private bool InitIcuCultureDataCore()
{
Debug.Assert(_sRealName != null);
Debug.Assert(!GlobalizationMode.Invariant);
const string ICU_COLLATION_KEYWORD = "@collation=";
string realNameBuffer = _sRealName;
// Basic validation
if (!IsValidCultureName(realNameBuffer, out var index))
{
return false;
}
// Replace _ (alternate sort) with @collation= for ICU
ReadOnlySpan<char> alternateSortName = default;
if (index > 0)
{
alternateSortName = realNameBuffer.AsSpan(index + 1);
realNameBuffer = string.Concat(realNameBuffer.AsSpan(0, index), ICU_COLLATION_KEYWORD, alternateSortName);
}
// Get the locale name from ICU
if (!GetLocaleName(realNameBuffer, out _sWindowsName))
{
return false; // fail
}
// Replace the ICU collation keyword with an _
Debug.Assert(_sWindowsName != null);
index = _sWindowsName.IndexOf(ICU_COLLATION_KEYWORD, StringComparison.Ordinal);
if (index >= 0)
{
// Use original culture name if alternateSortName is not set, which is possible even if the normalized
// culture name has "@collation=".
// "zh-TW-u-co-zhuyin" is a good example. The term "u-co-" means the following part will be the sort name
// and it will be treated in ICU as "zh-TW@collation=zhuyin".
_sName = alternateSortName.Length == 0 ? realNameBuffer : string.Concat(_sWindowsName.AsSpan(0, index), "_", alternateSortName);
}
else
{
_sName = _sWindowsName;
}
_sRealName = _sName;
_iLanguage = LCID;
if (_iLanguage == 0)
{
_iLanguage = CultureInfo.LOCALE_CUSTOM_UNSPECIFIED;
}
_bNeutral = TwoLetterISOCountryName.Length == 0;
_sSpecificCulture = _bNeutral ? IcuLocaleData.GetSpecificCultureName(_sRealName) : _sRealName;
// Remove the sort from sName unless custom culture
if (index > 0 && !_bNeutral && !IsCustomCultureId(_iLanguage))
{
_sName = _sWindowsName.Substring(0, index);
}
return true;
}
internal static unsafe bool GetLocaleName(string localeName, out string? windowsName)
{
// Get the locale name from ICU
char* buffer = stackalloc char[ICU_ULOC_FULLNAME_CAPACITY];
if (!Interop.Globalization.GetLocaleName(localeName, buffer, ICU_ULOC_FULLNAME_CAPACITY))
{
windowsName = null;
return false; // fail
}
// Success - use the locale name returned which may be different than realNameBuffer (casing)
windowsName = new string(buffer); // the name passed to subsequent ICU calls
return true;
}
internal static unsafe bool GetDefaultLocaleName([NotNullWhen(true)] out string? windowsName)
{
// Get the default (system) locale name from ICU
char* buffer = stackalloc char[ICU_ULOC_FULLNAME_CAPACITY];
if (!Interop.Globalization.GetDefaultLocaleName(buffer, ICU_ULOC_FULLNAME_CAPACITY))
{
windowsName = null;
return false; // fail
}
// Success - use the locale name returned which may be different than realNameBuffer (casing)
windowsName = new string(buffer); // the name passed to subsequent ICU calls
return true;
}
private string IcuGetLocaleInfo(LocaleStringData type, string? uiCultureName = null)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!GlobalizationMode.UseNls);
Debug.Assert(_sWindowsName != null, "[CultureData.IcuGetLocaleInfo] Expected _sWindowsName to be populated already");
return IcuGetLocaleInfo(_sWindowsName, type, uiCultureName);
}
// For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the
// "windows" name, which can be specific for downlevel (< windows 7) os's.
private unsafe string IcuGetLocaleInfo(string localeName, LocaleStringData type, string? uiCultureName = null)
{
Debug.Assert(!GlobalizationMode.UseNls);
Debug.Assert(localeName != null, "[CultureData.IcuGetLocaleInfo] Expected localeName to be not be null");
switch (type)
{
case LocaleStringData.NegativeInfinitySymbol:
// not an equivalent in ICU; prefix the PositiveInfinitySymbol with NegativeSign
return IcuGetLocaleInfo(localeName, LocaleStringData.NegativeSign) +
IcuGetLocaleInfo(localeName, LocaleStringData.PositiveInfinitySymbol);
}
char* buffer = stackalloc char[ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY];
bool result = Interop.Globalization.GetLocaleInfoString(localeName, (uint)type, buffer, ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY, uiCultureName);
if (!result)
{
// Failed, just use empty string
Debug.Fail("[CultureData.IcuGetLocaleInfo(LocaleStringData)] Failed");
return string.Empty;
}
return new string(buffer);
}
private int IcuGetLocaleInfo(LocaleNumberData type)
{
Debug.Assert(!GlobalizationMode.UseNls);
Debug.Assert(_sWindowsName != null, "[CultureData.IcuGetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already");
switch (type)
{
case LocaleNumberData.CalendarType:
// returning 0 will cause the first supported calendar to be returned, which is the preferred calendar
return 0;
}
int value = 0;
bool result = Interop.Globalization.GetLocaleInfoInt(_sWindowsName, (uint)type, ref value);
if (!result)
{
// Failed, just use 0
Debug.Fail("[CultureData.IcuGetLocaleInfo(LocaleNumberData)] failed");
}
return value;
}
private int[] IcuGetLocaleInfo(LocaleGroupingData type)
{
Debug.Assert(!GlobalizationMode.UseNls);
Debug.Assert(_sWindowsName != null, "[CultureData.IcuGetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already");
int primaryGroupingSize = 0;
int secondaryGroupingSize = 0;
bool result = Interop.Globalization.GetLocaleInfoGroupingSizes(_sWindowsName, (uint)type, ref primaryGroupingSize, ref secondaryGroupingSize);
if (!result)
{
Debug.Fail("[CultureData.IcuGetLocaleInfo(LocaleGroupingData type)] failed");
}
if (secondaryGroupingSize == 0)
{
return new int[] { primaryGroupingSize };
}
return new int[] { primaryGroupingSize, secondaryGroupingSize };
}
private string IcuGetTimeFormatString() => IcuGetTimeFormatString(shortFormat: false);
private unsafe string IcuGetTimeFormatString(bool shortFormat)
{
Debug.Assert(!GlobalizationMode.UseNls);
Debug.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already");
char* buffer = stackalloc char[ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY];
bool result = Interop.Globalization.GetLocaleTimeFormat(_sWindowsName, shortFormat, buffer, ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
if (!result)
{
// Failed, just use empty string
Debug.Fail("[CultureData.GetTimeFormatString(bool shortFormat)] Failed");
return string.Empty;
}
var span = new ReadOnlySpan<char>(buffer, ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
return ConvertIcuTimeFormatString(span.Slice(0, span.IndexOf('\0')));
}
// no support to lookup by region name, other than the hard-coded list in CultureData
private static CultureData? IcuGetCultureDataFromRegionName() => null;
private string IcuGetLanguageDisplayName(string cultureName) => IcuGetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName, CultureInfo.CurrentUICulture.Name);
// use the fallback which is to return NativeName
private static string? IcuGetRegionDisplayName() => null;
internal static bool IcuIsEnsurePredefinedLocaleName(string name)
{
Debug.Assert(!GlobalizationMode.UseNls);
return Interop.Globalization.IsPredefinedLocale(name);
}
private static string ConvertIcuTimeFormatString(ReadOnlySpan<char> icuFormatString)
{
Debug.Assert(icuFormatString.Length < ICU_ULOC_FULLNAME_CAPACITY);
Span<char> result = stackalloc char[ICU_ULOC_FULLNAME_CAPACITY];
bool amPmAdded = false;
int resultPos = 0;
for (int i = 0; i < icuFormatString.Length; i++)
{
switch (icuFormatString[i])
{
case '\'':
result[resultPos++] = icuFormatString[i++];
while (i < icuFormatString.Length)
{
char current = icuFormatString[i];
result[resultPos++] = current;
if (current == '\'')
{
break;
}
i++;
}
break;
case ':':
case '.':
case 'H':
case 'h':
case 'm':
case 's':
result[resultPos++] = icuFormatString[i];
break;
case ' ':
case '\u00A0':
// Convert nonbreaking spaces into regular spaces
result[resultPos++] = ' ';
break;
case 'a': // AM/PM
if (!amPmAdded)
{
amPmAdded = true;
result[resultPos++] = 't';
result[resultPos++] = 't';
}
break;
}
}
return result.Slice(0, resultPos).ToString();
}
private static int IcuLocaleNameToLCID(string cultureName)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!GlobalizationMode.UseNls);
int lcid = IcuLocaleData.GetLocaleDataNumericPart(cultureName, IcuLocaleDataParts.Lcid);
return lcid == -1 ? CultureInfo.LOCALE_CUSTOM_UNSPECIFIED : lcid;
}
private static int IcuGetGeoId(string cultureName)
{
Debug.Assert(!GlobalizationMode.UseNls);
int geoId = IcuLocaleData.GetLocaleDataNumericPart(cultureName, IcuLocaleDataParts.GeoId);
return geoId == -1 ? CultureData.Invariant.GeoId : geoId;
}
private const uint DigitSubstitutionMask = 0x0000FFFF;
private const uint ListSeparatorMask = 0xFFFF0000;
private static int IcuGetDigitSubstitution(string cultureName)
{
Debug.Assert(!GlobalizationMode.UseNls);
int digitSubstitution = IcuLocaleData.GetLocaleDataNumericPart(cultureName, IcuLocaleDataParts.DigitSubstitutionOrListSeparator);
return digitSubstitution == -1 ? (int) DigitShapes.None : (int)(digitSubstitution & DigitSubstitutionMask);
}
private static string IcuGetListSeparator(string? cultureName)
{
Debug.Assert(!GlobalizationMode.UseNls);
Debug.Assert(cultureName != null);
int separator = IcuLocaleData.GetLocaleDataNumericPart(cultureName, IcuLocaleDataParts.DigitSubstitutionOrListSeparator);
if (separator != -1)
{
switch (separator & ListSeparatorMask)
{
case IcuLocaleData.CommaSep:
return ",";
case IcuLocaleData.SemicolonSep:
return ";";
case IcuLocaleData.ArabicCommaSep:
return "\u060C";
case IcuLocaleData.ArabicSemicolonSep:
return "\u061B";
case IcuLocaleData.DoubleCommaSep:
return ",,";
default:
Debug.Assert(false, "[CultureData.IcuGetListSeparator] Unexpected ListSeparator value.");
break;
}
}
return ","; // default separator
}
private static string IcuGetThreeLetterWindowsLanguageName(string cultureName)
{
Debug.Assert(!GlobalizationMode.UseNls);
return IcuLocaleData.GetThreeLetterWindowsLanguageName(cultureName) ?? "ZZZ" /* default lang name */;
}
private static CultureInfo[] IcuEnumCultures(CultureTypes types)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!GlobalizationMode.UseNls);
if ((types & (CultureTypes.NeutralCultures | CultureTypes.SpecificCultures)) == 0)
{
return Array.Empty<CultureInfo>();
}
int bufferLength = Interop.Globalization.GetLocales(null, 0);
if (bufferLength <= 0)
{
return Array.Empty<CultureInfo>();
}
char [] chars = new char[bufferLength];
bufferLength = Interop.Globalization.GetLocales(chars, bufferLength);
if (bufferLength <= 0)
{
return Array.Empty<CultureInfo>();
}
bool enumNeutrals = (types & CultureTypes.NeutralCultures) != 0;
bool enumSpecificss = (types & CultureTypes.SpecificCultures) != 0;
List<CultureInfo> list = new List<CultureInfo>();
if (enumNeutrals)
{
list.Add(CultureInfo.InvariantCulture);
}
int index = 0;
while (index < bufferLength)
{
int length = (int) chars[index++];
if (index + length <= bufferLength)
{
CultureInfo ci = CultureInfo.GetCultureInfo(new string(chars, index, length));
if ((enumNeutrals && ci.IsNeutralCulture) || (enumSpecificss && !ci.IsNeutralCulture))
{
list.Add(ci);
}
}
index += length;
}
return list.ToArray();
}
private static string IcuGetConsoleFallbackName(string cultureName)
{
Debug.Assert(!GlobalizationMode.UseNls);
return IcuLocaleData.GetConsoleUICulture(cultureName);
}
/// <summary>
/// Implementation of culture name validation.
/// </summary>
/// <remarks>
/// This is a fast approximate implementation based on BCP47 spec. It covers only parts of
/// the spec; such that, when it returns false, the input is definitely in incorrect format.
/// However, it returns true for some characters which are not allowed by the spec. It also
/// returns true for some inputs where spec specifies the lengths of subtags, but we are not
/// validating subtags individually to keep algorithm's computational complexity at O(n).
///
/// Rules of implementation:
/// * Allow only letters, digits, - and '_' or \0 (NULL is for backward compatibility).
/// * Allow input length of zero (for invariant culture) or otherwise greater than 1 and less than or equal LocaleNameMaxLength.
/// * Disallow input that starts or ends with '-' or '_'.
/// * Disallow input that has any combination of consecutive '-' or '_'.
/// * Disallow input that has multiple '_'.
/// </remarks>
private static bool IsValidCultureName(string subject, out int indexOfUnderscore)
{
indexOfUnderscore = -1;
if (subject.Length == 0) return true; // Invariant Culture
if (subject.Length == 1 || subject.Length > LocaleNameMaxLength) return false;
bool seenUnderscore = false;
for (int i = 0; i < subject.Length; ++i)
{
char c = subject[i];
if ((uint)(c - 'A') <= ('Z' - 'A') || (uint)(c - 'a') <= ('z' - 'a') || (uint)(c - '0') <= ('9' - '0') || c == '\0')
{
continue;
}
if (c == '_' || c == '-')
{
if (i == 0 || i == subject.Length - 1) return false;
if (subject[i - 1] == '_' || subject[i - 1] == '-') return false;
if (c == '_')
{
if (seenUnderscore) return false; // only one _ is allowed
seenUnderscore = true;
indexOfUnderscore = i;
}
}
else
{
return false;
}
}
return true;
}
}
}
| // 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;
namespace System.Globalization
{
internal sealed partial class CultureData
{
// ICU constants
private const int ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY = 100; // max size of keyword or value
private const int ICU_ULOC_FULLNAME_CAPACITY = 157; // max size of locale name
/// <summary>
/// This method uses the sRealName field (which is initialized by the constructor before this is called) to
/// initialize the rest of the state of CultureData based on the underlying OS globalization library.
/// </summary>
private bool InitIcuCultureDataCore()
{
Debug.Assert(_sRealName != null);
Debug.Assert(!GlobalizationMode.Invariant);
const string ICU_COLLATION_KEYWORD = "@collation=";
string realNameBuffer = _sRealName;
// Basic validation
if (!IsValidCultureName(realNameBuffer, out var index))
{
return false;
}
// Replace _ (alternate sort) with @collation= for ICU
ReadOnlySpan<char> alternateSortName = default;
if (index > 0)
{
alternateSortName = realNameBuffer.AsSpan(index + 1);
realNameBuffer = string.Concat(realNameBuffer.AsSpan(0, index), ICU_COLLATION_KEYWORD, alternateSortName);
}
// Get the locale name from ICU
if (!GetLocaleName(realNameBuffer, out _sWindowsName))
{
return false; // fail
}
// Replace the ICU collation keyword with an _
Debug.Assert(_sWindowsName != null);
index = _sWindowsName.IndexOf(ICU_COLLATION_KEYWORD, StringComparison.Ordinal);
if (index >= 0)
{
// Use original culture name if alternateSortName is not set, which is possible even if the normalized
// culture name has "@collation=".
// "zh-TW-u-co-zhuyin" is a good example. The term "u-co-" means the following part will be the sort name
// and it will be treated in ICU as "zh-TW@collation=zhuyin".
_sName = alternateSortName.Length == 0 ? realNameBuffer : string.Concat(_sWindowsName.AsSpan(0, index), "_", alternateSortName);
}
else
{
_sName = _sWindowsName;
}
_sRealName = _sName;
_iLanguage = LCID;
if (_iLanguage == 0)
{
_iLanguage = CultureInfo.LOCALE_CUSTOM_UNSPECIFIED;
}
_bNeutral = TwoLetterISOCountryName.Length == 0;
_sSpecificCulture = _bNeutral ? IcuLocaleData.GetSpecificCultureName(_sRealName) : _sRealName;
// Remove the sort from sName unless custom culture
if (index > 0 && !_bNeutral && !IsCustomCultureId(_iLanguage))
{
_sName = _sWindowsName.Substring(0, index);
}
return true;
}
internal static unsafe bool GetLocaleName(string localeName, out string? windowsName)
{
// Get the locale name from ICU
char* buffer = stackalloc char[ICU_ULOC_FULLNAME_CAPACITY];
if (!Interop.Globalization.GetLocaleName(localeName, buffer, ICU_ULOC_FULLNAME_CAPACITY))
{
windowsName = null;
return false; // fail
}
// Success - use the locale name returned which may be different than realNameBuffer (casing)
windowsName = new string(buffer); // the name passed to subsequent ICU calls
return true;
}
internal static unsafe bool GetDefaultLocaleName([NotNullWhen(true)] out string? windowsName)
{
// Get the default (system) locale name from ICU
char* buffer = stackalloc char[ICU_ULOC_FULLNAME_CAPACITY];
if (!Interop.Globalization.GetDefaultLocaleName(buffer, ICU_ULOC_FULLNAME_CAPACITY))
{
windowsName = null;
return false; // fail
}
// Success - use the locale name returned which may be different than realNameBuffer (casing)
windowsName = new string(buffer); // the name passed to subsequent ICU calls
return true;
}
private string IcuGetLocaleInfo(LocaleStringData type, string? uiCultureName = null)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!GlobalizationMode.UseNls);
Debug.Assert(_sWindowsName != null, "[CultureData.IcuGetLocaleInfo] Expected _sWindowsName to be populated already");
return IcuGetLocaleInfo(_sWindowsName, type, uiCultureName);
}
// For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the
// "windows" name, which can be specific for downlevel (< windows 7) os's.
private unsafe string IcuGetLocaleInfo(string localeName, LocaleStringData type, string? uiCultureName = null)
{
Debug.Assert(!GlobalizationMode.UseNls);
Debug.Assert(localeName != null, "[CultureData.IcuGetLocaleInfo] Expected localeName to be not be null");
switch (type)
{
case LocaleStringData.NegativeInfinitySymbol:
// not an equivalent in ICU; prefix the PositiveInfinitySymbol with NegativeSign
return IcuGetLocaleInfo(localeName, LocaleStringData.NegativeSign) +
IcuGetLocaleInfo(localeName, LocaleStringData.PositiveInfinitySymbol);
}
char* buffer = stackalloc char[ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY];
bool result = Interop.Globalization.GetLocaleInfoString(localeName, (uint)type, buffer, ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY, uiCultureName);
if (!result)
{
// Failed, just use empty string
Debug.Fail("[CultureData.IcuGetLocaleInfo(LocaleStringData)] Failed");
return string.Empty;
}
return new string(buffer);
}
private int IcuGetLocaleInfo(LocaleNumberData type)
{
Debug.Assert(!GlobalizationMode.UseNls);
Debug.Assert(_sWindowsName != null, "[CultureData.IcuGetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already");
switch (type)
{
case LocaleNumberData.CalendarType:
// returning 0 will cause the first supported calendar to be returned, which is the preferred calendar
return 0;
}
int value = 0;
bool result = Interop.Globalization.GetLocaleInfoInt(_sWindowsName, (uint)type, ref value);
if (!result)
{
// Failed, just use 0
Debug.Fail("[CultureData.IcuGetLocaleInfo(LocaleNumberData)] failed");
}
return value;
}
private int[] IcuGetLocaleInfo(LocaleGroupingData type)
{
Debug.Assert(!GlobalizationMode.UseNls);
Debug.Assert(_sWindowsName != null, "[CultureData.IcuGetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already");
int primaryGroupingSize = 0;
int secondaryGroupingSize = 0;
bool result = Interop.Globalization.GetLocaleInfoGroupingSizes(_sWindowsName, (uint)type, ref primaryGroupingSize, ref secondaryGroupingSize);
if (!result)
{
Debug.Fail("[CultureData.IcuGetLocaleInfo(LocaleGroupingData type)] failed");
}
if (secondaryGroupingSize == 0)
{
return new int[] { primaryGroupingSize };
}
return new int[] { primaryGroupingSize, secondaryGroupingSize };
}
private string IcuGetTimeFormatString() => IcuGetTimeFormatString(shortFormat: false);
private unsafe string IcuGetTimeFormatString(bool shortFormat)
{
Debug.Assert(!GlobalizationMode.UseNls);
Debug.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already");
char* buffer = stackalloc char[ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY];
bool result = Interop.Globalization.GetLocaleTimeFormat(_sWindowsName, shortFormat, buffer, ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
if (!result)
{
// Failed, just use empty string
Debug.Fail("[CultureData.GetTimeFormatString(bool shortFormat)] Failed");
return string.Empty;
}
var span = new ReadOnlySpan<char>(buffer, ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
return ConvertIcuTimeFormatString(span.Slice(0, span.IndexOf('\0')));
}
// no support to lookup by region name, other than the hard-coded list in CultureData
private static CultureData? IcuGetCultureDataFromRegionName() => null;
private string IcuGetLanguageDisplayName(string cultureName) => IcuGetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName, CultureInfo.CurrentUICulture.Name);
// use the fallback which is to return NativeName
private static string? IcuGetRegionDisplayName() => null;
internal static bool IcuIsEnsurePredefinedLocaleName(string name)
{
Debug.Assert(!GlobalizationMode.UseNls);
return Interop.Globalization.IsPredefinedLocale(name);
}
private static string ConvertIcuTimeFormatString(ReadOnlySpan<char> icuFormatString)
{
Debug.Assert(icuFormatString.Length < ICU_ULOC_FULLNAME_CAPACITY);
Span<char> result = stackalloc char[ICU_ULOC_FULLNAME_CAPACITY];
bool amPmAdded = false;
int resultPos = 0;
for (int i = 0; i < icuFormatString.Length; i++)
{
switch (icuFormatString[i])
{
case '\'':
result[resultPos++] = icuFormatString[i++];
while (i < icuFormatString.Length)
{
char current = icuFormatString[i];
result[resultPos++] = current;
if (current == '\'')
{
break;
}
i++;
}
break;
case ':':
case '.':
case 'H':
case 'h':
case 'm':
case 's':
result[resultPos++] = icuFormatString[i];
break;
case ' ':
case '\u00A0':
// Convert nonbreaking spaces into regular spaces
result[resultPos++] = ' ';
break;
case 'a': // AM/PM
if (!amPmAdded)
{
amPmAdded = true;
result[resultPos++] = 't';
result[resultPos++] = 't';
}
break;
}
}
return result.Slice(0, resultPos).ToString();
}
private static int IcuLocaleNameToLCID(string cultureName)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!GlobalizationMode.UseNls);
int lcid = IcuLocaleData.GetLocaleDataNumericPart(cultureName, IcuLocaleDataParts.Lcid);
return lcid == -1 ? CultureInfo.LOCALE_CUSTOM_UNSPECIFIED : lcid;
}
private static int IcuGetGeoId(string cultureName)
{
Debug.Assert(!GlobalizationMode.UseNls);
int geoId = IcuLocaleData.GetLocaleDataNumericPart(cultureName, IcuLocaleDataParts.GeoId);
return geoId == -1 ? CultureData.Invariant.GeoId : geoId;
}
private const uint DigitSubstitutionMask = 0x0000FFFF;
private const uint ListSeparatorMask = 0xFFFF0000;
private static int IcuGetDigitSubstitution(string cultureName)
{
Debug.Assert(!GlobalizationMode.UseNls);
int digitSubstitution = IcuLocaleData.GetLocaleDataNumericPart(cultureName, IcuLocaleDataParts.DigitSubstitutionOrListSeparator);
return digitSubstitution == -1 ? (int) DigitShapes.None : (int)(digitSubstitution & DigitSubstitutionMask);
}
private static string IcuGetListSeparator(string? cultureName)
{
Debug.Assert(!GlobalizationMode.UseNls);
Debug.Assert(cultureName != null);
int separator = IcuLocaleData.GetLocaleDataNumericPart(cultureName, IcuLocaleDataParts.DigitSubstitutionOrListSeparator);
if (separator != -1)
{
switch (separator & ListSeparatorMask)
{
case IcuLocaleData.CommaSep:
return ",";
case IcuLocaleData.SemicolonSep:
return ";";
case IcuLocaleData.ArabicCommaSep:
return "\u060C";
case IcuLocaleData.ArabicSemicolonSep:
return "\u061B";
case IcuLocaleData.DoubleCommaSep:
return ",,";
default:
Debug.Assert(false, "[CultureData.IcuGetListSeparator] Unexpected ListSeparator value.");
break;
}
}
return ","; // default separator
}
private static string IcuGetThreeLetterWindowsLanguageName(string cultureName)
{
Debug.Assert(!GlobalizationMode.UseNls);
return IcuLocaleData.GetThreeLetterWindowsLanguageName(cultureName) ?? "ZZZ" /* default lang name */;
}
private static CultureInfo[] IcuEnumCultures(CultureTypes types)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!GlobalizationMode.UseNls);
if ((types & (CultureTypes.NeutralCultures | CultureTypes.SpecificCultures)) == 0)
{
return Array.Empty<CultureInfo>();
}
int bufferLength = Interop.Globalization.GetLocales(null, 0);
if (bufferLength <= 0)
{
return Array.Empty<CultureInfo>();
}
char [] chars = new char[bufferLength];
bufferLength = Interop.Globalization.GetLocales(chars, bufferLength);
if (bufferLength <= 0)
{
return Array.Empty<CultureInfo>();
}
bool enumNeutrals = (types & CultureTypes.NeutralCultures) != 0;
bool enumSpecificss = (types & CultureTypes.SpecificCultures) != 0;
List<CultureInfo> list = new List<CultureInfo>();
if (enumNeutrals)
{
list.Add(CultureInfo.InvariantCulture);
}
int index = 0;
while (index < bufferLength)
{
int length = (int) chars[index++];
if (index + length <= bufferLength)
{
CultureInfo ci = CultureInfo.GetCultureInfo(new string(chars, index, length));
if ((enumNeutrals && ci.IsNeutralCulture) || (enumSpecificss && !ci.IsNeutralCulture))
{
list.Add(ci);
}
}
index += length;
}
return list.ToArray();
}
private static string IcuGetConsoleFallbackName(string cultureName)
{
Debug.Assert(!GlobalizationMode.UseNls);
return IcuLocaleData.GetConsoleUICulture(cultureName);
}
/// <summary>
/// Implementation of culture name validation.
/// </summary>
/// <remarks>
/// This is a fast approximate implementation based on BCP47 spec. It covers only parts of
/// the spec; such that, when it returns false, the input is definitely in incorrect format.
/// However, it returns true for some characters which are not allowed by the spec. It also
/// returns true for some inputs where spec specifies the lengths of subtags, but we are not
/// validating subtags individually to keep algorithm's computational complexity at O(n).
///
/// Rules of implementation:
/// * Allow only letters, digits, - and '_' or \0 (NULL is for backward compatibility).
/// * Allow input length of zero (for invariant culture) or otherwise greater than 1 and less than or equal LocaleNameMaxLength.
/// * Disallow input that starts or ends with '-' or '_'.
/// * Disallow input that has any combination of consecutive '-' or '_'.
/// * Disallow input that has multiple '_'.
/// </remarks>
private static bool IsValidCultureName(string subject, out int indexOfUnderscore)
{
indexOfUnderscore = -1;
if (subject.Length == 0) return true; // Invariant Culture
if (subject.Length == 1 || subject.Length > LocaleNameMaxLength) return false;
bool seenUnderscore = false;
for (int i = 0; i < subject.Length; ++i)
{
char c = subject[i];
if ((uint)(c - 'A') <= ('Z' - 'A') || (uint)(c - 'a') <= ('z' - 'a') || (uint)(c - '0') <= ('9' - '0') || c == '\0')
{
continue;
}
if (c == '_' || c == '-')
{
if (i == 0 || i == subject.Length - 1) return false;
if (subject[i - 1] == '_' || subject[i - 1] == '-') return false;
if (c == '_')
{
if (seenUnderscore) return false; // only one _ is allowed
seenUnderscore = true;
indexOfUnderscore = i;
}
}
else
{
return false;
}
}
return true;
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.IO.Pipes/ref/System.IO.Pipes.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ------------------------------------------------------------------------------
// Changes to this file must follow the https://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace Microsoft.Win32.SafeHandles
{
public sealed partial class SafePipeHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
{
public SafePipeHandle() : base (default(bool)) { }
public SafePipeHandle(System.IntPtr preexistingHandle, bool ownsHandle) : base (default(bool)) { }
public override bool IsInvalid { get { throw null; } }
protected override bool ReleaseHandle() { throw null; }
}
}
namespace System.IO.Pipes
{
public sealed partial class AnonymousPipeClientStream : System.IO.Pipes.PipeStream
{
public AnonymousPipeClientStream(System.IO.Pipes.PipeDirection direction, Microsoft.Win32.SafeHandles.SafePipeHandle safePipeHandle) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public AnonymousPipeClientStream(System.IO.Pipes.PipeDirection direction, string pipeHandleAsString) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public AnonymousPipeClientStream(string pipeHandleAsString) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public override System.IO.Pipes.PipeTransmissionMode ReadMode { set { } }
public override System.IO.Pipes.PipeTransmissionMode TransmissionMode { get { throw null; } }
~AnonymousPipeClientStream() { }
}
public sealed partial class AnonymousPipeServerStream : System.IO.Pipes.PipeStream
{
public AnonymousPipeServerStream() : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public AnonymousPipeServerStream(System.IO.Pipes.PipeDirection direction) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public AnonymousPipeServerStream(System.IO.Pipes.PipeDirection direction, Microsoft.Win32.SafeHandles.SafePipeHandle serverSafePipeHandle, Microsoft.Win32.SafeHandles.SafePipeHandle clientSafePipeHandle) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public AnonymousPipeServerStream(System.IO.Pipes.PipeDirection direction, System.IO.HandleInheritability inheritability) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public AnonymousPipeServerStream(System.IO.Pipes.PipeDirection direction, System.IO.HandleInheritability inheritability, int bufferSize) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public Microsoft.Win32.SafeHandles.SafePipeHandle ClientSafePipeHandle { get { throw null; } }
public override System.IO.Pipes.PipeTransmissionMode ReadMode { set { } }
public override System.IO.Pipes.PipeTransmissionMode TransmissionMode { get { throw null; } }
protected override void Dispose(bool disposing) { }
public void DisposeLocalCopyOfClientHandle() { }
~AnonymousPipeServerStream() { }
public string GetClientHandleAsString() { throw null; }
}
public sealed partial class NamedPipeClientStream : System.IO.Pipes.PipeStream
{
public NamedPipeClientStream(System.IO.Pipes.PipeDirection direction, bool isAsync, bool isConnected, Microsoft.Win32.SafeHandles.SafePipeHandle safePipeHandle) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeClientStream(string pipeName) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeClientStream(string serverName, string pipeName) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeClientStream(string serverName, string pipeName, System.IO.Pipes.PipeDirection direction) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeClientStream(string serverName, string pipeName, System.IO.Pipes.PipeDirection direction, System.IO.Pipes.PipeOptions options) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeClientStream(string serverName, string pipeName, System.IO.Pipes.PipeDirection direction, System.IO.Pipes.PipeOptions options, System.Security.Principal.TokenImpersonationLevel impersonationLevel) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeClientStream(string serverName, string pipeName, System.IO.Pipes.PipeDirection direction, System.IO.Pipes.PipeOptions options, System.Security.Principal.TokenImpersonationLevel impersonationLevel, System.IO.HandleInheritability inheritability) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public int NumberOfServerInstances { get { throw null; } }
protected internal override void CheckPipePropertyOperations() { }
public void Connect() { }
public void Connect(int timeout) { }
public System.Threading.Tasks.Task ConnectAsync() { throw null; }
public System.Threading.Tasks.Task ConnectAsync(int timeout) { throw null; }
public System.Threading.Tasks.Task ConnectAsync(int timeout, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task ConnectAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
~NamedPipeClientStream() { }
}
public sealed partial class NamedPipeServerStream : System.IO.Pipes.PipeStream
{
public const int MaxAllowedServerInstances = -1;
public NamedPipeServerStream(System.IO.Pipes.PipeDirection direction, bool isAsync, bool isConnected, Microsoft.Win32.SafeHandles.SafePipeHandle safePipeHandle) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeServerStream(string pipeName) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeServerStream(string pipeName, System.IO.Pipes.PipeDirection direction) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeServerStream(string pipeName, System.IO.Pipes.PipeDirection direction, int maxNumberOfServerInstances) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeServerStream(string pipeName, System.IO.Pipes.PipeDirection direction, int maxNumberOfServerInstances, System.IO.Pipes.PipeTransmissionMode transmissionMode) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeServerStream(string pipeName, System.IO.Pipes.PipeDirection direction, int maxNumberOfServerInstances, System.IO.Pipes.PipeTransmissionMode transmissionMode, System.IO.Pipes.PipeOptions options) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeServerStream(string pipeName, System.IO.Pipes.PipeDirection direction, int maxNumberOfServerInstances, System.IO.Pipes.PipeTransmissionMode transmissionMode, System.IO.Pipes.PipeOptions options, int inBufferSize, int outBufferSize) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public System.IAsyncResult BeginWaitForConnection(System.AsyncCallback? callback, object? state) { throw null; }
public void Disconnect() { }
public void EndWaitForConnection(System.IAsyncResult asyncResult) { }
~NamedPipeServerStream() { }
public string GetImpersonationUserName() { throw null; }
public void RunAsClient(System.IO.Pipes.PipeStreamImpersonationWorker impersonationWorker) { }
public void WaitForConnection() { }
public System.Threading.Tasks.Task WaitForConnectionAsync() { throw null; }
public System.Threading.Tasks.Task WaitForConnectionAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
}
public enum PipeDirection
{
In = 1,
Out = 2,
InOut = 3,
}
[System.FlagsAttribute]
public enum PipeOptions
{
WriteThrough = -2147483648,
None = 0,
CurrentUserOnly = 536870912,
Asynchronous = 1073741824,
}
public abstract partial class PipeStream : System.IO.Stream
{
protected PipeStream(System.IO.Pipes.PipeDirection direction, int bufferSize) { }
protected PipeStream(System.IO.Pipes.PipeDirection direction, System.IO.Pipes.PipeTransmissionMode transmissionMode, int outBufferSize) { }
public override bool CanRead { get { throw null; } }
public override bool CanSeek { get { throw null; } }
public override bool CanWrite { get { throw null; } }
public virtual int InBufferSize { get { throw null; } }
public bool IsAsync { get { throw null; } }
public bool IsConnected { get { throw null; } protected set { } }
protected bool IsHandleExposed { get { throw null; } }
public bool IsMessageComplete { get { throw null; } }
public override long Length { get { throw null; } }
public virtual int OutBufferSize { get { throw null; } }
public override long Position { get { throw null; } set { } }
public virtual System.IO.Pipes.PipeTransmissionMode ReadMode { get { throw null; } set { } }
public Microsoft.Win32.SafeHandles.SafePipeHandle SafePipeHandle { get { throw null; } }
public virtual System.IO.Pipes.PipeTransmissionMode TransmissionMode { get { throw null; } }
public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback? callback, object? state) { throw null; }
public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback? callback, object? state) { throw null; }
protected internal virtual void CheckPipePropertyOperations() { }
protected internal void CheckReadOperations() { }
protected internal void CheckWriteOperations() { }
protected override void Dispose(bool disposing) { }
public override int EndRead(System.IAsyncResult asyncResult) { throw null; }
public override void EndWrite(System.IAsyncResult asyncResult) { }
public override void Flush() { }
public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
protected void InitializeHandle(Microsoft.Win32.SafeHandles.SafePipeHandle? handle, bool isExposed, bool isAsync) { }
public override int Read(byte[] buffer, int offset, int count) { throw null; }
public override int Read(System.Span<byte> buffer) { throw null; }
public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; }
public override System.Threading.Tasks.ValueTask<int> ReadAsync(System.Memory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override int ReadByte() { throw null; }
public override long Seek(long offset, System.IO.SeekOrigin origin) { throw null; }
public override void SetLength(long value) { }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public void WaitForPipeDrain() { }
public override void Write(byte[] buffer, int offset, int count) { }
public override void Write(System.ReadOnlySpan<byte> buffer) { }
public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; }
public override System.Threading.Tasks.ValueTask WriteAsync(System.ReadOnlyMemory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override void WriteByte(byte value) { }
}
public delegate void PipeStreamImpersonationWorker();
public enum PipeTransmissionMode
{
Byte = 0,
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
Message = 1,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ------------------------------------------------------------------------------
// Changes to this file must follow the https://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace Microsoft.Win32.SafeHandles
{
public sealed partial class SafePipeHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
{
public SafePipeHandle() : base (default(bool)) { }
public SafePipeHandle(System.IntPtr preexistingHandle, bool ownsHandle) : base (default(bool)) { }
public override bool IsInvalid { get { throw null; } }
protected override bool ReleaseHandle() { throw null; }
}
}
namespace System.IO.Pipes
{
public sealed partial class AnonymousPipeClientStream : System.IO.Pipes.PipeStream
{
public AnonymousPipeClientStream(System.IO.Pipes.PipeDirection direction, Microsoft.Win32.SafeHandles.SafePipeHandle safePipeHandle) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public AnonymousPipeClientStream(System.IO.Pipes.PipeDirection direction, string pipeHandleAsString) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public AnonymousPipeClientStream(string pipeHandleAsString) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public override System.IO.Pipes.PipeTransmissionMode ReadMode { set { } }
public override System.IO.Pipes.PipeTransmissionMode TransmissionMode { get { throw null; } }
~AnonymousPipeClientStream() { }
}
public sealed partial class AnonymousPipeServerStream : System.IO.Pipes.PipeStream
{
public AnonymousPipeServerStream() : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public AnonymousPipeServerStream(System.IO.Pipes.PipeDirection direction) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public AnonymousPipeServerStream(System.IO.Pipes.PipeDirection direction, Microsoft.Win32.SafeHandles.SafePipeHandle serverSafePipeHandle, Microsoft.Win32.SafeHandles.SafePipeHandle clientSafePipeHandle) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public AnonymousPipeServerStream(System.IO.Pipes.PipeDirection direction, System.IO.HandleInheritability inheritability) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public AnonymousPipeServerStream(System.IO.Pipes.PipeDirection direction, System.IO.HandleInheritability inheritability, int bufferSize) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public Microsoft.Win32.SafeHandles.SafePipeHandle ClientSafePipeHandle { get { throw null; } }
public override System.IO.Pipes.PipeTransmissionMode ReadMode { set { } }
public override System.IO.Pipes.PipeTransmissionMode TransmissionMode { get { throw null; } }
protected override void Dispose(bool disposing) { }
public void DisposeLocalCopyOfClientHandle() { }
~AnonymousPipeServerStream() { }
public string GetClientHandleAsString() { throw null; }
}
public sealed partial class NamedPipeClientStream : System.IO.Pipes.PipeStream
{
public NamedPipeClientStream(System.IO.Pipes.PipeDirection direction, bool isAsync, bool isConnected, Microsoft.Win32.SafeHandles.SafePipeHandle safePipeHandle) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeClientStream(string pipeName) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeClientStream(string serverName, string pipeName) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeClientStream(string serverName, string pipeName, System.IO.Pipes.PipeDirection direction) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeClientStream(string serverName, string pipeName, System.IO.Pipes.PipeDirection direction, System.IO.Pipes.PipeOptions options) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeClientStream(string serverName, string pipeName, System.IO.Pipes.PipeDirection direction, System.IO.Pipes.PipeOptions options, System.Security.Principal.TokenImpersonationLevel impersonationLevel) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeClientStream(string serverName, string pipeName, System.IO.Pipes.PipeDirection direction, System.IO.Pipes.PipeOptions options, System.Security.Principal.TokenImpersonationLevel impersonationLevel, System.IO.HandleInheritability inheritability) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public int NumberOfServerInstances { get { throw null; } }
protected internal override void CheckPipePropertyOperations() { }
public void Connect() { }
public void Connect(int timeout) { }
public System.Threading.Tasks.Task ConnectAsync() { throw null; }
public System.Threading.Tasks.Task ConnectAsync(int timeout) { throw null; }
public System.Threading.Tasks.Task ConnectAsync(int timeout, System.Threading.CancellationToken cancellationToken) { throw null; }
public System.Threading.Tasks.Task ConnectAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
~NamedPipeClientStream() { }
}
public sealed partial class NamedPipeServerStream : System.IO.Pipes.PipeStream
{
public const int MaxAllowedServerInstances = -1;
public NamedPipeServerStream(System.IO.Pipes.PipeDirection direction, bool isAsync, bool isConnected, Microsoft.Win32.SafeHandles.SafePipeHandle safePipeHandle) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeServerStream(string pipeName) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeServerStream(string pipeName, System.IO.Pipes.PipeDirection direction) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeServerStream(string pipeName, System.IO.Pipes.PipeDirection direction, int maxNumberOfServerInstances) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeServerStream(string pipeName, System.IO.Pipes.PipeDirection direction, int maxNumberOfServerInstances, System.IO.Pipes.PipeTransmissionMode transmissionMode) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeServerStream(string pipeName, System.IO.Pipes.PipeDirection direction, int maxNumberOfServerInstances, System.IO.Pipes.PipeTransmissionMode transmissionMode, System.IO.Pipes.PipeOptions options) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public NamedPipeServerStream(string pipeName, System.IO.Pipes.PipeDirection direction, int maxNumberOfServerInstances, System.IO.Pipes.PipeTransmissionMode transmissionMode, System.IO.Pipes.PipeOptions options, int inBufferSize, int outBufferSize) : base (default(System.IO.Pipes.PipeDirection), default(int)) { }
public System.IAsyncResult BeginWaitForConnection(System.AsyncCallback? callback, object? state) { throw null; }
public void Disconnect() { }
public void EndWaitForConnection(System.IAsyncResult asyncResult) { }
~NamedPipeServerStream() { }
public string GetImpersonationUserName() { throw null; }
public void RunAsClient(System.IO.Pipes.PipeStreamImpersonationWorker impersonationWorker) { }
public void WaitForConnection() { }
public System.Threading.Tasks.Task WaitForConnectionAsync() { throw null; }
public System.Threading.Tasks.Task WaitForConnectionAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
}
public enum PipeDirection
{
In = 1,
Out = 2,
InOut = 3,
}
[System.FlagsAttribute]
public enum PipeOptions
{
WriteThrough = -2147483648,
None = 0,
CurrentUserOnly = 536870912,
Asynchronous = 1073741824,
}
public abstract partial class PipeStream : System.IO.Stream
{
protected PipeStream(System.IO.Pipes.PipeDirection direction, int bufferSize) { }
protected PipeStream(System.IO.Pipes.PipeDirection direction, System.IO.Pipes.PipeTransmissionMode transmissionMode, int outBufferSize) { }
public override bool CanRead { get { throw null; } }
public override bool CanSeek { get { throw null; } }
public override bool CanWrite { get { throw null; } }
public virtual int InBufferSize { get { throw null; } }
public bool IsAsync { get { throw null; } }
public bool IsConnected { get { throw null; } protected set { } }
protected bool IsHandleExposed { get { throw null; } }
public bool IsMessageComplete { get { throw null; } }
public override long Length { get { throw null; } }
public virtual int OutBufferSize { get { throw null; } }
public override long Position { get { throw null; } set { } }
public virtual System.IO.Pipes.PipeTransmissionMode ReadMode { get { throw null; } set { } }
public Microsoft.Win32.SafeHandles.SafePipeHandle SafePipeHandle { get { throw null; } }
public virtual System.IO.Pipes.PipeTransmissionMode TransmissionMode { get { throw null; } }
public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback? callback, object? state) { throw null; }
public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback? callback, object? state) { throw null; }
protected internal virtual void CheckPipePropertyOperations() { }
protected internal void CheckReadOperations() { }
protected internal void CheckWriteOperations() { }
protected override void Dispose(bool disposing) { }
public override int EndRead(System.IAsyncResult asyncResult) { throw null; }
public override void EndWrite(System.IAsyncResult asyncResult) { }
public override void Flush() { }
public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { throw null; }
protected void InitializeHandle(Microsoft.Win32.SafeHandles.SafePipeHandle? handle, bool isExposed, bool isAsync) { }
public override int Read(byte[] buffer, int offset, int count) { throw null; }
public override int Read(System.Span<byte> buffer) { throw null; }
public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; }
public override System.Threading.Tasks.ValueTask<int> ReadAsync(System.Memory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override int ReadByte() { throw null; }
public override long Seek(long offset, System.IO.SeekOrigin origin) { throw null; }
public override void SetLength(long value) { }
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
public void WaitForPipeDrain() { }
public override void Write(byte[] buffer, int offset, int count) { }
public override void Write(System.ReadOnlySpan<byte> buffer) { }
public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; }
public override System.Threading.Tasks.ValueTask WriteAsync(System.ReadOnlyMemory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public override void WriteByte(byte value) { }
}
public delegate void PipeStreamImpersonationWorker();
public enum PipeTransmissionMode
{
Byte = 0,
[System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")]
Message = 1,
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/OrNot.Vector128.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.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 OrNot_Vector128_Byte()
{
var test = new SimpleBinaryOpTest__OrNot_Vector128_Byte();
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__OrNot_Vector128_Byte
{
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(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
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<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, 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<Byte> _fld1;
public Vector128<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__OrNot_Vector128_Byte testClass)
{
var result = AdvSimd.OrNot(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__OrNot_Vector128_Byte testClass)
{
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = AdvSimd.OrNot(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(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<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__OrNot_Vector128_Byte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public SimpleBinaryOpTest__OrNot_Vector128_Byte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, new Byte[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.OrNot(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_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.OrNot(
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Byte*)(_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.OrNot), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(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.OrNot), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.OrNot(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector128<Byte>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.OrNot(
AdvSimd.LoadVector128((Byte*)(pClsVar1)),
AdvSimd.LoadVector128((Byte*)(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<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = AdvSimd.OrNot(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((Byte*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = AdvSimd.OrNot(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__OrNot_Vector128_Byte();
var result = AdvSimd.OrNot(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__OrNot_Vector128_Byte();
fixed (Vector128<Byte>* pFld1 = &test._fld1)
fixed (Vector128<Byte>* pFld2 = &test._fld2)
{
var result = AdvSimd.OrNot(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.OrNot(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = AdvSimd.OrNot(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(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.OrNot(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.OrNot(
AdvSimd.LoadVector128((Byte*)(&test._fld1)),
AdvSimd.LoadVector128((Byte*)(&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<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (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(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.OrNot(left[i], right[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.OrNot)}<Byte>(Vector128<Byte>, Vector128<Byte>): {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 OrNot_Vector128_Byte()
{
var test = new SimpleBinaryOpTest__OrNot_Vector128_Byte();
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__OrNot_Vector128_Byte
{
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(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
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<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, 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<Byte> _fld1;
public Vector128<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__OrNot_Vector128_Byte testClass)
{
var result = AdvSimd.OrNot(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__OrNot_Vector128_Byte testClass)
{
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = AdvSimd.OrNot(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(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<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__OrNot_Vector128_Byte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public SimpleBinaryOpTest__OrNot_Vector128_Byte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, new Byte[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.OrNot(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_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.OrNot(
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Byte*)(_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.OrNot), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(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.OrNot), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.OrNot(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector128<Byte>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.OrNot(
AdvSimd.LoadVector128((Byte*)(pClsVar1)),
AdvSimd.LoadVector128((Byte*)(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<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = AdvSimd.OrNot(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((Byte*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = AdvSimd.OrNot(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__OrNot_Vector128_Byte();
var result = AdvSimd.OrNot(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__OrNot_Vector128_Byte();
fixed (Vector128<Byte>* pFld1 = &test._fld1)
fixed (Vector128<Byte>* pFld2 = &test._fld2)
{
var result = AdvSimd.OrNot(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.OrNot(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = AdvSimd.OrNot(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(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.OrNot(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.OrNot(
AdvSimd.LoadVector128((Byte*)(&test._fld1)),
AdvSimd.LoadVector128((Byte*)(&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<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (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(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.OrNot(left[i], right[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.OrNot)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/CodeGenBringUpTests/LocallocB_N.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
using System.Runtime.CompilerServices;
public class BringUpTest_LocallocB_N
{
const int Pass = 100;
const int Fail = -1;
// Reduce all values to byte
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static unsafe bool CHECK(byte check, byte expected) {
return check == expected;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static unsafe int LocallocB_N(int n)
{
byte* a = stackalloc byte[n];
for (int i = 0; i < n; i++)
{
a[i] = (byte) i;
}
for (int i = 0; i < n; i++)
{
if (!CHECK(a[i], (byte) i)) return i;
}
return -1;
}
public static int Main()
{
int ret;
ret = LocallocB_N(1);
if (ret != -1) {
Console.WriteLine("LocallocB_N - Test 1: Failed on index: " + ret);
return Fail;
}
ret = LocallocB_N(5);
if (ret != -1) {
Console.WriteLine("LocallocB_N - Test 2: Failed on index: " + ret);
return Fail;
}
ret = LocallocB_N(117);
if (ret != -1) {
Console.WriteLine("LocallocB_N - Test 3: Failed on index: " + ret);
return Fail;
}
ret = LocallocB_N(5001);
if (ret != -1) {
Console.WriteLine("LocallocB_N - Test 4: Failed on index: " + ret);
return Fail;
}
return Pass;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
using System.Runtime.CompilerServices;
public class BringUpTest_LocallocB_N
{
const int Pass = 100;
const int Fail = -1;
// Reduce all values to byte
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static unsafe bool CHECK(byte check, byte expected) {
return check == expected;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static unsafe int LocallocB_N(int n)
{
byte* a = stackalloc byte[n];
for (int i = 0; i < n; i++)
{
a[i] = (byte) i;
}
for (int i = 0; i < n; i++)
{
if (!CHECK(a[i], (byte) i)) return i;
}
return -1;
}
public static int Main()
{
int ret;
ret = LocallocB_N(1);
if (ret != -1) {
Console.WriteLine("LocallocB_N - Test 1: Failed on index: " + ret);
return Fail;
}
ret = LocallocB_N(5);
if (ret != -1) {
Console.WriteLine("LocallocB_N - Test 2: Failed on index: " + ret);
return Fail;
}
ret = LocallocB_N(117);
if (ret != -1) {
Console.WriteLine("LocallocB_N - Test 3: Failed on index: " + ret);
return Fail;
}
ret = LocallocB_N(5001);
if (ret != -1) {
Console.WriteLine("LocallocB_N - Test 4: Failed on index: " + ret);
return Fail;
}
return Pass;
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/ComEventsHelperTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Xunit;
namespace System.Runtime.InteropServices.Tests
{
public class ComEventsHelperTests
{
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void Combine_Unix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => ComEventsHelper.Combine(null, Guid.Empty, 1, null));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Combine_NullRcw_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>(null, () => ComEventsHelper.Combine(null, Guid.Empty, 1, null));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Combine_NotComObject_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("obj", () => ComEventsHelper.Combine(1, Guid.Empty, 1, null));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void Remove_Unix_ThrowPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => ComEventsHelper.Remove(null, Guid.Empty, 1, null));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Remove_NullRcw_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>(null, () => ComEventsHelper.Remove(null, Guid.Empty, 1, null));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Remove_NotComObject_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("obj", () => ComEventsHelper.Remove(1, Guid.Empty, 1, 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.Runtime.InteropServices.Tests
{
public class ComEventsHelperTests
{
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void Combine_Unix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => ComEventsHelper.Combine(null, Guid.Empty, 1, null));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Combine_NullRcw_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>(null, () => ComEventsHelper.Combine(null, Guid.Empty, 1, null));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Combine_NotComObject_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("obj", () => ComEventsHelper.Combine(1, Guid.Empty, 1, null));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void Remove_Unix_ThrowPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => ComEventsHelper.Remove(null, Guid.Empty, 1, null));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Remove_NullRcw_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>(null, () => ComEventsHelper.Remove(null, Guid.Empty, 1, null));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void Remove_NotComObject_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("obj", () => ComEventsHelper.Remove(1, Guid.Empty, 1, null));
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Reflection.MetadataLoadContext/tests/src/Tests/TypeInfoFromProjectN/TypeInfo_MethodTests.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;
#pragma warning disable 0067 // Unused event
namespace System.Reflection.Tests
{
public class TypeInfoMethodTests
{
// Verify AsType() method
[Fact]
public static void TestAsType1()
{
Type runtimeType = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = runtimeType.GetTypeInfo();
Type type = typeInfo.AsType();
Assert.Equal(runtimeType, type);
}
// Verify AsType() method
[Fact]
public static void TestAsType2()
{
Type runtimeType = typeof(MethodPublicClass.PublicNestedType).Project();
TypeInfo typeInfo = runtimeType.GetTypeInfo();
Type type = typeInfo.AsType();
Assert.Equal(runtimeType, type);
}
// Verify GetArrayRank() method
[Fact]
public static void TestGetArrayRank1()
{
int[] myArray = { 1, 2, 3, 4, 5, 6, 7 };
int expectedRank = 1;
Type type = myArray.GetType();
TypeInfo typeInfo = type.GetTypeInfo();
int rank = typeInfo.GetArrayRank();
Assert.Equal(expectedRank, rank);
}
// Verify GetArrayRank() method
[Fact]
public static void TestGetArrayRank2()
{
string[] myArray = { "hello" };
int expectedRank = 1;
Type type = myArray.GetType();
TypeInfo typeInfo = type.GetTypeInfo();
int rank = typeInfo.GetArrayRank();
Assert.Equal(expectedRank, rank);
}
// Verify GetDeclaredEvent() method
[Fact]
public static void TestGetDeclaredEvent1()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredEvent(typeInfo, "EventPublic");
}
// Verify GetDeclaredEvent() method
[Fact]
public static void TestGetDeclaredEvent2()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
EventInfo ei = typeInfo.GetDeclaredEvent("NoSuchEvent");
Assert.Null(ei);
}
// Verify GetDeclaredEvent() method
[Fact]
public static void TestGetDeclaredEvent3()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
Assert.Throws<ArgumentNullException>(() => { EventInfo ei = typeInfo.GetDeclaredEvent(null); });
}
// Verify GetDeclaredField() method
[Fact]
public static void TestGetDeclaredField1()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredField(typeInfo, "PublicField");
}
// Verify GetDeclaredField() method
[Fact]
public static void TestGetDeclaredField2()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredField(typeInfo, "PublicStaticField");
}
// Verify GetDeclaredField() method
[Fact]
public static void TestGetDeclaredField3()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
FieldInfo fi = typeInfo.GetDeclaredField("NoSuchField");
Assert.Null(fi);
}
// Verify GetDeclaredField() method
[Fact]
public static void TestGetDeclaredField4()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
Assert.Throws<ArgumentNullException>(() => { FieldInfo fi = typeInfo.GetDeclaredField(null); });
}
// Verify GetDeclaredMethod() method
[Fact]
public static void TestGetDeclaredMethod1()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredMethod(typeInfo, "PublicMethod");
}
// Verify GetDeclaredMethod() method
[Fact]
public static void TestGetDeclaredMethod2()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredMethod(typeInfo, "PublicStaticMethod");
}
// Verify GetDeclaredMethod() method
[Fact]
public static void TestGetDeclaredMethod3()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
MethodInfo mi = typeInfo.GetDeclaredMethod("NoSuchMethod");
Assert.Null(mi);
}
// Verify GetDeclaredMethod() method
[Fact]
public static void TestGetDeclaredMethod4()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
Assert.Throws<ArgumentNullException>(() => { MethodInfo mi = typeInfo.GetDeclaredMethod(null); });
}
// Verify GetDeclaredMethods() method
[Fact]
public static void TestGetDeclaredMethods1()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredMethods(typeInfo, "overRiddenMethod", 4);
}
// Verify GetDeclaredMethods() method
[Fact]
public static void TestGetDeclaredMethods2()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredMethods(typeInfo, "NoSuchMethod", 0);
}
// Verify GetDeclaredNestedType() method
[Fact]
public static void TestGetDeclaredNestedType1()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredNestedType(typeInfo, "PublicNestedType");
}
// Verify GetDeclaredNestedType() method
[Fact]
public static void TestGetDeclaredNestedType2()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
TypeInfo nested_ti = typeInfo.GetDeclaredNestedType("NoSuchType");
Assert.Null(nested_ti);
}
// Verify GetDeclaredNestedType() method
[Fact]
public static void TestGetDeclaredNestedType3()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
Assert.Throws<ArgumentNullException>(() => { TypeInfo nested_ti = typeInfo.GetDeclaredNestedType(null); });
}
// Verify GetElementType() method
[Fact]
public static void TestGetElementType1()
{
Type runtimeType = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = runtimeType.GetTypeInfo();
Type type = typeInfo.GetElementType();
Assert.Null(type);
}
// Verify GetElementType() method
[Fact]
public static void TestGetElementType2()
{
string[] myArray = { "a", "b", "c" };
Type runtimeType = myArray.GetType();
TypeInfo typeInfo = runtimeType.GetTypeInfo();
Type type = typeInfo.GetElementType();
Assert.NotNull(type);
Assert.Equal(typeof(string).Project().Name, type.Name);
}
// Verify GetElementType() method
[Fact]
public static void TestGetElementType3()
{
int[] myArray = { 1, 2, 3, 4 };
Type runtimeType = myArray.GetType();
TypeInfo typeInfo = runtimeType.GetTypeInfo();
Type type = typeInfo.GetElementType();
Assert.NotNull(type);
Assert.Equal(typeof(int).Project().Name, type.Name);
}
// Verify GetGenericParameterConstraints() method
[Fact]
public static void TestGetGenericParameterConstraints1()
{
Type def = typeof(TypeInfoMethodClassWithConstraints<,>).Project();
TypeInfo ti = def.GetTypeInfo();
Type[] defparams = ti.GenericTypeParameters;
Assert.Equal(2, defparams.Length);
Type[] tpConstraints = defparams[0].GetTypeInfo().GetGenericParameterConstraints();
Assert.Equal(2, tpConstraints.Length);
Assert.Equal(typeof(TypeInfoMethodBase).Project(), tpConstraints[0]);
Assert.Equal(typeof(MethodITest).Project(), tpConstraints[1]);
}
// Verify GetGenericParameterConstraints() method
[Fact]
public static void TestGetGenericParameterConstraints2()
{
Type def = typeof(TypeInfoMethodClassWithConstraints<,>).Project();
TypeInfo ti = def.GetTypeInfo();
Type[] defparams = ti.GenericTypeParameters;
Assert.Equal(2, defparams.Length);
Type[] tpConstraints = defparams[1].GetTypeInfo().GetGenericParameterConstraints();
Assert.Equal(0, tpConstraints.Length);
}
// Verify GetGenericTypeDefinition() method
[Fact]
public static void TestGetGenericTypeDefinition()
{
TypeInfoMethodGenericClass<int> genericObj = new TypeInfoMethodGenericClass<int>();
Type type = genericObj.GetType().Project();
Type generictype = type.GetTypeInfo().GetGenericTypeDefinition();
Assert.NotNull(generictype);
Assert.Equal(typeof(TypeInfoMethodGenericClass<>).Project(), generictype);
}
// Verify IsSubClassOf() method
[Fact]
public static void TestIsSubClassOf1()
{
TypeInfo t1 = typeof(TypeInfoMethodBase).Project().GetTypeInfo();
TypeInfo t2 = typeof(TypeInfoMethodDerived).Project().GetTypeInfo();
bool isSubClass = t1.IsSubclassOf(t2.AsType());
Assert.False(isSubClass);
}
// Verify IsSubClassOf() method
[Fact]
public static void TestIsSubClassOf2()
{
TypeInfo t1 = typeof(TypeInfoMethodBase).Project().GetTypeInfo();
TypeInfo t2 = typeof(TypeInfoMethodDerived).Project().GetTypeInfo();
bool isSubClass = t2.IsSubclassOf(t1.AsType());
Assert.True(isSubClass, "Failed! isSubClass returned False when this class derives from input class ");
}
// Verify IsAssignableFrom() method
[Fact]
public static void TestIsAssignableFrom1()
{
TypeInfo t1 = typeof(TypeInfoMethodBase).Project().GetTypeInfo();
TypeInfo t2 = typeof(TypeInfoMethodDerived).Project().GetTypeInfo();
bool isAssignable = t1.IsAssignableFrom(t2);
Assert.True(isAssignable, "Failed! IsAssignableFrom returned False");
}
// Verify IsAssignableFrom() method
[Fact]
public static void TestIsAssignableFrom2()
{
TypeInfo t1 = typeof(TypeInfoMethodBase).Project().GetTypeInfo();
TypeInfo t2 = typeof(TypeInfoMethodDerived).Project().GetTypeInfo();
bool isAssignable = t2.IsAssignableFrom(t1);
Assert.False(isAssignable, "Failed! IsAssignableFrom returned True");
}
// Verify IsAssignableFrom() method
[Fact]
public static void TestIsAssignableFrom3()
{
TypeInfo t1 = typeof(TypeInfoMethodBase).Project().GetTypeInfo();
TypeInfo t2 = typeof(TypeInfoMethodBase).Project().GetTypeInfo();
bool isAssignable = t2.IsAssignableFrom(t2);
Assert.True(isAssignable, "Failed! IsAssignableFrom returned False for same Type");
}
// Verify IsAssignableFrom() method
[Fact]
public static void TestIsAssignableFrom4()
{
TypeInfo t1 = typeof(MethodITest).Project().GetTypeInfo();
TypeInfo t2 = typeof(TypeInfoMethodImplClass).Project().GetTypeInfo();
bool isAssignable = t1.IsAssignableFrom(t2);
Assert.True(isAssignable, "Failed! IsAssignableFrom returned False");
}
// Verify MakeArrayType() method
[Fact]
public static void TestMakeArrayType1()
{
TypeInfo ti = typeof(string).Project().GetTypeInfo();
Type arraytype = ti.MakeArrayType();
string[] strArray = { "a", "b", "c" };
Assert.NotNull(arraytype);
Assert.Equal(strArray.GetType().Project(), arraytype);
}
// Verify MakeArrayType() method
[Fact]
public static void TestMakeArrayType2()
{
TypeInfo ti = typeof(int).Project().GetTypeInfo();
Type arraytype = ti.MakeArrayType();
int[] intArray = { 1, 2, 3 };
Assert.NotNull(arraytype);
Assert.Equal(intArray.GetType().Project(), arraytype);
}
// Verify MakeArrayType(int rank) method
[Fact]
public static void TestMakeArrayTypeWithRank1()
{
TypeInfo ti = typeof(string).Project().GetTypeInfo();
Type arraytype = ti.MakeArrayType(1);
Assert.NotNull(arraytype);
Assert.True(arraytype.IsArray, "Failed!! MakeArrayType() returned type that is not Array");
}
// Verify MakeArrayType(int rank) method
[Fact]
public static void TestMakeArrayTypeWithRank2()
{
GC.KeepAlive(typeof(int[,]).Project());
TypeInfo ti = typeof(int).Project().GetTypeInfo();
Type arraytype = ti.MakeArrayType(2);
Assert.NotNull(arraytype);
Assert.True(arraytype.IsArray, "Failed!! MakeArrayType() returned type that is not Array");
}
// Verify MakeArrayType() method
[Fact]
public static void TestMakeArrayOfPointerType1()
{
TypeInfo ti = typeof(char*).Project().GetTypeInfo();
Type arraytype = ti.MakeArrayType(3);
Assert.NotNull(arraytype);
Assert.True(arraytype.IsArray);
Assert.Equal(3, arraytype.GetArrayRank());
Assert.Equal(arraytype.GetElementType(), typeof(char*).Project());
}
// Verify MakeArrayType(int rank) method
[Fact]
public static void TestMakeArrayTypeWithRank3()
{
GC.KeepAlive(typeof(int[,,]).Project());
TypeInfo ti = typeof(int).Project().GetTypeInfo();
Type arraytype = ti.MakeArrayType(3);
Assert.NotNull(arraytype);
Assert.True(arraytype.IsArray, "Failed!! MakeArrayType() returned type that is not Array");
}
// Verify MakeByRefType method
[Fact]
public static void TestMakeByRefType1()
{
TypeInfo ti = typeof(int).Project().GetTypeInfo();
Type byreftype = ti.MakeByRefType();
Assert.NotNull(byreftype);
Assert.True(byreftype.IsByRef, "Failed!! MakeByRefType() returned type that is not ByRef");
}
// Verify MakeByRefType method
[Fact]
public static void TestMakeByRefType2()
{
TypeInfo ti = typeof(string).Project().GetTypeInfo();
Type byreftype = ti.MakeByRefType();
Assert.NotNull(byreftype);
Assert.True(byreftype.IsByRef, "Failed!! MakeByRefType() returned type that is not ByRef");
}
// Verify MakePointerType method
[Fact]
public static void TestMakePointerType1()
{
TypeInfo ti = typeof(int).Project().GetTypeInfo();
Type ptrtype = ti.MakePointerType();
Assert.NotNull(ptrtype);
Assert.True(ptrtype.IsPointer, "Failed!! MakePointerType() returned type that is not Pointer");
}
// Verify MakePointerType method
[Fact]
public static void TestMakePointerType2()
{
TypeInfo ti = typeof(string).Project().GetTypeInfo();
Type ptrtype = ti.MakePointerType();
Assert.NotNull(ptrtype);
Assert.True(ptrtype.IsPointer, "Failed!! MakePointerType() returned type that is not Pointer");
}
// Verify MakeGenericType() method
[Fact]
public static void TestMakeGenericType()
{
Type type = typeof(List<>).Project();
Type[] typeArgs = { typeof(string).Project() };
TypeInfo typeInfo = type.GetTypeInfo();
Type generictype = typeInfo.MakeGenericType(typeArgs);
Assert.NotNull(generictype);
Assert.True(generictype.GetTypeInfo().IsGenericType, "Failed!! MakeGenericType() returned type that is not generic");
}
// Verify ToString() method
[Fact]
public static void TestToString1()
{
Type type = typeof(string).Project();
TypeInfo typeInfo = type.GetTypeInfo();
Assert.Equal("System.String", typeInfo.ToString());
}
// Verify ToString() method
[Fact]
public static void TestToString2()
{
Type type = typeof(int).Project();
TypeInfo typeInfo = type.GetTypeInfo();
Assert.Equal("System.Int32", typeInfo.ToString());
}
//Private Helper Methods
private static void VerifyGetDeclaredEvent(TypeInfo ti, string eventName)
{
EventInfo ei = ti.GetDeclaredEvent(eventName);
Assert.NotNull(ei);
Assert.Equal(eventName, ei.Name);
}
private static void VerifyGetDeclaredField(TypeInfo ti, string fieldName)
{
FieldInfo fi = ti.GetDeclaredField(fieldName);
Assert.NotNull(fi);
Assert.Equal(fieldName, fi.Name);
}
private static void VerifyGetDeclaredMethod(TypeInfo ti, string methodName)
{
MethodInfo mi = ti.GetDeclaredMethod(methodName);
Assert.NotNull(mi);
Assert.Equal(methodName, mi.Name);
}
private static void VerifyGetDeclaredMethods(TypeInfo ti, string methodName, int count)
{
IEnumerator<MethodInfo> alldefinedMethods = ti.GetDeclaredMethods(methodName).GetEnumerator();
MethodInfo mi = null;
int numMethods = 0;
while (alldefinedMethods.MoveNext())
{
mi = alldefinedMethods.Current;
Assert.Equal(methodName, mi.Name);
numMethods++;
}
Assert.Equal(count, numMethods);
}
private static void VerifyGetDeclaredNestedType(TypeInfo ti, string name)
{
TypeInfo nested_ti = ti.GetDeclaredNestedType(name);
Assert.NotNull(nested_ti);
Assert.Equal(name, nested_ti.Name);
}
private static void VerifyGetDeclaredProperty(TypeInfo ti, string name)
{
PropertyInfo pi = ti.GetDeclaredProperty(name);
Assert.NotNull(pi);
Assert.Equal(name, pi.Name);
}
}
//Metadata for Reflection
public class MethodPublicClass
{
public int PublicField;
public static int PublicStaticField;
public MethodPublicClass() { }
public void PublicMethod() { }
public void overRiddenMethod() { }
public void overRiddenMethod(int i) { }
public void overRiddenMethod(string s) { }
public void overRiddenMethod(object o) { }
public static void PublicStaticMethod() { }
public class PublicNestedType { }
public int PublicProperty { get { return default(int); } set { } }
public event System.EventHandler EventPublic;
}
public interface MethodITest { }
public class TypeInfoMethodBase { }
public class TypeInfoMethodDerived : TypeInfoMethodBase { }
public class TypeInfoMethodImplClass : MethodITest { }
public class TypeInfoMethodGenericClass<T> { }
public class TypeInfoMethodClassWithConstraints<T, U>
where T : TypeInfoMethodBase, MethodITest
where U : class, new()
{ }
}
| // 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;
#pragma warning disable 0067 // Unused event
namespace System.Reflection.Tests
{
public class TypeInfoMethodTests
{
// Verify AsType() method
[Fact]
public static void TestAsType1()
{
Type runtimeType = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = runtimeType.GetTypeInfo();
Type type = typeInfo.AsType();
Assert.Equal(runtimeType, type);
}
// Verify AsType() method
[Fact]
public static void TestAsType2()
{
Type runtimeType = typeof(MethodPublicClass.PublicNestedType).Project();
TypeInfo typeInfo = runtimeType.GetTypeInfo();
Type type = typeInfo.AsType();
Assert.Equal(runtimeType, type);
}
// Verify GetArrayRank() method
[Fact]
public static void TestGetArrayRank1()
{
int[] myArray = { 1, 2, 3, 4, 5, 6, 7 };
int expectedRank = 1;
Type type = myArray.GetType();
TypeInfo typeInfo = type.GetTypeInfo();
int rank = typeInfo.GetArrayRank();
Assert.Equal(expectedRank, rank);
}
// Verify GetArrayRank() method
[Fact]
public static void TestGetArrayRank2()
{
string[] myArray = { "hello" };
int expectedRank = 1;
Type type = myArray.GetType();
TypeInfo typeInfo = type.GetTypeInfo();
int rank = typeInfo.GetArrayRank();
Assert.Equal(expectedRank, rank);
}
// Verify GetDeclaredEvent() method
[Fact]
public static void TestGetDeclaredEvent1()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredEvent(typeInfo, "EventPublic");
}
// Verify GetDeclaredEvent() method
[Fact]
public static void TestGetDeclaredEvent2()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
EventInfo ei = typeInfo.GetDeclaredEvent("NoSuchEvent");
Assert.Null(ei);
}
// Verify GetDeclaredEvent() method
[Fact]
public static void TestGetDeclaredEvent3()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
Assert.Throws<ArgumentNullException>(() => { EventInfo ei = typeInfo.GetDeclaredEvent(null); });
}
// Verify GetDeclaredField() method
[Fact]
public static void TestGetDeclaredField1()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredField(typeInfo, "PublicField");
}
// Verify GetDeclaredField() method
[Fact]
public static void TestGetDeclaredField2()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredField(typeInfo, "PublicStaticField");
}
// Verify GetDeclaredField() method
[Fact]
public static void TestGetDeclaredField3()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
FieldInfo fi = typeInfo.GetDeclaredField("NoSuchField");
Assert.Null(fi);
}
// Verify GetDeclaredField() method
[Fact]
public static void TestGetDeclaredField4()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
Assert.Throws<ArgumentNullException>(() => { FieldInfo fi = typeInfo.GetDeclaredField(null); });
}
// Verify GetDeclaredMethod() method
[Fact]
public static void TestGetDeclaredMethod1()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredMethod(typeInfo, "PublicMethod");
}
// Verify GetDeclaredMethod() method
[Fact]
public static void TestGetDeclaredMethod2()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredMethod(typeInfo, "PublicStaticMethod");
}
// Verify GetDeclaredMethod() method
[Fact]
public static void TestGetDeclaredMethod3()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
MethodInfo mi = typeInfo.GetDeclaredMethod("NoSuchMethod");
Assert.Null(mi);
}
// Verify GetDeclaredMethod() method
[Fact]
public static void TestGetDeclaredMethod4()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
Assert.Throws<ArgumentNullException>(() => { MethodInfo mi = typeInfo.GetDeclaredMethod(null); });
}
// Verify GetDeclaredMethods() method
[Fact]
public static void TestGetDeclaredMethods1()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredMethods(typeInfo, "overRiddenMethod", 4);
}
// Verify GetDeclaredMethods() method
[Fact]
public static void TestGetDeclaredMethods2()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredMethods(typeInfo, "NoSuchMethod", 0);
}
// Verify GetDeclaredNestedType() method
[Fact]
public static void TestGetDeclaredNestedType1()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
VerifyGetDeclaredNestedType(typeInfo, "PublicNestedType");
}
// Verify GetDeclaredNestedType() method
[Fact]
public static void TestGetDeclaredNestedType2()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
TypeInfo nested_ti = typeInfo.GetDeclaredNestedType("NoSuchType");
Assert.Null(nested_ti);
}
// Verify GetDeclaredNestedType() method
[Fact]
public static void TestGetDeclaredNestedType3()
{
Type type = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = type.GetTypeInfo();
Assert.Throws<ArgumentNullException>(() => { TypeInfo nested_ti = typeInfo.GetDeclaredNestedType(null); });
}
// Verify GetElementType() method
[Fact]
public static void TestGetElementType1()
{
Type runtimeType = typeof(MethodPublicClass).Project();
TypeInfo typeInfo = runtimeType.GetTypeInfo();
Type type = typeInfo.GetElementType();
Assert.Null(type);
}
// Verify GetElementType() method
[Fact]
public static void TestGetElementType2()
{
string[] myArray = { "a", "b", "c" };
Type runtimeType = myArray.GetType();
TypeInfo typeInfo = runtimeType.GetTypeInfo();
Type type = typeInfo.GetElementType();
Assert.NotNull(type);
Assert.Equal(typeof(string).Project().Name, type.Name);
}
// Verify GetElementType() method
[Fact]
public static void TestGetElementType3()
{
int[] myArray = { 1, 2, 3, 4 };
Type runtimeType = myArray.GetType();
TypeInfo typeInfo = runtimeType.GetTypeInfo();
Type type = typeInfo.GetElementType();
Assert.NotNull(type);
Assert.Equal(typeof(int).Project().Name, type.Name);
}
// Verify GetGenericParameterConstraints() method
[Fact]
public static void TestGetGenericParameterConstraints1()
{
Type def = typeof(TypeInfoMethodClassWithConstraints<,>).Project();
TypeInfo ti = def.GetTypeInfo();
Type[] defparams = ti.GenericTypeParameters;
Assert.Equal(2, defparams.Length);
Type[] tpConstraints = defparams[0].GetTypeInfo().GetGenericParameterConstraints();
Assert.Equal(2, tpConstraints.Length);
Assert.Equal(typeof(TypeInfoMethodBase).Project(), tpConstraints[0]);
Assert.Equal(typeof(MethodITest).Project(), tpConstraints[1]);
}
// Verify GetGenericParameterConstraints() method
[Fact]
public static void TestGetGenericParameterConstraints2()
{
Type def = typeof(TypeInfoMethodClassWithConstraints<,>).Project();
TypeInfo ti = def.GetTypeInfo();
Type[] defparams = ti.GenericTypeParameters;
Assert.Equal(2, defparams.Length);
Type[] tpConstraints = defparams[1].GetTypeInfo().GetGenericParameterConstraints();
Assert.Equal(0, tpConstraints.Length);
}
// Verify GetGenericTypeDefinition() method
[Fact]
public static void TestGetGenericTypeDefinition()
{
TypeInfoMethodGenericClass<int> genericObj = new TypeInfoMethodGenericClass<int>();
Type type = genericObj.GetType().Project();
Type generictype = type.GetTypeInfo().GetGenericTypeDefinition();
Assert.NotNull(generictype);
Assert.Equal(typeof(TypeInfoMethodGenericClass<>).Project(), generictype);
}
// Verify IsSubClassOf() method
[Fact]
public static void TestIsSubClassOf1()
{
TypeInfo t1 = typeof(TypeInfoMethodBase).Project().GetTypeInfo();
TypeInfo t2 = typeof(TypeInfoMethodDerived).Project().GetTypeInfo();
bool isSubClass = t1.IsSubclassOf(t2.AsType());
Assert.False(isSubClass);
}
// Verify IsSubClassOf() method
[Fact]
public static void TestIsSubClassOf2()
{
TypeInfo t1 = typeof(TypeInfoMethodBase).Project().GetTypeInfo();
TypeInfo t2 = typeof(TypeInfoMethodDerived).Project().GetTypeInfo();
bool isSubClass = t2.IsSubclassOf(t1.AsType());
Assert.True(isSubClass, "Failed! isSubClass returned False when this class derives from input class ");
}
// Verify IsAssignableFrom() method
[Fact]
public static void TestIsAssignableFrom1()
{
TypeInfo t1 = typeof(TypeInfoMethodBase).Project().GetTypeInfo();
TypeInfo t2 = typeof(TypeInfoMethodDerived).Project().GetTypeInfo();
bool isAssignable = t1.IsAssignableFrom(t2);
Assert.True(isAssignable, "Failed! IsAssignableFrom returned False");
}
// Verify IsAssignableFrom() method
[Fact]
public static void TestIsAssignableFrom2()
{
TypeInfo t1 = typeof(TypeInfoMethodBase).Project().GetTypeInfo();
TypeInfo t2 = typeof(TypeInfoMethodDerived).Project().GetTypeInfo();
bool isAssignable = t2.IsAssignableFrom(t1);
Assert.False(isAssignable, "Failed! IsAssignableFrom returned True");
}
// Verify IsAssignableFrom() method
[Fact]
public static void TestIsAssignableFrom3()
{
TypeInfo t1 = typeof(TypeInfoMethodBase).Project().GetTypeInfo();
TypeInfo t2 = typeof(TypeInfoMethodBase).Project().GetTypeInfo();
bool isAssignable = t2.IsAssignableFrom(t2);
Assert.True(isAssignable, "Failed! IsAssignableFrom returned False for same Type");
}
// Verify IsAssignableFrom() method
[Fact]
public static void TestIsAssignableFrom4()
{
TypeInfo t1 = typeof(MethodITest).Project().GetTypeInfo();
TypeInfo t2 = typeof(TypeInfoMethodImplClass).Project().GetTypeInfo();
bool isAssignable = t1.IsAssignableFrom(t2);
Assert.True(isAssignable, "Failed! IsAssignableFrom returned False");
}
// Verify MakeArrayType() method
[Fact]
public static void TestMakeArrayType1()
{
TypeInfo ti = typeof(string).Project().GetTypeInfo();
Type arraytype = ti.MakeArrayType();
string[] strArray = { "a", "b", "c" };
Assert.NotNull(arraytype);
Assert.Equal(strArray.GetType().Project(), arraytype);
}
// Verify MakeArrayType() method
[Fact]
public static void TestMakeArrayType2()
{
TypeInfo ti = typeof(int).Project().GetTypeInfo();
Type arraytype = ti.MakeArrayType();
int[] intArray = { 1, 2, 3 };
Assert.NotNull(arraytype);
Assert.Equal(intArray.GetType().Project(), arraytype);
}
// Verify MakeArrayType(int rank) method
[Fact]
public static void TestMakeArrayTypeWithRank1()
{
TypeInfo ti = typeof(string).Project().GetTypeInfo();
Type arraytype = ti.MakeArrayType(1);
Assert.NotNull(arraytype);
Assert.True(arraytype.IsArray, "Failed!! MakeArrayType() returned type that is not Array");
}
// Verify MakeArrayType(int rank) method
[Fact]
public static void TestMakeArrayTypeWithRank2()
{
GC.KeepAlive(typeof(int[,]).Project());
TypeInfo ti = typeof(int).Project().GetTypeInfo();
Type arraytype = ti.MakeArrayType(2);
Assert.NotNull(arraytype);
Assert.True(arraytype.IsArray, "Failed!! MakeArrayType() returned type that is not Array");
}
// Verify MakeArrayType() method
[Fact]
public static void TestMakeArrayOfPointerType1()
{
TypeInfo ti = typeof(char*).Project().GetTypeInfo();
Type arraytype = ti.MakeArrayType(3);
Assert.NotNull(arraytype);
Assert.True(arraytype.IsArray);
Assert.Equal(3, arraytype.GetArrayRank());
Assert.Equal(arraytype.GetElementType(), typeof(char*).Project());
}
// Verify MakeArrayType(int rank) method
[Fact]
public static void TestMakeArrayTypeWithRank3()
{
GC.KeepAlive(typeof(int[,,]).Project());
TypeInfo ti = typeof(int).Project().GetTypeInfo();
Type arraytype = ti.MakeArrayType(3);
Assert.NotNull(arraytype);
Assert.True(arraytype.IsArray, "Failed!! MakeArrayType() returned type that is not Array");
}
// Verify MakeByRefType method
[Fact]
public static void TestMakeByRefType1()
{
TypeInfo ti = typeof(int).Project().GetTypeInfo();
Type byreftype = ti.MakeByRefType();
Assert.NotNull(byreftype);
Assert.True(byreftype.IsByRef, "Failed!! MakeByRefType() returned type that is not ByRef");
}
// Verify MakeByRefType method
[Fact]
public static void TestMakeByRefType2()
{
TypeInfo ti = typeof(string).Project().GetTypeInfo();
Type byreftype = ti.MakeByRefType();
Assert.NotNull(byreftype);
Assert.True(byreftype.IsByRef, "Failed!! MakeByRefType() returned type that is not ByRef");
}
// Verify MakePointerType method
[Fact]
public static void TestMakePointerType1()
{
TypeInfo ti = typeof(int).Project().GetTypeInfo();
Type ptrtype = ti.MakePointerType();
Assert.NotNull(ptrtype);
Assert.True(ptrtype.IsPointer, "Failed!! MakePointerType() returned type that is not Pointer");
}
// Verify MakePointerType method
[Fact]
public static void TestMakePointerType2()
{
TypeInfo ti = typeof(string).Project().GetTypeInfo();
Type ptrtype = ti.MakePointerType();
Assert.NotNull(ptrtype);
Assert.True(ptrtype.IsPointer, "Failed!! MakePointerType() returned type that is not Pointer");
}
// Verify MakeGenericType() method
[Fact]
public static void TestMakeGenericType()
{
Type type = typeof(List<>).Project();
Type[] typeArgs = { typeof(string).Project() };
TypeInfo typeInfo = type.GetTypeInfo();
Type generictype = typeInfo.MakeGenericType(typeArgs);
Assert.NotNull(generictype);
Assert.True(generictype.GetTypeInfo().IsGenericType, "Failed!! MakeGenericType() returned type that is not generic");
}
// Verify ToString() method
[Fact]
public static void TestToString1()
{
Type type = typeof(string).Project();
TypeInfo typeInfo = type.GetTypeInfo();
Assert.Equal("System.String", typeInfo.ToString());
}
// Verify ToString() method
[Fact]
public static void TestToString2()
{
Type type = typeof(int).Project();
TypeInfo typeInfo = type.GetTypeInfo();
Assert.Equal("System.Int32", typeInfo.ToString());
}
//Private Helper Methods
private static void VerifyGetDeclaredEvent(TypeInfo ti, string eventName)
{
EventInfo ei = ti.GetDeclaredEvent(eventName);
Assert.NotNull(ei);
Assert.Equal(eventName, ei.Name);
}
private static void VerifyGetDeclaredField(TypeInfo ti, string fieldName)
{
FieldInfo fi = ti.GetDeclaredField(fieldName);
Assert.NotNull(fi);
Assert.Equal(fieldName, fi.Name);
}
private static void VerifyGetDeclaredMethod(TypeInfo ti, string methodName)
{
MethodInfo mi = ti.GetDeclaredMethod(methodName);
Assert.NotNull(mi);
Assert.Equal(methodName, mi.Name);
}
private static void VerifyGetDeclaredMethods(TypeInfo ti, string methodName, int count)
{
IEnumerator<MethodInfo> alldefinedMethods = ti.GetDeclaredMethods(methodName).GetEnumerator();
MethodInfo mi = null;
int numMethods = 0;
while (alldefinedMethods.MoveNext())
{
mi = alldefinedMethods.Current;
Assert.Equal(methodName, mi.Name);
numMethods++;
}
Assert.Equal(count, numMethods);
}
private static void VerifyGetDeclaredNestedType(TypeInfo ti, string name)
{
TypeInfo nested_ti = ti.GetDeclaredNestedType(name);
Assert.NotNull(nested_ti);
Assert.Equal(name, nested_ti.Name);
}
private static void VerifyGetDeclaredProperty(TypeInfo ti, string name)
{
PropertyInfo pi = ti.GetDeclaredProperty(name);
Assert.NotNull(pi);
Assert.Equal(name, pi.Name);
}
}
//Metadata for Reflection
public class MethodPublicClass
{
public int PublicField;
public static int PublicStaticField;
public MethodPublicClass() { }
public void PublicMethod() { }
public void overRiddenMethod() { }
public void overRiddenMethod(int i) { }
public void overRiddenMethod(string s) { }
public void overRiddenMethod(object o) { }
public static void PublicStaticMethod() { }
public class PublicNestedType { }
public int PublicProperty { get { return default(int); } set { } }
public event System.EventHandler EventPublic;
}
public interface MethodITest { }
public class TypeInfoMethodBase { }
public class TypeInfoMethodDerived : TypeInfoMethodBase { }
public class TypeInfoMethodImplClass : MethodITest { }
public class TypeInfoMethodGenericClass<T> { }
public class TypeInfoMethodClassWithConstraints<T, U>
where T : TypeInfoMethodBase, MethodITest
where U : class, new()
{ }
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Configuration.ConfigurationManager/tests/Mono/ConfigurationSaveTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// ConfigurationSaveTest.cs
//
// Author:
// Martin Baulig <[email protected]>
//
// Copyright (c) 2012 Xamarin Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Text;
using System.Reflection;
using System.Globalization;
using System.Configuration;
using System.Collections.Generic;
using SysConfig = System.Configuration.Configuration;
using Xunit;
namespace MonoTests.System.Configuration
{
using Util;
public class ConfigurationSaveTest
{
#region Test Framework
public abstract class ConfigProvider
{
public void Create(string filename)
{
if (File.Exists(filename))
File.Delete(filename);
var settings = new XmlWriterSettings();
settings.Indent = true;
using (var writer = XmlTextWriter.Create(filename, settings))
{
writer.WriteStartElement("configuration");
WriteXml(writer);
writer.WriteEndElement();
}
}
public abstract UserLevel Level
{
get;
}
public enum UserLevel
{
MachineAndExe,
RoamingAndExe
}
public virtual SysConfig OpenConfig(string parentFile, string configFile)
{
ConfigurationUserLevel level;
var map = new ExeConfigurationFileMap();
switch (Level)
{
case UserLevel.MachineAndExe:
map.ExeConfigFilename = configFile;
map.MachineConfigFilename = parentFile;
level = ConfigurationUserLevel.None;
break;
case UserLevel.RoamingAndExe:
map.RoamingUserConfigFilename = configFile;
map.ExeConfigFilename = parentFile;
level = ConfigurationUserLevel.PerUserRoaming;
break;
default:
throw new InvalidOperationException();
}
return ConfigurationManager.OpenMappedExeConfiguration(map, level);
}
protected abstract void WriteXml(XmlWriter writer);
}
public abstract class MachineConfigProvider : ConfigProvider
{
protected override void WriteXml(XmlWriter writer)
{
writer.WriteStartElement("configSections");
WriteSections(writer);
writer.WriteEndElement();
WriteValues(writer);
}
public override UserLevel Level
{
get { return UserLevel.MachineAndExe; }
}
protected abstract void WriteSections(XmlWriter writer);
protected abstract void WriteValues(XmlWriter writer);
}
class DefaultMachineConfig : MachineConfigProvider
{
protected override void WriteSections(XmlWriter writer)
{
writer.WriteStartElement("section");
writer.WriteAttributeString("name", "my");
writer.WriteAttributeString("type", typeof(MySection).AssemblyQualifiedName);
writer.WriteAttributeString("allowLocation", "true");
writer.WriteAttributeString("allowDefinition", "Everywhere");
writer.WriteAttributeString("allowExeDefinition", "MachineToRoamingUser");
writer.WriteAttributeString("restartOnExternalChanges", "true");
writer.WriteAttributeString("requirePermission", "true");
writer.WriteEndElement();
}
internal static void WriteConfigSections(XmlWriter writer)
{
var provider = new DefaultMachineConfig();
writer.WriteStartElement("configSections");
provider.WriteSections(writer);
writer.WriteEndElement();
}
protected override void WriteValues(XmlWriter writer)
{
writer.WriteStartElement("my");
writer.WriteEndElement();
}
}
class DefaultMachineConfig2 : MachineConfigProvider
{
protected override void WriteSections(XmlWriter writer)
{
writer.WriteStartElement("section");
writer.WriteAttributeString("name", "my2");
writer.WriteAttributeString("type", typeof(MySection2).AssemblyQualifiedName);
writer.WriteAttributeString("allowLocation", "true");
writer.WriteAttributeString("allowDefinition", "Everywhere");
writer.WriteAttributeString("allowExeDefinition", "MachineToRoamingUser");
writer.WriteAttributeString("restartOnExternalChanges", "true");
writer.WriteAttributeString("requirePermission", "true");
writer.WriteEndElement();
}
internal static void WriteConfigSections(XmlWriter writer)
{
var provider = new DefaultMachineConfig2();
writer.WriteStartElement("configSections");
provider.WriteSections(writer);
writer.WriteEndElement();
}
protected override void WriteValues(XmlWriter writer)
{
}
}
abstract class ParentProvider : ConfigProvider
{
protected override void WriteXml(XmlWriter writer)
{
DefaultMachineConfig.WriteConfigSections(writer);
writer.WriteStartElement("my");
writer.WriteStartElement("test");
writer.WriteAttributeString("Hello", "29");
writer.WriteEndElement();
writer.WriteEndElement();
}
}
class RoamingAndExe : ParentProvider
{
public override UserLevel Level
{
get { return UserLevel.RoamingAndExe; }
}
}
private delegate void TestFunction(SysConfig config, TestLabel label);
private delegate void XmlCheckFunction(XPathNavigator nav, TestLabel label);
private static void Run(string name, TestFunction func)
{
var label = new TestLabel(name);
TestUtil.RunWithTempFile(filename =>
{
var fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = filename;
var config = ConfigurationManager.OpenMappedExeConfiguration(
fileMap, ConfigurationUserLevel.None);
func(config, label);
});
}
private static void Run<TConfig>(string name, TestFunction func)
where TConfig : ConfigProvider, new()
{
Run<TConfig>(new TestLabel(name), func, null);
}
private static void Run<TConfig>(TestLabel label, TestFunction func)
where TConfig : ConfigProvider, new()
{
Run<TConfig>(label, func, null);
}
private static void Run<TConfig>(
string name, TestFunction func, XmlCheckFunction check)
where TConfig : ConfigProvider, new()
{
Run<TConfig>(new TestLabel(name), func, check);
}
private static void Run<TConfig>(
TestLabel label, TestFunction func, XmlCheckFunction check)
where TConfig : ConfigProvider, new()
{
TestUtil.RunWithTempFiles((parent, filename) =>
{
var provider = new TConfig();
provider.Create(parent);
Assert.False(File.Exists(filename));
var config = provider.OpenConfig(parent, filename);
Assert.False(File.Exists(filename));
try
{
label.EnterScope("config");
func(config, label);
}
finally
{
label.LeaveScope();
}
if (check == null)
return;
var xml = new XmlDocument();
xml.Load(filename);
var nav = xml.CreateNavigator().SelectSingleNode("/configuration");
try
{
label.EnterScope("xml");
check(nav, label);
}
finally
{
label.LeaveScope();
}
});
}
#endregion
#region Assertion Helpers
static void AssertNotModified(MySection my, TestLabel label)
{
label.EnterScope("modified");
Assert.NotNull(my);
Assert.False(my.IsModified, label.Get());
Assert.NotNull(my.List);
Assert.Equal(0, my.List.Collection.Count);
Assert.False(my.List.IsModified, label.Get());
label.LeaveScope();
}
static void AssertListElement(XPathNavigator nav, TestLabel label)
{
Assert.True(nav.HasChildren, label.Get());
var iter = nav.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter.Count);
Assert.True(iter.MoveNext(), label.Get());
var my = iter.Current;
label.EnterScope("my");
Assert.Equal("my", my.Name);
Assert.False(my.HasAttributes, label.Get());
label.EnterScope("children");
Assert.True(my.HasChildren, label.Get());
var iter2 = my.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter2.Count);
Assert.True(iter2.MoveNext(), label.Get());
var test = iter2.Current;
label.EnterScope("test");
Assert.Equal("test", test.Name);
Assert.False(test.HasChildren, label.Get());
Assert.True(test.HasAttributes, label.Get());
var attr = test.GetAttribute("Hello", string.Empty);
Assert.Equal("29", attr);
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
}
#endregion
#region Tests
[Fact]
public void DefaultValues()
{
Run<DefaultMachineConfig>("DefaultValues", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
label.EnterScope("file");
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Minimal);
Assert.False(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
});
}
[Fact]
public void AddDefaultListElement()
{
Run<DefaultMachineConfig>("AddDefaultListElement", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
label.EnterScope("add");
var element = my.List.Collection.AddElement();
Assert.True(my.IsModified, label.Get());
Assert.True(my.List.IsModified, label.Get());
Assert.True(my.List.Collection.IsModified, label.Get());
Assert.False(element.IsModified, label.Get());
label.LeaveScope();
config.Save(ConfigurationSaveMode.Minimal);
Assert.False(File.Exists(config.FilePath), label.Get());
});
}
[Fact]
public void AddDefaultListElement2()
{
Run<DefaultMachineConfig>("AddDefaultListElement2", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
label.EnterScope("add");
var element = my.List.Collection.AddElement();
Assert.True(my.IsModified, label.Get());
Assert.True(my.List.IsModified, label.Get());
Assert.True(my.List.Collection.IsModified, label.Get());
Assert.False(element.IsModified, label.Get());
label.LeaveScope();
config.Save(ConfigurationSaveMode.Modified);
Assert.True(File.Exists(config.FilePath), label.Get());
}, (nav, label) =>
{
Assert.True(nav.HasChildren, label.Get());
var iter = nav.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter.Count);
Assert.True(iter.MoveNext(), label.Get());
var my = iter.Current;
label.EnterScope("my");
Assert.Equal("my", my.Name);
Assert.False(my.HasAttributes, label.Get());
Assert.False(my.HasChildren, label.Get());
label.LeaveScope();
});
}
[Fact]
public void AddDefaultListElement3()
{
Run<DefaultMachineConfig>("AddDefaultListElement3", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
label.EnterScope("add");
var element = my.List.Collection.AddElement();
Assert.True(my.IsModified, label.Get());
Assert.True(my.List.IsModified, label.Get());
Assert.True(my.List.Collection.IsModified, label.Get());
Assert.False(element.IsModified, label.Get());
label.LeaveScope();
config.Save(ConfigurationSaveMode.Full);
Assert.True(File.Exists(config.FilePath), label.Get());
}, (nav, label) =>
{
Assert.True(nav.HasChildren, label.Get());
var iter = nav.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter.Count);
Assert.True(iter.MoveNext(), label.Get());
var my = iter.Current;
label.EnterScope("my");
Assert.Equal("my", my.Name);
Assert.False(my.HasAttributes, label.Get());
label.EnterScope("children");
Assert.True(my.HasChildren, label.Get());
var iter2 = my.SelectChildren(XPathNodeType.Element);
Assert.Equal(2, iter2.Count);
label.EnterScope("list");
var iter3 = my.Select("list/*");
Assert.Equal(1, iter3.Count);
Assert.True(iter3.MoveNext(), label.Get());
var collection = iter3.Current;
Assert.Equal("collection", collection.Name);
Assert.False(collection.HasChildren, label.Get());
Assert.True(collection.HasAttributes, label.Get());
var hello = collection.GetAttribute("Hello", string.Empty);
Assert.Equal("8", hello);
var world = collection.GetAttribute("World", string.Empty);
Assert.Equal("0", world);
label.LeaveScope();
label.EnterScope("test");
var iter4 = my.Select("test");
Assert.Equal(1, iter4.Count);
Assert.True(iter4.MoveNext(), label.Get());
var test = iter4.Current;
Assert.Equal("test", test.Name);
Assert.False(test.HasChildren, label.Get());
Assert.True(test.HasAttributes, label.Get());
var hello2 = test.GetAttribute("Hello", string.Empty);
Assert.Equal("8", hello2);
var world2 = test.GetAttribute("World", string.Empty);
Assert.Equal("0", world2);
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
});
}
[Fact]
public void AddListElement()
{
Run<DefaultMachineConfig>("AddListElement", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
my.Test.Hello = 29;
label.EnterScope("file");
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Minimal);
Assert.True(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
}, (nav, label) =>
{
AssertListElement(nav, label);
});
}
[Fact]
public void NotModifiedAfterSave()
{
Run<DefaultMachineConfig>("NotModifiedAfterSave", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
label.EnterScope("add");
var element = my.List.Collection.AddElement();
Assert.True(my.IsModified, label.Get());
Assert.True(my.List.IsModified, label.Get());
Assert.True(my.List.Collection.IsModified, label.Get());
Assert.False(element.IsModified, label.Get());
label.LeaveScope();
label.EnterScope("1st-save");
config.Save(ConfigurationSaveMode.Minimal);
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Modified);
Assert.False(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
label.EnterScope("modify");
element.Hello = 12;
Assert.True(my.IsModified, label.Get());
Assert.True(my.List.IsModified, label.Get());
Assert.True(my.List.Collection.IsModified, label.Get());
Assert.True(element.IsModified, label.Get());
label.LeaveScope();
label.EnterScope("2nd-save");
config.Save(ConfigurationSaveMode.Modified);
Assert.True(File.Exists(config.FilePath), label.Get());
Assert.False(my.IsModified, label.Get());
Assert.False(my.List.IsModified, label.Get());
Assert.False(my.List.Collection.IsModified, label.Get());
Assert.False(element.IsModified, label.Get());
label.LeaveScope(); // 2nd-save
});
}
[Fact]
public void AddSection()
{
Run("AddSection", (config, label) =>
{
Assert.Null(config.Sections["my"]);
var my = new MySection();
config.Sections.Add("my2", my);
config.Save(ConfigurationSaveMode.Full);
Assert.True(File.Exists(config.FilePath), label.Get());
});
}
[Fact]
public void AddElement()
{
Run<DefaultMachineConfig>("AddElement", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
var element = my.List.DefaultCollection.AddElement();
element.Hello = 12;
config.Save(ConfigurationSaveMode.Modified);
label.EnterScope("file");
Assert.True(File.Exists(config.FilePath), "#c2");
label.LeaveScope();
}, (nav, label) =>
{
Assert.True(nav.HasChildren, label.Get());
var iter = nav.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter.Count);
Assert.True(iter.MoveNext(), label.Get());
var my = iter.Current;
label.EnterScope("my");
Assert.Equal("my", my.Name);
Assert.False(my.HasAttributes, label.Get());
Assert.True(my.HasChildren, label.Get());
label.EnterScope("children");
var iter2 = my.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter2.Count);
Assert.True(iter2.MoveNext(), label.Get());
var list = iter2.Current;
label.EnterScope("list");
Assert.Equal("list", list.Name);
Assert.False(list.HasChildren, label.Get());
Assert.True(list.HasAttributes, label.Get());
var attr = list.GetAttribute("Hello", string.Empty);
Assert.Equal("12", attr);
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
});
}
[Fact]
public void ModifyListElement()
{
Run<RoamingAndExe>("ModifyListElement", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
my.Test.Hello = 29;
label.EnterScope("file");
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Minimal);
Assert.False(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
});
}
[Fact]
public void ModifyListElement2()
{
Run<RoamingAndExe>("ModifyListElement2", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
my.Test.Hello = 29;
label.EnterScope("file");
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Modified);
Assert.True(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
}, (nav, label) =>
{
AssertListElement(nav, label);
});
}
[Fact]
public void TestElementWithCollection()
{
Run<DefaultMachineConfig2>("TestElementWithCollection", (config, label) =>
{
label.EnterScope("section");
var my2 = config.Sections["my2"] as MySection2;
Assert.NotNull(my2);
Assert.NotNull(my2.Test);
Assert.NotNull(my2.Test.DefaultCollection);
Assert.Equal(0, my2.Test.DefaultCollection.Count);
label.LeaveScope();
my2.Test.DefaultCollection.AddElement();
my2.Element.Hello = 29;
label.EnterScope("file");
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Minimal);
Assert.True(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
}, (nav, label) =>
{
Assert.True(nav.HasChildren, label.Get());
var iter = nav.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter.Count);
Assert.True(iter.MoveNext(), label.Get());
var my = iter.Current;
label.EnterScope("my2");
Assert.Equal("my2", my.Name);
Assert.False(my.HasAttributes, label.Get());
Assert.True(my.HasChildren, label.Get());
label.EnterScope("children");
var iter2 = my.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter2.Count);
Assert.True(iter2.MoveNext(), label.Get());
var element = iter2.Current;
label.EnterScope("element");
Assert.Equal("element", element.Name);
Assert.False(element.HasChildren, label.Get());
Assert.True(element.HasAttributes, label.Get());
var attr = element.GetAttribute("Hello", string.Empty);
Assert.Equal("29", attr);
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
});
}
[Fact]
public void TestElementWithCollection2()
{
Run<DefaultMachineConfig2>("TestElementWithCollection2", (config, label) =>
{
label.EnterScope("section");
var my2 = config.Sections["my2"] as MySection2;
Assert.NotNull(my2);
Assert.NotNull(my2.Test);
Assert.NotNull(my2.Test.DefaultCollection);
Assert.Equal(0, my2.Test.DefaultCollection.Count);
label.LeaveScope();
var element = my2.Test.DefaultCollection.AddElement();
var element2 = element.Test.DefaultCollection.AddElement();
element2.Hello = 1;
label.EnterScope("file");
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Minimal);
Assert.True(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
}, (nav, label) =>
{
Assert.True(nav.HasChildren, label.Get());
var iter = nav.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter.Count);
Assert.True(iter.MoveNext(), label.Get());
var my = iter.Current;
label.EnterScope("my2");
Assert.Equal("my2", my.Name);
Assert.False(my.HasAttributes, label.Get());
Assert.True(my.HasChildren, label.Get());
label.EnterScope("children");
var iter2 = my.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter2.Count);
Assert.True(iter2.MoveNext(), label.Get());
var collection = iter2.Current;
label.EnterScope("collection");
Assert.Equal("collection", collection.Name);
Assert.True(collection.HasChildren, label.Get());
Assert.False(collection.HasAttributes, label.Get());
label.EnterScope("children");
var iter3 = collection.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter3.Count);
Assert.True(iter3.MoveNext(), label.Get());
var element = iter3.Current;
label.EnterScope("element");
Assert.Equal("test", element.Name);
Assert.False(element.HasChildren, label.Get());
Assert.True(element.HasAttributes, label.Get());
var attr = element.GetAttribute("Hello", string.Empty);
Assert.Equal("1", attr);
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
});
}
#endregion
#region Configuration Classes
public class MyElement : ConfigurationElement
{
[ConfigurationProperty("Hello", DefaultValue = 8)]
public int Hello
{
get { return (int)base["Hello"]; }
set { base["Hello"] = value; }
}
[ConfigurationProperty("World", IsRequired = false)]
public int World
{
get { return (int)base["World"]; }
set { base["World"] = value; }
}
public new bool IsModified
{
get { return base.IsModified(); }
}
}
public class MyCollection<T> : ConfigurationElementCollection
where T : ConfigurationElement, new()
{
#region implemented abstract members of ConfigurationElementCollection
protected override ConfigurationElement CreateNewElement()
{
return new T();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((T)element).GetHashCode();
}
#endregion
public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.BasicMap;
}
}
public T AddElement()
{
var element = new T();
BaseAdd(element);
return element;
}
public void RemoveElement(T element)
{
BaseRemove(GetElementKey(element));
}
public new bool IsModified
{
get { return base.IsModified(); }
}
}
public class MyCollectionElement<T> : ConfigurationElement
where T : ConfigurationElement, new()
{
[ConfigurationProperty("",
Options = ConfigurationPropertyOptions.IsDefaultCollection,
IsDefaultCollection = true)]
public MyCollection<T> DefaultCollection
{
get { return (MyCollection<T>)this[string.Empty]; }
set { this[string.Empty] = value; }
}
[ConfigurationProperty("collection", Options = ConfigurationPropertyOptions.None)]
public MyCollection<T> Collection
{
get { return (MyCollection<T>)this["collection"]; }
set { this["collection"] = value; }
}
public new bool IsModified
{
get { return base.IsModified(); }
}
}
public class MySection : ConfigurationSection
{
[ConfigurationProperty("list", Options = ConfigurationPropertyOptions.None)]
public MyCollectionElement<MyElement> List
{
get { return (MyCollectionElement<MyElement>)this["list"]; }
}
[ConfigurationProperty("test", Options = ConfigurationPropertyOptions.None)]
public MyElement Test
{
get { return (MyElement)this["test"]; }
}
public new bool IsModified
{
get { return base.IsModified(); }
}
}
public class MyElementWithCollection : ConfigurationElement
{
[ConfigurationProperty("test")]
public MyCollectionElement<MyElement> Test
{
get { return (MyCollectionElement<MyElement>)this["test"]; }
}
}
public class MySection2 : ConfigurationSection
{
[ConfigurationProperty("collection", Options = ConfigurationPropertyOptions.None)]
public MyCollectionElement<MyElementWithCollection> Test
{
get { return (MyCollectionElement<MyElementWithCollection>)this["collection"]; }
}
[ConfigurationProperty("element", Options = ConfigurationPropertyOptions.None)]
public MyElement Element
{
get { return (MyElement)this["element"]; }
}
}
public class MySectionGroup : ConfigurationSectionGroup
{
public MySection2 My2
{
get { return (MySection2)Sections["my2"]; }
}
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// ConfigurationSaveTest.cs
//
// Author:
// Martin Baulig <[email protected]>
//
// Copyright (c) 2012 Xamarin Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Text;
using System.Reflection;
using System.Globalization;
using System.Configuration;
using System.Collections.Generic;
using SysConfig = System.Configuration.Configuration;
using Xunit;
namespace MonoTests.System.Configuration
{
using Util;
public class ConfigurationSaveTest
{
#region Test Framework
public abstract class ConfigProvider
{
public void Create(string filename)
{
if (File.Exists(filename))
File.Delete(filename);
var settings = new XmlWriterSettings();
settings.Indent = true;
using (var writer = XmlTextWriter.Create(filename, settings))
{
writer.WriteStartElement("configuration");
WriteXml(writer);
writer.WriteEndElement();
}
}
public abstract UserLevel Level
{
get;
}
public enum UserLevel
{
MachineAndExe,
RoamingAndExe
}
public virtual SysConfig OpenConfig(string parentFile, string configFile)
{
ConfigurationUserLevel level;
var map = new ExeConfigurationFileMap();
switch (Level)
{
case UserLevel.MachineAndExe:
map.ExeConfigFilename = configFile;
map.MachineConfigFilename = parentFile;
level = ConfigurationUserLevel.None;
break;
case UserLevel.RoamingAndExe:
map.RoamingUserConfigFilename = configFile;
map.ExeConfigFilename = parentFile;
level = ConfigurationUserLevel.PerUserRoaming;
break;
default:
throw new InvalidOperationException();
}
return ConfigurationManager.OpenMappedExeConfiguration(map, level);
}
protected abstract void WriteXml(XmlWriter writer);
}
public abstract class MachineConfigProvider : ConfigProvider
{
protected override void WriteXml(XmlWriter writer)
{
writer.WriteStartElement("configSections");
WriteSections(writer);
writer.WriteEndElement();
WriteValues(writer);
}
public override UserLevel Level
{
get { return UserLevel.MachineAndExe; }
}
protected abstract void WriteSections(XmlWriter writer);
protected abstract void WriteValues(XmlWriter writer);
}
class DefaultMachineConfig : MachineConfigProvider
{
protected override void WriteSections(XmlWriter writer)
{
writer.WriteStartElement("section");
writer.WriteAttributeString("name", "my");
writer.WriteAttributeString("type", typeof(MySection).AssemblyQualifiedName);
writer.WriteAttributeString("allowLocation", "true");
writer.WriteAttributeString("allowDefinition", "Everywhere");
writer.WriteAttributeString("allowExeDefinition", "MachineToRoamingUser");
writer.WriteAttributeString("restartOnExternalChanges", "true");
writer.WriteAttributeString("requirePermission", "true");
writer.WriteEndElement();
}
internal static void WriteConfigSections(XmlWriter writer)
{
var provider = new DefaultMachineConfig();
writer.WriteStartElement("configSections");
provider.WriteSections(writer);
writer.WriteEndElement();
}
protected override void WriteValues(XmlWriter writer)
{
writer.WriteStartElement("my");
writer.WriteEndElement();
}
}
class DefaultMachineConfig2 : MachineConfigProvider
{
protected override void WriteSections(XmlWriter writer)
{
writer.WriteStartElement("section");
writer.WriteAttributeString("name", "my2");
writer.WriteAttributeString("type", typeof(MySection2).AssemblyQualifiedName);
writer.WriteAttributeString("allowLocation", "true");
writer.WriteAttributeString("allowDefinition", "Everywhere");
writer.WriteAttributeString("allowExeDefinition", "MachineToRoamingUser");
writer.WriteAttributeString("restartOnExternalChanges", "true");
writer.WriteAttributeString("requirePermission", "true");
writer.WriteEndElement();
}
internal static void WriteConfigSections(XmlWriter writer)
{
var provider = new DefaultMachineConfig2();
writer.WriteStartElement("configSections");
provider.WriteSections(writer);
writer.WriteEndElement();
}
protected override void WriteValues(XmlWriter writer)
{
}
}
abstract class ParentProvider : ConfigProvider
{
protected override void WriteXml(XmlWriter writer)
{
DefaultMachineConfig.WriteConfigSections(writer);
writer.WriteStartElement("my");
writer.WriteStartElement("test");
writer.WriteAttributeString("Hello", "29");
writer.WriteEndElement();
writer.WriteEndElement();
}
}
class RoamingAndExe : ParentProvider
{
public override UserLevel Level
{
get { return UserLevel.RoamingAndExe; }
}
}
private delegate void TestFunction(SysConfig config, TestLabel label);
private delegate void XmlCheckFunction(XPathNavigator nav, TestLabel label);
private static void Run(string name, TestFunction func)
{
var label = new TestLabel(name);
TestUtil.RunWithTempFile(filename =>
{
var fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = filename;
var config = ConfigurationManager.OpenMappedExeConfiguration(
fileMap, ConfigurationUserLevel.None);
func(config, label);
});
}
private static void Run<TConfig>(string name, TestFunction func)
where TConfig : ConfigProvider, new()
{
Run<TConfig>(new TestLabel(name), func, null);
}
private static void Run<TConfig>(TestLabel label, TestFunction func)
where TConfig : ConfigProvider, new()
{
Run<TConfig>(label, func, null);
}
private static void Run<TConfig>(
string name, TestFunction func, XmlCheckFunction check)
where TConfig : ConfigProvider, new()
{
Run<TConfig>(new TestLabel(name), func, check);
}
private static void Run<TConfig>(
TestLabel label, TestFunction func, XmlCheckFunction check)
where TConfig : ConfigProvider, new()
{
TestUtil.RunWithTempFiles((parent, filename) =>
{
var provider = new TConfig();
provider.Create(parent);
Assert.False(File.Exists(filename));
var config = provider.OpenConfig(parent, filename);
Assert.False(File.Exists(filename));
try
{
label.EnterScope("config");
func(config, label);
}
finally
{
label.LeaveScope();
}
if (check == null)
return;
var xml = new XmlDocument();
xml.Load(filename);
var nav = xml.CreateNavigator().SelectSingleNode("/configuration");
try
{
label.EnterScope("xml");
check(nav, label);
}
finally
{
label.LeaveScope();
}
});
}
#endregion
#region Assertion Helpers
static void AssertNotModified(MySection my, TestLabel label)
{
label.EnterScope("modified");
Assert.NotNull(my);
Assert.False(my.IsModified, label.Get());
Assert.NotNull(my.List);
Assert.Equal(0, my.List.Collection.Count);
Assert.False(my.List.IsModified, label.Get());
label.LeaveScope();
}
static void AssertListElement(XPathNavigator nav, TestLabel label)
{
Assert.True(nav.HasChildren, label.Get());
var iter = nav.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter.Count);
Assert.True(iter.MoveNext(), label.Get());
var my = iter.Current;
label.EnterScope("my");
Assert.Equal("my", my.Name);
Assert.False(my.HasAttributes, label.Get());
label.EnterScope("children");
Assert.True(my.HasChildren, label.Get());
var iter2 = my.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter2.Count);
Assert.True(iter2.MoveNext(), label.Get());
var test = iter2.Current;
label.EnterScope("test");
Assert.Equal("test", test.Name);
Assert.False(test.HasChildren, label.Get());
Assert.True(test.HasAttributes, label.Get());
var attr = test.GetAttribute("Hello", string.Empty);
Assert.Equal("29", attr);
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
}
#endregion
#region Tests
[Fact]
public void DefaultValues()
{
Run<DefaultMachineConfig>("DefaultValues", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
label.EnterScope("file");
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Minimal);
Assert.False(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
});
}
[Fact]
public void AddDefaultListElement()
{
Run<DefaultMachineConfig>("AddDefaultListElement", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
label.EnterScope("add");
var element = my.List.Collection.AddElement();
Assert.True(my.IsModified, label.Get());
Assert.True(my.List.IsModified, label.Get());
Assert.True(my.List.Collection.IsModified, label.Get());
Assert.False(element.IsModified, label.Get());
label.LeaveScope();
config.Save(ConfigurationSaveMode.Minimal);
Assert.False(File.Exists(config.FilePath), label.Get());
});
}
[Fact]
public void AddDefaultListElement2()
{
Run<DefaultMachineConfig>("AddDefaultListElement2", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
label.EnterScope("add");
var element = my.List.Collection.AddElement();
Assert.True(my.IsModified, label.Get());
Assert.True(my.List.IsModified, label.Get());
Assert.True(my.List.Collection.IsModified, label.Get());
Assert.False(element.IsModified, label.Get());
label.LeaveScope();
config.Save(ConfigurationSaveMode.Modified);
Assert.True(File.Exists(config.FilePath), label.Get());
}, (nav, label) =>
{
Assert.True(nav.HasChildren, label.Get());
var iter = nav.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter.Count);
Assert.True(iter.MoveNext(), label.Get());
var my = iter.Current;
label.EnterScope("my");
Assert.Equal("my", my.Name);
Assert.False(my.HasAttributes, label.Get());
Assert.False(my.HasChildren, label.Get());
label.LeaveScope();
});
}
[Fact]
public void AddDefaultListElement3()
{
Run<DefaultMachineConfig>("AddDefaultListElement3", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
label.EnterScope("add");
var element = my.List.Collection.AddElement();
Assert.True(my.IsModified, label.Get());
Assert.True(my.List.IsModified, label.Get());
Assert.True(my.List.Collection.IsModified, label.Get());
Assert.False(element.IsModified, label.Get());
label.LeaveScope();
config.Save(ConfigurationSaveMode.Full);
Assert.True(File.Exists(config.FilePath), label.Get());
}, (nav, label) =>
{
Assert.True(nav.HasChildren, label.Get());
var iter = nav.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter.Count);
Assert.True(iter.MoveNext(), label.Get());
var my = iter.Current;
label.EnterScope("my");
Assert.Equal("my", my.Name);
Assert.False(my.HasAttributes, label.Get());
label.EnterScope("children");
Assert.True(my.HasChildren, label.Get());
var iter2 = my.SelectChildren(XPathNodeType.Element);
Assert.Equal(2, iter2.Count);
label.EnterScope("list");
var iter3 = my.Select("list/*");
Assert.Equal(1, iter3.Count);
Assert.True(iter3.MoveNext(), label.Get());
var collection = iter3.Current;
Assert.Equal("collection", collection.Name);
Assert.False(collection.HasChildren, label.Get());
Assert.True(collection.HasAttributes, label.Get());
var hello = collection.GetAttribute("Hello", string.Empty);
Assert.Equal("8", hello);
var world = collection.GetAttribute("World", string.Empty);
Assert.Equal("0", world);
label.LeaveScope();
label.EnterScope("test");
var iter4 = my.Select("test");
Assert.Equal(1, iter4.Count);
Assert.True(iter4.MoveNext(), label.Get());
var test = iter4.Current;
Assert.Equal("test", test.Name);
Assert.False(test.HasChildren, label.Get());
Assert.True(test.HasAttributes, label.Get());
var hello2 = test.GetAttribute("Hello", string.Empty);
Assert.Equal("8", hello2);
var world2 = test.GetAttribute("World", string.Empty);
Assert.Equal("0", world2);
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
});
}
[Fact]
public void AddListElement()
{
Run<DefaultMachineConfig>("AddListElement", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
my.Test.Hello = 29;
label.EnterScope("file");
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Minimal);
Assert.True(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
}, (nav, label) =>
{
AssertListElement(nav, label);
});
}
[Fact]
public void NotModifiedAfterSave()
{
Run<DefaultMachineConfig>("NotModifiedAfterSave", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
label.EnterScope("add");
var element = my.List.Collection.AddElement();
Assert.True(my.IsModified, label.Get());
Assert.True(my.List.IsModified, label.Get());
Assert.True(my.List.Collection.IsModified, label.Get());
Assert.False(element.IsModified, label.Get());
label.LeaveScope();
label.EnterScope("1st-save");
config.Save(ConfigurationSaveMode.Minimal);
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Modified);
Assert.False(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
label.EnterScope("modify");
element.Hello = 12;
Assert.True(my.IsModified, label.Get());
Assert.True(my.List.IsModified, label.Get());
Assert.True(my.List.Collection.IsModified, label.Get());
Assert.True(element.IsModified, label.Get());
label.LeaveScope();
label.EnterScope("2nd-save");
config.Save(ConfigurationSaveMode.Modified);
Assert.True(File.Exists(config.FilePath), label.Get());
Assert.False(my.IsModified, label.Get());
Assert.False(my.List.IsModified, label.Get());
Assert.False(my.List.Collection.IsModified, label.Get());
Assert.False(element.IsModified, label.Get());
label.LeaveScope(); // 2nd-save
});
}
[Fact]
public void AddSection()
{
Run("AddSection", (config, label) =>
{
Assert.Null(config.Sections["my"]);
var my = new MySection();
config.Sections.Add("my2", my);
config.Save(ConfigurationSaveMode.Full);
Assert.True(File.Exists(config.FilePath), label.Get());
});
}
[Fact]
public void AddElement()
{
Run<DefaultMachineConfig>("AddElement", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
var element = my.List.DefaultCollection.AddElement();
element.Hello = 12;
config.Save(ConfigurationSaveMode.Modified);
label.EnterScope("file");
Assert.True(File.Exists(config.FilePath), "#c2");
label.LeaveScope();
}, (nav, label) =>
{
Assert.True(nav.HasChildren, label.Get());
var iter = nav.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter.Count);
Assert.True(iter.MoveNext(), label.Get());
var my = iter.Current;
label.EnterScope("my");
Assert.Equal("my", my.Name);
Assert.False(my.HasAttributes, label.Get());
Assert.True(my.HasChildren, label.Get());
label.EnterScope("children");
var iter2 = my.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter2.Count);
Assert.True(iter2.MoveNext(), label.Get());
var list = iter2.Current;
label.EnterScope("list");
Assert.Equal("list", list.Name);
Assert.False(list.HasChildren, label.Get());
Assert.True(list.HasAttributes, label.Get());
var attr = list.GetAttribute("Hello", string.Empty);
Assert.Equal("12", attr);
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
});
}
[Fact]
public void ModifyListElement()
{
Run<RoamingAndExe>("ModifyListElement", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
my.Test.Hello = 29;
label.EnterScope("file");
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Minimal);
Assert.False(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
});
}
[Fact]
public void ModifyListElement2()
{
Run<RoamingAndExe>("ModifyListElement2", (config, label) =>
{
var my = config.Sections["my"] as MySection;
AssertNotModified(my, label);
my.Test.Hello = 29;
label.EnterScope("file");
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Modified);
Assert.True(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
}, (nav, label) =>
{
AssertListElement(nav, label);
});
}
[Fact]
public void TestElementWithCollection()
{
Run<DefaultMachineConfig2>("TestElementWithCollection", (config, label) =>
{
label.EnterScope("section");
var my2 = config.Sections["my2"] as MySection2;
Assert.NotNull(my2);
Assert.NotNull(my2.Test);
Assert.NotNull(my2.Test.DefaultCollection);
Assert.Equal(0, my2.Test.DefaultCollection.Count);
label.LeaveScope();
my2.Test.DefaultCollection.AddElement();
my2.Element.Hello = 29;
label.EnterScope("file");
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Minimal);
Assert.True(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
}, (nav, label) =>
{
Assert.True(nav.HasChildren, label.Get());
var iter = nav.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter.Count);
Assert.True(iter.MoveNext(), label.Get());
var my = iter.Current;
label.EnterScope("my2");
Assert.Equal("my2", my.Name);
Assert.False(my.HasAttributes, label.Get());
Assert.True(my.HasChildren, label.Get());
label.EnterScope("children");
var iter2 = my.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter2.Count);
Assert.True(iter2.MoveNext(), label.Get());
var element = iter2.Current;
label.EnterScope("element");
Assert.Equal("element", element.Name);
Assert.False(element.HasChildren, label.Get());
Assert.True(element.HasAttributes, label.Get());
var attr = element.GetAttribute("Hello", string.Empty);
Assert.Equal("29", attr);
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
});
}
[Fact]
public void TestElementWithCollection2()
{
Run<DefaultMachineConfig2>("TestElementWithCollection2", (config, label) =>
{
label.EnterScope("section");
var my2 = config.Sections["my2"] as MySection2;
Assert.NotNull(my2);
Assert.NotNull(my2.Test);
Assert.NotNull(my2.Test.DefaultCollection);
Assert.Equal(0, my2.Test.DefaultCollection.Count);
label.LeaveScope();
var element = my2.Test.DefaultCollection.AddElement();
var element2 = element.Test.DefaultCollection.AddElement();
element2.Hello = 1;
label.EnterScope("file");
Assert.False(File.Exists(config.FilePath), label.Get());
config.Save(ConfigurationSaveMode.Minimal);
Assert.True(File.Exists(config.FilePath), label.Get());
label.LeaveScope();
}, (nav, label) =>
{
Assert.True(nav.HasChildren, label.Get());
var iter = nav.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter.Count);
Assert.True(iter.MoveNext(), label.Get());
var my = iter.Current;
label.EnterScope("my2");
Assert.Equal("my2", my.Name);
Assert.False(my.HasAttributes, label.Get());
Assert.True(my.HasChildren, label.Get());
label.EnterScope("children");
var iter2 = my.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter2.Count);
Assert.True(iter2.MoveNext(), label.Get());
var collection = iter2.Current;
label.EnterScope("collection");
Assert.Equal("collection", collection.Name);
Assert.True(collection.HasChildren, label.Get());
Assert.False(collection.HasAttributes, label.Get());
label.EnterScope("children");
var iter3 = collection.SelectChildren(XPathNodeType.Element);
Assert.Equal(1, iter3.Count);
Assert.True(iter3.MoveNext(), label.Get());
var element = iter3.Current;
label.EnterScope("element");
Assert.Equal("test", element.Name);
Assert.False(element.HasChildren, label.Get());
Assert.True(element.HasAttributes, label.Get());
var attr = element.GetAttribute("Hello", string.Empty);
Assert.Equal("1", attr);
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
label.LeaveScope();
});
}
#endregion
#region Configuration Classes
public class MyElement : ConfigurationElement
{
[ConfigurationProperty("Hello", DefaultValue = 8)]
public int Hello
{
get { return (int)base["Hello"]; }
set { base["Hello"] = value; }
}
[ConfigurationProperty("World", IsRequired = false)]
public int World
{
get { return (int)base["World"]; }
set { base["World"] = value; }
}
public new bool IsModified
{
get { return base.IsModified(); }
}
}
public class MyCollection<T> : ConfigurationElementCollection
where T : ConfigurationElement, new()
{
#region implemented abstract members of ConfigurationElementCollection
protected override ConfigurationElement CreateNewElement()
{
return new T();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((T)element).GetHashCode();
}
#endregion
public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.BasicMap;
}
}
public T AddElement()
{
var element = new T();
BaseAdd(element);
return element;
}
public void RemoveElement(T element)
{
BaseRemove(GetElementKey(element));
}
public new bool IsModified
{
get { return base.IsModified(); }
}
}
public class MyCollectionElement<T> : ConfigurationElement
where T : ConfigurationElement, new()
{
[ConfigurationProperty("",
Options = ConfigurationPropertyOptions.IsDefaultCollection,
IsDefaultCollection = true)]
public MyCollection<T> DefaultCollection
{
get { return (MyCollection<T>)this[string.Empty]; }
set { this[string.Empty] = value; }
}
[ConfigurationProperty("collection", Options = ConfigurationPropertyOptions.None)]
public MyCollection<T> Collection
{
get { return (MyCollection<T>)this["collection"]; }
set { this["collection"] = value; }
}
public new bool IsModified
{
get { return base.IsModified(); }
}
}
public class MySection : ConfigurationSection
{
[ConfigurationProperty("list", Options = ConfigurationPropertyOptions.None)]
public MyCollectionElement<MyElement> List
{
get { return (MyCollectionElement<MyElement>)this["list"]; }
}
[ConfigurationProperty("test", Options = ConfigurationPropertyOptions.None)]
public MyElement Test
{
get { return (MyElement)this["test"]; }
}
public new bool IsModified
{
get { return base.IsModified(); }
}
}
public class MyElementWithCollection : ConfigurationElement
{
[ConfigurationProperty("test")]
public MyCollectionElement<MyElement> Test
{
get { return (MyCollectionElement<MyElement>)this["test"]; }
}
}
public class MySection2 : ConfigurationSection
{
[ConfigurationProperty("collection", Options = ConfigurationPropertyOptions.None)]
public MyCollectionElement<MyElementWithCollection> Test
{
get { return (MyCollectionElement<MyElementWithCollection>)this["collection"]; }
}
[ConfigurationProperty("element", Options = ConfigurationPropertyOptions.None)]
public MyElement Element
{
get { return (MyElement)this["element"]; }
}
}
public class MySectionGroup : ConfigurationSectionGroup
{
public MySection2 My2
{
get { return (MySection2)Sections["my2"]; }
}
}
#endregion
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/Common/tests/System/Xml/ModuleCore/ccommon.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;
namespace OLEDB.Test.ModuleCore
{
////////////////////////////////////////////////////////////////
// Common
//
////////////////////////////////////////////////////////////////
internal class Common
{
public static void Assert(bool condition)
{
Assert(condition, "Assertion Failed!", null);
}
public static void Assert(bool condition, string strCondition)
{
Assert(condition, strCondition, null);
}
public static void Assert(bool condition, string strCondition, string message)
{
Debug.Assert(condition, strCondition + message /*+ new StackTrace()*/);
}
public static void Trace(string message)
{
Console.WriteLine(message);
Debug.WriteLine(message);
}
public static string ToString(object value)
{
if (value == null)
return null;
return value.ToString();
}
public static string Format(object value)
{
if (value == null)
return "(null)";
if (value is string)
return "\"" + value + "\"";
return ToString(value);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
namespace OLEDB.Test.ModuleCore
{
////////////////////////////////////////////////////////////////
// Common
//
////////////////////////////////////////////////////////////////
internal class Common
{
public static void Assert(bool condition)
{
Assert(condition, "Assertion Failed!", null);
}
public static void Assert(bool condition, string strCondition)
{
Assert(condition, strCondition, null);
}
public static void Assert(bool condition, string strCondition, string message)
{
Debug.Assert(condition, strCondition + message /*+ new StackTrace()*/);
}
public static void Trace(string message)
{
Console.WriteLine(message);
Debug.WriteLine(message);
}
public static string ToString(object value)
{
if (value == null)
return null;
return value.ToString();
}
public static string Format(object value)
{
if (value == null)
return "(null)";
if (value is string)
return "\"" + value + "\"";
return ToString(value);
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/Common/src/Interop/Linux/OpenLdap/Interop.Ber.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using System.DirectoryServices.Protocols;
using System.Diagnostics;
internal static partial class Interop
{
internal static partial class Ldap
{
public const int ber_default_successful_return_code = 0;
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_alloc_t")]
public static partial IntPtr ber_alloc(int option);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_init")]
public static partial IntPtr ber_init(BerVal value);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_free")]
public static partial IntPtr ber_free(IntPtr berelement, int option);
public static int ber_printf_emptyarg(SafeBerHandle berElement, string format, nuint tag)
{
if (format == "{")
{
return ber_start_seq(berElement, tag);
}
else if (format == "}")
{
return ber_put_seq(berElement, tag);
}
else if (format == "[")
{
return ber_start_set(berElement, tag);
}
else if (format == "]")
{
return ber_put_set(berElement, tag);
}
else
{
Debug.Assert(format == "n");
return ber_put_null(berElement, tag);
}
}
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_start_seq")]
public static partial int ber_start_seq(SafeBerHandle berElement, nuint tag);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_start_set")]
public static partial int ber_start_set(SafeBerHandle berElement, nuint tag);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_put_seq")]
public static partial int ber_put_seq(SafeBerHandle berElement, nuint tag);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_put_set")]
public static partial int ber_put_set(SafeBerHandle berElement, nuint tag);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_put_null")]
public static partial int ber_put_null(SafeBerHandle berElement, nuint tag);
public static int ber_printf_int(SafeBerHandle berElement, string format, int value, nuint tag)
{
if (format == "i")
{
return ber_put_int(berElement, value, tag);
}
else if (format == "e")
{
return ber_put_enum(berElement, value, tag);
}
else
{
Debug.Assert(format == "b");
return ber_put_boolean(berElement, value, tag);
}
}
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_put_int")]
public static partial int ber_put_int(SafeBerHandle berElement, int value, nuint tag);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_put_enum")]
public static partial int ber_put_enum(SafeBerHandle berElement, int value, nuint tag);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_put_boolean")]
public static partial int ber_put_boolean(SafeBerHandle berElement, int value, nuint tag);
public static int ber_printf_bytearray(SafeBerHandle berElement, string format, HGlobalMemHandle value, nuint length, nuint tag)
{
if (format == "o")
{
return ber_put_ostring(berElement, value, length, tag);
}
else if (format == "s")
{
return ber_put_string(berElement, value, tag);
}
else
{
Debug.Assert(format == "X");
return ber_put_bitstring(berElement, value, length, tag);
}
}
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_put_ostring")]
private static partial int ber_put_ostring(SafeBerHandle berElement, HGlobalMemHandle value, nuint length, nuint tag);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_put_string")]
private static partial int ber_put_string(SafeBerHandle berElement, HGlobalMemHandle value, nuint tag);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_put_bitstring")]
private static partial int ber_put_bitstring(SafeBerHandle berElement, HGlobalMemHandle value, nuint length, nuint tag);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_flatten")]
public static partial int ber_flatten(SafeBerHandle berElement, ref IntPtr value);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_bvfree")]
public static partial int ber_bvfree(IntPtr value);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_bvecfree")]
public static partial int ber_bvecfree(IntPtr value);
public static int ber_scanf_emptyarg(SafeBerHandle berElement, string format)
{
Debug.Assert(format == "{" || format == "}" || format == "[" || format == "]" || format == "n" || format == "x");
if (format == "{" || format == "[")
{
nuint len = 0;
return ber_skip_tag(berElement, ref len);
}
else if (format == "]" || format == "}")
{
return ber_default_successful_return_code;
}
else
{
Debug.Assert(format == "n" || format == "x");
return ber_get_null(berElement);
}
}
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_skip_tag")]
private static partial int ber_skip_tag(SafeBerHandle berElement, ref nuint len);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_get_null")]
private static partial int ber_get_null(SafeBerHandle berElement);
public static int ber_scanf_int(SafeBerHandle berElement, string format, ref int value)
{
if (format == "i")
{
return ber_get_int(berElement, ref value);
}
else if (format == "e")
{
return ber_get_enum(berElement, ref value);
}
else
{
Debug.Assert(format == "b");
return ber_get_boolean(berElement, ref value);
}
}
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_get_int")]
private static partial int ber_get_int(SafeBerHandle berElement, ref int value);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_get_enum")]
private static partial int ber_get_enum(SafeBerHandle berElement, ref int value);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_get_boolean")]
private static partial int ber_get_boolean(SafeBerHandle berElement, ref int value);
public static int ber_scanf_bitstring(SafeBerHandle berElement, string format, ref IntPtr value, ref uint bitLength)
{
Debug.Assert(format == "B");
nuint bitLengthAsNuint = 0;
int res = ber_get_stringb(berElement, ref value, ref bitLengthAsNuint);
bitLength = (uint)bitLengthAsNuint;
return res;
}
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_get_stringb")]
private static partial int ber_get_stringb(SafeBerHandle berElement, ref IntPtr value, ref nuint bitLength);
public static int ber_scanf_ptr(SafeBerHandle berElement, string format, ref IntPtr value)
{
Debug.Assert(format == "O");
return ber_get_stringal(berElement, ref value);
}
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_get_stringal")]
private static partial int ber_get_stringal(SafeBerHandle berElement, ref IntPtr value);
public static int ber_printf_berarray(SafeBerHandle berElement, string format, IntPtr value, nuint tag)
{
Debug.Assert(format == "v" || format == "V");
// V and v are not supported on Unix yet.
return -1;
}
public static int ber_scanf_multibytearray(SafeBerHandle berElement, string format, ref IntPtr value)
{
Debug.Assert(format == "v" || format == "V");
// V and v are not supported on Unix yet.
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.Runtime.InteropServices;
using System.DirectoryServices.Protocols;
using System.Diagnostics;
internal static partial class Interop
{
internal static partial class Ldap
{
public const int ber_default_successful_return_code = 0;
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_alloc_t")]
public static partial IntPtr ber_alloc(int option);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_init")]
public static partial IntPtr ber_init(BerVal value);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_free")]
public static partial IntPtr ber_free(IntPtr berelement, int option);
public static int ber_printf_emptyarg(SafeBerHandle berElement, string format, nuint tag)
{
if (format == "{")
{
return ber_start_seq(berElement, tag);
}
else if (format == "}")
{
return ber_put_seq(berElement, tag);
}
else if (format == "[")
{
return ber_start_set(berElement, tag);
}
else if (format == "]")
{
return ber_put_set(berElement, tag);
}
else
{
Debug.Assert(format == "n");
return ber_put_null(berElement, tag);
}
}
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_start_seq")]
public static partial int ber_start_seq(SafeBerHandle berElement, nuint tag);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_start_set")]
public static partial int ber_start_set(SafeBerHandle berElement, nuint tag);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_put_seq")]
public static partial int ber_put_seq(SafeBerHandle berElement, nuint tag);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_put_set")]
public static partial int ber_put_set(SafeBerHandle berElement, nuint tag);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_put_null")]
public static partial int ber_put_null(SafeBerHandle berElement, nuint tag);
public static int ber_printf_int(SafeBerHandle berElement, string format, int value, nuint tag)
{
if (format == "i")
{
return ber_put_int(berElement, value, tag);
}
else if (format == "e")
{
return ber_put_enum(berElement, value, tag);
}
else
{
Debug.Assert(format == "b");
return ber_put_boolean(berElement, value, tag);
}
}
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_put_int")]
public static partial int ber_put_int(SafeBerHandle berElement, int value, nuint tag);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_put_enum")]
public static partial int ber_put_enum(SafeBerHandle berElement, int value, nuint tag);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_put_boolean")]
public static partial int ber_put_boolean(SafeBerHandle berElement, int value, nuint tag);
public static int ber_printf_bytearray(SafeBerHandle berElement, string format, HGlobalMemHandle value, nuint length, nuint tag)
{
if (format == "o")
{
return ber_put_ostring(berElement, value, length, tag);
}
else if (format == "s")
{
return ber_put_string(berElement, value, tag);
}
else
{
Debug.Assert(format == "X");
return ber_put_bitstring(berElement, value, length, tag);
}
}
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_put_ostring")]
private static partial int ber_put_ostring(SafeBerHandle berElement, HGlobalMemHandle value, nuint length, nuint tag);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_put_string")]
private static partial int ber_put_string(SafeBerHandle berElement, HGlobalMemHandle value, nuint tag);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_put_bitstring")]
private static partial int ber_put_bitstring(SafeBerHandle berElement, HGlobalMemHandle value, nuint length, nuint tag);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_flatten")]
public static partial int ber_flatten(SafeBerHandle berElement, ref IntPtr value);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_bvfree")]
public static partial int ber_bvfree(IntPtr value);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_bvecfree")]
public static partial int ber_bvecfree(IntPtr value);
public static int ber_scanf_emptyarg(SafeBerHandle berElement, string format)
{
Debug.Assert(format == "{" || format == "}" || format == "[" || format == "]" || format == "n" || format == "x");
if (format == "{" || format == "[")
{
nuint len = 0;
return ber_skip_tag(berElement, ref len);
}
else if (format == "]" || format == "}")
{
return ber_default_successful_return_code;
}
else
{
Debug.Assert(format == "n" || format == "x");
return ber_get_null(berElement);
}
}
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_skip_tag")]
private static partial int ber_skip_tag(SafeBerHandle berElement, ref nuint len);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_get_null")]
private static partial int ber_get_null(SafeBerHandle berElement);
public static int ber_scanf_int(SafeBerHandle berElement, string format, ref int value)
{
if (format == "i")
{
return ber_get_int(berElement, ref value);
}
else if (format == "e")
{
return ber_get_enum(berElement, ref value);
}
else
{
Debug.Assert(format == "b");
return ber_get_boolean(berElement, ref value);
}
}
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_get_int")]
private static partial int ber_get_int(SafeBerHandle berElement, ref int value);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_get_enum")]
private static partial int ber_get_enum(SafeBerHandle berElement, ref int value);
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_get_boolean")]
private static partial int ber_get_boolean(SafeBerHandle berElement, ref int value);
public static int ber_scanf_bitstring(SafeBerHandle berElement, string format, ref IntPtr value, ref uint bitLength)
{
Debug.Assert(format == "B");
nuint bitLengthAsNuint = 0;
int res = ber_get_stringb(berElement, ref value, ref bitLengthAsNuint);
bitLength = (uint)bitLengthAsNuint;
return res;
}
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_get_stringb")]
private static partial int ber_get_stringb(SafeBerHandle berElement, ref IntPtr value, ref nuint bitLength);
public static int ber_scanf_ptr(SafeBerHandle berElement, string format, ref IntPtr value)
{
Debug.Assert(format == "O");
return ber_get_stringal(berElement, ref value);
}
[GeneratedDllImport(Libraries.OpenLdap, EntryPoint = "ber_get_stringal")]
private static partial int ber_get_stringal(SafeBerHandle berElement, ref IntPtr value);
public static int ber_printf_berarray(SafeBerHandle berElement, string format, IntPtr value, nuint tag)
{
Debug.Assert(format == "v" || format == "V");
// V and v are not supported on Unix yet.
return -1;
}
public static int ber_scanf_multibytearray(SafeBerHandle berElement, string format, ref IntPtr value)
{
Debug.Assert(format == "v" || format == "V");
// V and v are not supported on Unix yet.
return -1;
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/Methodical/MDArray/InnerProd/classarr.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//Inner Product of two 2D array
using System;
public class ArrayClass
{
public int[,] a2d;
public int[,,] a3d;
public ArrayClass(int size)
{
a2d = new int[size, size];
a3d = new int[size, size, size];
}
}
public class intmm
{
public static int size;
public static Random rand;
public const int DefaultSeed = 20010415;
public static ArrayClass ima;
public static ArrayClass imb;
public static ArrayClass imr;
public static void Init2DMatrix(out ArrayClass m, out int[][] refm)
{
int i, j, temp;
i = 0;
//m = new int[size, size];
m = new ArrayClass(size);
refm = new int[size][];
for (int k = 0; k < refm.Length; k++)
refm[k] = new int[size];
while (i < size)
{
j = 0;
while (j < size)
{
temp = rand.Next();
m.a2d[i, j] = temp - (temp / 120) * 120 - 60;
refm[i][j] = temp - (temp / 120) * 120 - 60;
j++;
}
i++;
}
}
public static void InnerProduct2D(out int res, ref ArrayClass a2d, ref ArrayClass b, int row, int col)
{
int i;
res = 0;
i = 0;
while (i < size)
{
res = res + a2d.a2d[row, i] * b.a2d[i, col];
i++;
}
}
public static void InnerProduct2DRef(out int res, ref int[][] a2d, ref int[][] b, int row, int col)
{
int i;
res = 0;
i = 0;
while (i < size)
{
res = res + a2d[row][i] * b[i][col];
i++;
}
}
public static void Init3DMatrix(ArrayClass m, int[][] refm)
{
int i, j, temp;
i = 0;
while (i < size)
{
j = 0;
while (j < size)
{
temp = rand.Next();
m.a3d[i, j, 0] = temp - (temp / 120) * 120 - 60;
refm[i][j] = temp - (temp / 120) * 120 - 60;
j++;
}
i++;
}
}
public static void InnerProduct3D(out int res, ArrayClass a3d, ArrayClass b, int row, int col)
{
int i;
res = 0;
i = 0;
while (i < size)
{
res = res + a3d.a3d[row, i, 0] * b.a3d[i, col, 0];
i++;
}
}
public static void InnerProduct3DRef(out int res, int[][] a3d, int[][] b, int row, int col)
{
int i;
res = 0;
i = 0;
while (i < size)
{
res = res + a3d[row][i] * b[i][col];
i++;
}
}
public static int Main()
{
bool pass = false;
int seed = Environment.GetEnvironmentVariable("CORECLR_SEED") switch
{
string seedStr when seedStr.Equals("random", StringComparison.OrdinalIgnoreCase) => new Random().Next(),
string seedStr when int.TryParse(seedStr, out int envSeed) => envSeed,
_ => DefaultSeed
};
rand = new Random(seed);
size = rand.Next(2, 10);
Console.WriteLine();
Console.WriteLine("2D Array");
Console.WriteLine("Random seed: {0}; set environment variable CORECLR_SEED to this value to reproduce", seed);
Console.WriteLine("Testing inner product of {0} by {0} matrices", size);
Console.WriteLine("the matrices are members of class");
Console.WriteLine("Matrix element stores random integer");
Console.WriteLine("array set/get, ref/out param are used");
ima = new ArrayClass(size);
imb = new ArrayClass(size);
imr = new ArrayClass(size);
int[][] refa2d = new int[size][];
int[][] refb2d = new int[size][];
int[][] refr2d = new int[size][];
for (int k = 0; k < refr2d.Length; k++)
refr2d[k] = new int[size];
Init2DMatrix(out ima, out refa2d);
Init2DMatrix(out imb, out refb2d);
int m = 0;
int n = 0;
while (m < size)
{
n = 0;
while (n < size)
{
InnerProduct2D(out imr.a2d[m, n], ref ima, ref imb, m, n);
InnerProduct2DRef(out refr2d[m][n], ref refa2d, ref refb2d, m, n);
n++;
}
m++;
}
for (int i = 0; i < size; i++)
{
pass = true;
for (int j = 0; j < size; j++)
if (imr.a2d[i, j] != refr2d[i][j])
{
Console.WriteLine("i={0}, j={1}, imr.a2d[i,j] {2}!=refr2d[i][j] {3}", i, j, imr.a2d[i, j], refr2d[i][j]);
pass = false;
}
}
Console.WriteLine();
Console.WriteLine("3D Array");
Console.WriteLine("Testing inner product of one slice of two {0} by {0} by {0} matrices", size);
Console.WriteLine("the matrices are members of class and matrix element stores random integer");
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
imr.a3d[i, j, 0] = 1;
int[][] refa3d = new int[size][];
int[][] refb3d = new int[size][];
int[][] refr3d = new int[size][];
for (int k = 0; k < refa3d.Length; k++)
refa3d[k] = new int[size];
for (int k = 0; k < refb3d.Length; k++)
refb3d[k] = new int[size];
for (int k = 0; k < refr3d.Length; k++)
refr3d[k] = new int[size];
Init3DMatrix(ima, refa3d);
Init3DMatrix(imb, refb3d);
m = 0;
n = 0;
while (m < size)
{
n = 0;
while (n < size)
{
InnerProduct3D(out imr.a3d[m, n, 0], ima, imb, m, n);
InnerProduct3DRef(out refr3d[m][n], refa3d, refb3d, m, n);
n++;
}
m++;
}
for (int i = 0; i < size; i++)
{
pass = true;
for (int j = 0; j < size; j++)
if (imr.a3d[i, j, 0] != refr3d[i][j])
{
Console.WriteLine("i={0}, j={1}, imr.a3d[i,j,0] {2}!=refr3d[i][j] {3}", i, j, imr.a3d[i, j, 0], refr3d[i][j]);
pass = false;
}
}
Console.WriteLine();
if (pass)
{
Console.WriteLine("PASSED");
return 100;
}
else
{
Console.WriteLine("FAILED");
return 1;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//Inner Product of two 2D array
using System;
public class ArrayClass
{
public int[,] a2d;
public int[,,] a3d;
public ArrayClass(int size)
{
a2d = new int[size, size];
a3d = new int[size, size, size];
}
}
public class intmm
{
public static int size;
public static Random rand;
public const int DefaultSeed = 20010415;
public static ArrayClass ima;
public static ArrayClass imb;
public static ArrayClass imr;
public static void Init2DMatrix(out ArrayClass m, out int[][] refm)
{
int i, j, temp;
i = 0;
//m = new int[size, size];
m = new ArrayClass(size);
refm = new int[size][];
for (int k = 0; k < refm.Length; k++)
refm[k] = new int[size];
while (i < size)
{
j = 0;
while (j < size)
{
temp = rand.Next();
m.a2d[i, j] = temp - (temp / 120) * 120 - 60;
refm[i][j] = temp - (temp / 120) * 120 - 60;
j++;
}
i++;
}
}
public static void InnerProduct2D(out int res, ref ArrayClass a2d, ref ArrayClass b, int row, int col)
{
int i;
res = 0;
i = 0;
while (i < size)
{
res = res + a2d.a2d[row, i] * b.a2d[i, col];
i++;
}
}
public static void InnerProduct2DRef(out int res, ref int[][] a2d, ref int[][] b, int row, int col)
{
int i;
res = 0;
i = 0;
while (i < size)
{
res = res + a2d[row][i] * b[i][col];
i++;
}
}
public static void Init3DMatrix(ArrayClass m, int[][] refm)
{
int i, j, temp;
i = 0;
while (i < size)
{
j = 0;
while (j < size)
{
temp = rand.Next();
m.a3d[i, j, 0] = temp - (temp / 120) * 120 - 60;
refm[i][j] = temp - (temp / 120) * 120 - 60;
j++;
}
i++;
}
}
public static void InnerProduct3D(out int res, ArrayClass a3d, ArrayClass b, int row, int col)
{
int i;
res = 0;
i = 0;
while (i < size)
{
res = res + a3d.a3d[row, i, 0] * b.a3d[i, col, 0];
i++;
}
}
public static void InnerProduct3DRef(out int res, int[][] a3d, int[][] b, int row, int col)
{
int i;
res = 0;
i = 0;
while (i < size)
{
res = res + a3d[row][i] * b[i][col];
i++;
}
}
public static int Main()
{
bool pass = false;
int seed = Environment.GetEnvironmentVariable("CORECLR_SEED") switch
{
string seedStr when seedStr.Equals("random", StringComparison.OrdinalIgnoreCase) => new Random().Next(),
string seedStr when int.TryParse(seedStr, out int envSeed) => envSeed,
_ => DefaultSeed
};
rand = new Random(seed);
size = rand.Next(2, 10);
Console.WriteLine();
Console.WriteLine("2D Array");
Console.WriteLine("Random seed: {0}; set environment variable CORECLR_SEED to this value to reproduce", seed);
Console.WriteLine("Testing inner product of {0} by {0} matrices", size);
Console.WriteLine("the matrices are members of class");
Console.WriteLine("Matrix element stores random integer");
Console.WriteLine("array set/get, ref/out param are used");
ima = new ArrayClass(size);
imb = new ArrayClass(size);
imr = new ArrayClass(size);
int[][] refa2d = new int[size][];
int[][] refb2d = new int[size][];
int[][] refr2d = new int[size][];
for (int k = 0; k < refr2d.Length; k++)
refr2d[k] = new int[size];
Init2DMatrix(out ima, out refa2d);
Init2DMatrix(out imb, out refb2d);
int m = 0;
int n = 0;
while (m < size)
{
n = 0;
while (n < size)
{
InnerProduct2D(out imr.a2d[m, n], ref ima, ref imb, m, n);
InnerProduct2DRef(out refr2d[m][n], ref refa2d, ref refb2d, m, n);
n++;
}
m++;
}
for (int i = 0; i < size; i++)
{
pass = true;
for (int j = 0; j < size; j++)
if (imr.a2d[i, j] != refr2d[i][j])
{
Console.WriteLine("i={0}, j={1}, imr.a2d[i,j] {2}!=refr2d[i][j] {3}", i, j, imr.a2d[i, j], refr2d[i][j]);
pass = false;
}
}
Console.WriteLine();
Console.WriteLine("3D Array");
Console.WriteLine("Testing inner product of one slice of two {0} by {0} by {0} matrices", size);
Console.WriteLine("the matrices are members of class and matrix element stores random integer");
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
imr.a3d[i, j, 0] = 1;
int[][] refa3d = new int[size][];
int[][] refb3d = new int[size][];
int[][] refr3d = new int[size][];
for (int k = 0; k < refa3d.Length; k++)
refa3d[k] = new int[size];
for (int k = 0; k < refb3d.Length; k++)
refb3d[k] = new int[size];
for (int k = 0; k < refr3d.Length; k++)
refr3d[k] = new int[size];
Init3DMatrix(ima, refa3d);
Init3DMatrix(imb, refb3d);
m = 0;
n = 0;
while (m < size)
{
n = 0;
while (n < size)
{
InnerProduct3D(out imr.a3d[m, n, 0], ima, imb, m, n);
InnerProduct3DRef(out refr3d[m][n], refa3d, refb3d, m, n);
n++;
}
m++;
}
for (int i = 0; i < size; i++)
{
pass = true;
for (int j = 0; j < size; j++)
if (imr.a3d[i, j, 0] != refr3d[i][j])
{
Console.WriteLine("i={0}, j={1}, imr.a3d[i,j,0] {2}!=refr3d[i][j] {3}", i, j, imr.a3d[i, j, 0], refr3d[i][j]);
pass = false;
}
}
Console.WriteLine();
if (pass)
{
Console.WriteLine("PASSED");
return 100;
}
else
{
Console.WriteLine("FAILED");
return 1;
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Runtime.Extensions/tests/System/Environment.ProcessorCount.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;
using System.Runtime.InteropServices;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Tests
{
public class EnvironmentProcessorCount
{
private const string ProcessorCountEnvVar = "DOTNET_PROCESSOR_COUNT";
[Fact]
public void ProcessorCount_IsPositive()
{
Assert.InRange(Environment.ProcessorCount, 1, int.MaxValue);
}
private static unsafe int ParseProcessorCount(string settingValue)
{
const uint MAX_PROCESSOR_COUNT = 0xffff;
if (string.IsNullOrEmpty(settingValue))
return 0;
// Mimic handling the setting's value in coreclr's GetCurrentProcessCpuCount
fixed (char *ptr = settingValue)
{
char *endptr;
int value = (int)wcstoul(ptr, &endptr, 10);
if (0 < value && value <= MAX_PROCESSOR_COUNT)
return value;
}
return 0;
}
private static int GetTotalProcessorCount()
{
// Assume a single CPU group
GetSystemInfo(out SYSTEM_INFO sysInfo);
return (int)sysInfo.dwNumberOfProcessors;
}
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get processor information
[Fact]
public void ProcessorCount_Windows_MatchesGetSystemInfo()
{
string procCountConfig = Environment.GetEnvironmentVariable(ProcessorCountEnvVar);
int expectedCount = ParseProcessorCount(procCountConfig);
// Assume no process affinity or CPU quota set
if (expectedCount == 0)
expectedCount = GetTotalProcessorCount();
Assert.Equal(expectedCount, Environment.ProcessorCount);
}
public static int GetProcessorCount() => Environment.ProcessorCount;
[PlatformSpecific(TestPlatforms.Windows)]
[Theory]
[ActiveIssue("https://github.com/dotnet/runtime/issues/52910", TestRuntimes.Mono)]
[InlineData(8000, 0, null)]
[InlineData(8000, 2000, null)]
[InlineData(8000, 0, "1")]
[InlineData(2000, 0, null)]
[InlineData(2000, 0, " 17 ")]
[InlineData(0, 0, "3")]
public static unsafe void ProcessorCount_Windows_RespectsJobCpuRateAndConfigurationSetting(
ushort maxRate, ushort minRate, string procCountConfig)
{
IntPtr hJob = IntPtr.Zero;
PROCESS_INFORMATION processInfo = default;
string savedProcCountConfig = Environment.GetEnvironmentVariable(ProcessorCountEnvVar);
try
{
hJob = CreateJobObject(IntPtr.Zero, null);
JOBOBJECT_CPU_RATE_CONTROL_INFORMATION cpuRateControl = default;
if (maxRate != 0)
{
// Setting JobObjectCpuRateControlInformation requires Windows 8 or later
if (!PlatformDetection.IsWindows8xOrLater)
return;
if (minRate == 0)
{
cpuRateControl.ControlFlags =
JobObjectCpuRateControlFlags.JOB_OBJECT_CPU_RATE_CONTROL_ENABLE |
JobObjectCpuRateControlFlags.JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP;
cpuRateControl.CpuRate = maxRate;
}
else
{
// Setting min and max rates requires Windows 10 or later
if (!PlatformDetection.IsWindows10OrLater)
return;
cpuRateControl.ControlFlags =
JobObjectCpuRateControlFlags.JOB_OBJECT_CPU_RATE_CONTROL_ENABLE |
JobObjectCpuRateControlFlags.JOB_OBJECT_CPU_RATE_CONTROL_MIN_MAX_RATE;
cpuRateControl.MinRate = minRate;
cpuRateControl.MaxRate = maxRate;
}
if (!SetInformationJobObject(
hJob, JOBOBJECTINFOCLASS.JobObjectCpuRateControlInformation, (IntPtr)(&cpuRateControl), (uint)Marshal.SizeOf(cpuRateControl)))
throw new Win32Exception();
}
ProcessStartInfo startInfo;
using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(GetProcessorCount, new RemoteInvokeOptions { Start = false }))
{
startInfo = handle.Process.StartInfo;
handle.Process.Dispose();
handle.Process = null;
}
STARTUPINFO startupInfo = new() { cb = (uint)Marshal.SizeOf<STARTUPINFO>() };
Environment.SetEnvironmentVariable(ProcessorCountEnvVar, procCountConfig);
if (!CreateProcess(
startInfo.FileName, $"\"{startInfo.FileName}\" {startInfo.Arguments}",
IntPtr.Zero, IntPtr.Zero, false, CREATE_SUSPENDED,
IntPtr.Zero, null, ref startupInfo, out processInfo))
throw new Win32Exception();
if (!AssignProcessToJobObject(hJob, processInfo.hProcess))
throw new Win32Exception();
uint result = ResumeThread(processInfo.hThread);
if (result == RESUME_THREAD_FAILED)
throw new Win32Exception();
const uint WaitTime = 3 * 60 * 1000; // Three minutes
result = WaitForSingleObject(processInfo.hProcess, WaitTime);
if (result == WAIT_FAILED)
throw new Win32Exception();
if (result != WAIT_OBJECT_0)
throw new Exception("Error waiting for the child process");
if (!GetExitCodeProcess(processInfo.hProcess, out uint exitCode))
throw new Win32Exception();
int expectedCount = ParseProcessorCount(procCountConfig);
if (expectedCount == 0)
{
int totalProcCount = GetTotalProcessorCount();
if (maxRate == 0)
expectedCount = totalProcCount;
else
expectedCount = (maxRate * totalProcCount + 9999) / 10000;
}
Assert.Equal(expectedCount, (int)exitCode);
}
finally
{
Environment.SetEnvironmentVariable(ProcessorCountEnvVar, savedProcCountConfig);
if (processInfo.hProcess != IntPtr.Zero)
{
TerminateProcess(processInfo.hProcess, unchecked((uint)(-1)));
CloseHandle(processInfo.hProcess);
}
if (processInfo.hThread != IntPtr.Zero)
CloseHandle(processInfo.hThread);
if (hJob != IntPtr.Zero)
CloseHandle(hJob);
}
}
[DllImport("msvcrt.dll")]
private static extern unsafe uint wcstoul(char *strSource, char **endptr, int @base);
[StructLayout(LayoutKind.Sequential)]
private struct SYSTEM_INFO
{
public ushort wProcessorArchitecture;
public ushort wReserved;
public uint dwPageSize;
public IntPtr lpMinimumApplicationAddress;
public IntPtr lpMaximumApplicationAddress;
public IntPtr dwActiveProcessorMask;
public uint dwNumberOfProcessors;
public uint dwProcessorType;
public uint dwAllocationGranularity;
public ushort wProcessorLevel;
public ushort wProcessorRevision;
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr CreateJobObject(IntPtr lpJobAttributes, string lpName);
[Flags]
private enum JobObjectCpuRateControlFlags : uint
{
JOB_OBJECT_CPU_RATE_CONTROL_ENABLE = 0x1,
JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP = 0x4,
JOB_OBJECT_CPU_RATE_CONTROL_MIN_MAX_RATE = 0x10,
}
private enum JOBOBJECTINFOCLASS
{
JobObjectCpuRateControlInformation = 15,
}
[StructLayout(LayoutKind.Explicit)]
private struct JOBOBJECT_CPU_RATE_CONTROL_INFORMATION
{
[FieldOffset(0)]
public JobObjectCpuRateControlFlags ControlFlags;
[FieldOffset(4)]
public uint CpuRate;
[FieldOffset(4)]
public uint Weight;
[FieldOffset(4)]
public ushort MinRate;
[FieldOffset(6)]
public ushort MaxRate;
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetInformationJobObject(
IntPtr hJob, JOBOBJECTINFOCLASS JobObjectInformationClass,
IntPtr lpJobObjectInformation, uint cbJobObjectInformationLength);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool QueryInformationJobObject(
IntPtr hJob, JOBOBJECTINFOCLASS JobObjectInformationClass,
IntPtr lpJobObjectInformation, uint cbJobObjectInformationLength, IntPtr lpReturnLength);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AssignProcessToJobObject(IntPtr hJob, IntPtr hProcess);
private const uint CREATE_SUSPENDED = 0x00000004;
private struct STARTUPINFO
{
public uint cb;
public IntPtr lpReserved;
public IntPtr lpDesktop;
public IntPtr lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public ushort wShowWindow;
public ushort cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
private struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CreateProcess(
string lpApplicationName,
string lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
bool bInheritHandles,
uint dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
[In] ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
private const uint RESUME_THREAD_FAILED = unchecked((uint)(-1));
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint ResumeThread(IntPtr hThread);
private const uint WAIT_OBJECT_0 = 0;
private const uint WAIT_FAILED = unchecked((uint)(-1));
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetExitCodeProcess(IntPtr hProcess, out uint lpExitCode);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool TerminateProcess(IntPtr hProcess, uint uExitCode);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
}
}
| // 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;
using System.Runtime.InteropServices;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Tests
{
public class EnvironmentProcessorCount
{
private const string ProcessorCountEnvVar = "DOTNET_PROCESSOR_COUNT";
[Fact]
public void ProcessorCount_IsPositive()
{
Assert.InRange(Environment.ProcessorCount, 1, int.MaxValue);
}
private static unsafe int ParseProcessorCount(string settingValue)
{
const uint MAX_PROCESSOR_COUNT = 0xffff;
if (string.IsNullOrEmpty(settingValue))
return 0;
// Mimic handling the setting's value in coreclr's GetCurrentProcessCpuCount
fixed (char *ptr = settingValue)
{
char *endptr;
int value = (int)wcstoul(ptr, &endptr, 10);
if (0 < value && value <= MAX_PROCESSOR_COUNT)
return value;
}
return 0;
}
private static int GetTotalProcessorCount()
{
// Assume a single CPU group
GetSystemInfo(out SYSTEM_INFO sysInfo);
return (int)sysInfo.dwNumberOfProcessors;
}
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get processor information
[Fact]
public void ProcessorCount_Windows_MatchesGetSystemInfo()
{
string procCountConfig = Environment.GetEnvironmentVariable(ProcessorCountEnvVar);
int expectedCount = ParseProcessorCount(procCountConfig);
// Assume no process affinity or CPU quota set
if (expectedCount == 0)
expectedCount = GetTotalProcessorCount();
Assert.Equal(expectedCount, Environment.ProcessorCount);
}
public static int GetProcessorCount() => Environment.ProcessorCount;
[PlatformSpecific(TestPlatforms.Windows)]
[Theory]
[ActiveIssue("https://github.com/dotnet/runtime/issues/52910", TestRuntimes.Mono)]
[InlineData(8000, 0, null)]
[InlineData(8000, 2000, null)]
[InlineData(8000, 0, "1")]
[InlineData(2000, 0, null)]
[InlineData(2000, 0, " 17 ")]
[InlineData(0, 0, "3")]
public static unsafe void ProcessorCount_Windows_RespectsJobCpuRateAndConfigurationSetting(
ushort maxRate, ushort minRate, string procCountConfig)
{
IntPtr hJob = IntPtr.Zero;
PROCESS_INFORMATION processInfo = default;
string savedProcCountConfig = Environment.GetEnvironmentVariable(ProcessorCountEnvVar);
try
{
hJob = CreateJobObject(IntPtr.Zero, null);
JOBOBJECT_CPU_RATE_CONTROL_INFORMATION cpuRateControl = default;
if (maxRate != 0)
{
// Setting JobObjectCpuRateControlInformation requires Windows 8 or later
if (!PlatformDetection.IsWindows8xOrLater)
return;
if (minRate == 0)
{
cpuRateControl.ControlFlags =
JobObjectCpuRateControlFlags.JOB_OBJECT_CPU_RATE_CONTROL_ENABLE |
JobObjectCpuRateControlFlags.JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP;
cpuRateControl.CpuRate = maxRate;
}
else
{
// Setting min and max rates requires Windows 10 or later
if (!PlatformDetection.IsWindows10OrLater)
return;
cpuRateControl.ControlFlags =
JobObjectCpuRateControlFlags.JOB_OBJECT_CPU_RATE_CONTROL_ENABLE |
JobObjectCpuRateControlFlags.JOB_OBJECT_CPU_RATE_CONTROL_MIN_MAX_RATE;
cpuRateControl.MinRate = minRate;
cpuRateControl.MaxRate = maxRate;
}
if (!SetInformationJobObject(
hJob, JOBOBJECTINFOCLASS.JobObjectCpuRateControlInformation, (IntPtr)(&cpuRateControl), (uint)Marshal.SizeOf(cpuRateControl)))
throw new Win32Exception();
}
ProcessStartInfo startInfo;
using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(GetProcessorCount, new RemoteInvokeOptions { Start = false }))
{
startInfo = handle.Process.StartInfo;
handle.Process.Dispose();
handle.Process = null;
}
STARTUPINFO startupInfo = new() { cb = (uint)Marshal.SizeOf<STARTUPINFO>() };
Environment.SetEnvironmentVariable(ProcessorCountEnvVar, procCountConfig);
if (!CreateProcess(
startInfo.FileName, $"\"{startInfo.FileName}\" {startInfo.Arguments}",
IntPtr.Zero, IntPtr.Zero, false, CREATE_SUSPENDED,
IntPtr.Zero, null, ref startupInfo, out processInfo))
throw new Win32Exception();
if (!AssignProcessToJobObject(hJob, processInfo.hProcess))
throw new Win32Exception();
uint result = ResumeThread(processInfo.hThread);
if (result == RESUME_THREAD_FAILED)
throw new Win32Exception();
const uint WaitTime = 3 * 60 * 1000; // Three minutes
result = WaitForSingleObject(processInfo.hProcess, WaitTime);
if (result == WAIT_FAILED)
throw new Win32Exception();
if (result != WAIT_OBJECT_0)
throw new Exception("Error waiting for the child process");
if (!GetExitCodeProcess(processInfo.hProcess, out uint exitCode))
throw new Win32Exception();
int expectedCount = ParseProcessorCount(procCountConfig);
if (expectedCount == 0)
{
int totalProcCount = GetTotalProcessorCount();
if (maxRate == 0)
expectedCount = totalProcCount;
else
expectedCount = (maxRate * totalProcCount + 9999) / 10000;
}
Assert.Equal(expectedCount, (int)exitCode);
}
finally
{
Environment.SetEnvironmentVariable(ProcessorCountEnvVar, savedProcCountConfig);
if (processInfo.hProcess != IntPtr.Zero)
{
TerminateProcess(processInfo.hProcess, unchecked((uint)(-1)));
CloseHandle(processInfo.hProcess);
}
if (processInfo.hThread != IntPtr.Zero)
CloseHandle(processInfo.hThread);
if (hJob != IntPtr.Zero)
CloseHandle(hJob);
}
}
[DllImport("msvcrt.dll")]
private static extern unsafe uint wcstoul(char *strSource, char **endptr, int @base);
[StructLayout(LayoutKind.Sequential)]
private struct SYSTEM_INFO
{
public ushort wProcessorArchitecture;
public ushort wReserved;
public uint dwPageSize;
public IntPtr lpMinimumApplicationAddress;
public IntPtr lpMaximumApplicationAddress;
public IntPtr dwActiveProcessorMask;
public uint dwNumberOfProcessors;
public uint dwProcessorType;
public uint dwAllocationGranularity;
public ushort wProcessorLevel;
public ushort wProcessorRevision;
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr CreateJobObject(IntPtr lpJobAttributes, string lpName);
[Flags]
private enum JobObjectCpuRateControlFlags : uint
{
JOB_OBJECT_CPU_RATE_CONTROL_ENABLE = 0x1,
JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP = 0x4,
JOB_OBJECT_CPU_RATE_CONTROL_MIN_MAX_RATE = 0x10,
}
private enum JOBOBJECTINFOCLASS
{
JobObjectCpuRateControlInformation = 15,
}
[StructLayout(LayoutKind.Explicit)]
private struct JOBOBJECT_CPU_RATE_CONTROL_INFORMATION
{
[FieldOffset(0)]
public JobObjectCpuRateControlFlags ControlFlags;
[FieldOffset(4)]
public uint CpuRate;
[FieldOffset(4)]
public uint Weight;
[FieldOffset(4)]
public ushort MinRate;
[FieldOffset(6)]
public ushort MaxRate;
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetInformationJobObject(
IntPtr hJob, JOBOBJECTINFOCLASS JobObjectInformationClass,
IntPtr lpJobObjectInformation, uint cbJobObjectInformationLength);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool QueryInformationJobObject(
IntPtr hJob, JOBOBJECTINFOCLASS JobObjectInformationClass,
IntPtr lpJobObjectInformation, uint cbJobObjectInformationLength, IntPtr lpReturnLength);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AssignProcessToJobObject(IntPtr hJob, IntPtr hProcess);
private const uint CREATE_SUSPENDED = 0x00000004;
private struct STARTUPINFO
{
public uint cb;
public IntPtr lpReserved;
public IntPtr lpDesktop;
public IntPtr lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public ushort wShowWindow;
public ushort cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
private struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CreateProcess(
string lpApplicationName,
string lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
bool bInheritHandles,
uint dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
[In] ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
private const uint RESUME_THREAD_FAILED = unchecked((uint)(-1));
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint ResumeThread(IntPtr hThread);
private const uint WAIT_OBJECT_0 = 0;
private const uint WAIT_FAILED = unchecked((uint)(-1));
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetExitCodeProcess(IntPtr hProcess, out uint lpExitCode);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool TerminateProcess(IntPtr hProcess, uint uExitCode);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/General/NotSupported/Vector64BooleanAsUInt32.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void Vector64BooleanAsUInt32()
{
bool succeeded = false;
try
{
Vector64<uint> result = default(Vector64<bool>).AsUInt32();
}
catch (NotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64BooleanAsUInt32: RunNotSupportedScenario failed to throw NotSupportedException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void Vector64BooleanAsUInt32()
{
bool succeeded = false;
try
{
Vector64<uint> result = default(Vector64<bool>).AsUInt32();
}
catch (NotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64BooleanAsUInt32: RunNotSupportedScenario failed to throw NotSupportedException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/X86/Bmi1.X64/BitFieldExtract.UInt64.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 BitFieldExtractUInt64()
{
var test = new ScalarBinaryOpTest__BitFieldExtractUInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.ReadUnaligned
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.ReadUnaligned
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.ReadUnaligned
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();
}
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 ScalarBinaryOpTest__BitFieldExtractUInt64
{
private struct TestStruct
{
public UInt64 _fld1;
public UInt16 _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
testStruct._fld1 = 0x1E00000000000000;
testStruct._fld2 = 0x0439;
return testStruct;
}
public void RunStructFldScenario(ScalarBinaryOpTest__BitFieldExtractUInt64 testClass)
{
var result = Bmi1.X64.BitFieldExtract(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
private static UInt64 _data1;
private static UInt16 _data2;
private static UInt64 _clsVar1;
private static UInt16 _clsVar2;
private UInt64 _fld1;
private UInt16 _fld2;
static ScalarBinaryOpTest__BitFieldExtractUInt64()
{
_clsVar1 = 0x1E00000000000000;
_clsVar2 = 0x0439;
}
public ScalarBinaryOpTest__BitFieldExtractUInt64()
{
Succeeded = true;
_fld1 = 0x1E00000000000000;
_fld2 = 0x0439;
_data1 = 0x1E00000000000000;
_data2 = 0x0439;
}
public bool IsSupported => Bmi1.X64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Bmi1.X64.BitFieldExtract(
Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1)),
Unsafe.ReadUnaligned<UInt16>(ref Unsafe.As<UInt16, byte>(ref _data2))
);
ValidateResult(_data1, _data2, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Bmi1.X64).GetMethod(nameof(Bmi1.X64.BitFieldExtract), new Type[] { typeof(UInt64), typeof(UInt16) })
.Invoke(null, new object[] {
Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1)),
Unsafe.ReadUnaligned<UInt16>(ref Unsafe.As<UInt16, byte>(ref _data2))
});
ValidateResult(_data1, _data2, (UInt64)result);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Bmi1.X64.BitFieldExtract(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var data1 = Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1));
var data2 = Unsafe.ReadUnaligned<UInt16>(ref Unsafe.As<UInt16, byte>(ref _data2));
var result = Bmi1.X64.BitFieldExtract(data1, data2);
ValidateResult(data1, data2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ScalarBinaryOpTest__BitFieldExtractUInt64();
var result = Bmi1.X64.BitFieldExtract(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Bmi1.X64.BitFieldExtract(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Bmi1.X64.BitFieldExtract(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);
}
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(UInt64 left, UInt16 right, UInt64 result, [CallerMemberName] string method = "")
{
var isUnexpectedResult = false;
ulong expectedResult = 15; isUnexpectedResult = (expectedResult != result);
if (isUnexpectedResult)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Bmi1.X64)}.{nameof(Bmi1.X64.BitFieldExtract)}<UInt64>(UInt64, UInt16): BitFieldExtract failed:");
TestLibrary.TestFramework.LogInformation($" left: {left}");
TestLibrary.TestFramework.LogInformation($" right: {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;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void BitFieldExtractUInt64()
{
var test = new ScalarBinaryOpTest__BitFieldExtractUInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.ReadUnaligned
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.ReadUnaligned
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.ReadUnaligned
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();
}
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 ScalarBinaryOpTest__BitFieldExtractUInt64
{
private struct TestStruct
{
public UInt64 _fld1;
public UInt16 _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
testStruct._fld1 = 0x1E00000000000000;
testStruct._fld2 = 0x0439;
return testStruct;
}
public void RunStructFldScenario(ScalarBinaryOpTest__BitFieldExtractUInt64 testClass)
{
var result = Bmi1.X64.BitFieldExtract(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
private static UInt64 _data1;
private static UInt16 _data2;
private static UInt64 _clsVar1;
private static UInt16 _clsVar2;
private UInt64 _fld1;
private UInt16 _fld2;
static ScalarBinaryOpTest__BitFieldExtractUInt64()
{
_clsVar1 = 0x1E00000000000000;
_clsVar2 = 0x0439;
}
public ScalarBinaryOpTest__BitFieldExtractUInt64()
{
Succeeded = true;
_fld1 = 0x1E00000000000000;
_fld2 = 0x0439;
_data1 = 0x1E00000000000000;
_data2 = 0x0439;
}
public bool IsSupported => Bmi1.X64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Bmi1.X64.BitFieldExtract(
Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1)),
Unsafe.ReadUnaligned<UInt16>(ref Unsafe.As<UInt16, byte>(ref _data2))
);
ValidateResult(_data1, _data2, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Bmi1.X64).GetMethod(nameof(Bmi1.X64.BitFieldExtract), new Type[] { typeof(UInt64), typeof(UInt16) })
.Invoke(null, new object[] {
Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1)),
Unsafe.ReadUnaligned<UInt16>(ref Unsafe.As<UInt16, byte>(ref _data2))
});
ValidateResult(_data1, _data2, (UInt64)result);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Bmi1.X64.BitFieldExtract(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var data1 = Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1));
var data2 = Unsafe.ReadUnaligned<UInt16>(ref Unsafe.As<UInt16, byte>(ref _data2));
var result = Bmi1.X64.BitFieldExtract(data1, data2);
ValidateResult(data1, data2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ScalarBinaryOpTest__BitFieldExtractUInt64();
var result = Bmi1.X64.BitFieldExtract(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Bmi1.X64.BitFieldExtract(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Bmi1.X64.BitFieldExtract(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);
}
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(UInt64 left, UInt16 right, UInt64 result, [CallerMemberName] string method = "")
{
var isUnexpectedResult = false;
ulong expectedResult = 15; isUnexpectedResult = (expectedResult != result);
if (isUnexpectedResult)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Bmi1.X64)}.{nameof(Bmi1.X64.BitFieldExtract)}<UInt64>(UInt64, UInt16): BitFieldExtract failed:");
TestLibrary.TestFramework.LogInformation($" left: {left}");
TestLibrary.TestFramework.LogInformation($" right: {right}");
TestLibrary.TestFramework.LogInformation($" result: {result}");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/CodeGenBringUpTests/Ne1_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="Ne1.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="Ne1.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Unit.Tests/System.Text.Json.SourceGeneration.Roslyn3.11.Unit.Tests.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<RoslynApiVersion>$(MicrosoftCodeAnalysisVersion_3_11)</RoslynApiVersion>
<IsHighAotMemoryUsageTest>true</IsHighAotMemoryUsageTest>
</PropertyGroup>
<ItemGroup>
<HighAotMemoryUsageAssembly Include="Microsoft.CodeAnalysis.CSharp.dll" />
</ItemGroup>
<Import Project="System.Text.Json.SourceGeneration.Unit.Tests.targets" />
<ItemGroup>
<ProjectReference Include="..\..\gen\System.Text.Json.SourceGeneration.Roslyn3.11.csproj" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<RoslynApiVersion>$(MicrosoftCodeAnalysisVersion_3_11)</RoslynApiVersion>
<IsHighAotMemoryUsageTest>true</IsHighAotMemoryUsageTest>
</PropertyGroup>
<ItemGroup>
<HighAotMemoryUsageAssembly Include="Microsoft.CodeAnalysis.CSharp.dll" />
</ItemGroup>
<Import Project="System.Text.Json.SourceGeneration.Unit.Tests.targets" />
<ItemGroup>
<ProjectReference Include="..\..\gen\System.Text.Json.SourceGeneration.Roslyn3.11.csproj" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/mono/mono/tests/verifier/unverifiable_void_ptr_store.cs | using System;
public unsafe class Driver {
static int foo;
static void * bla;
public static int Main (string[] args) {
void * test = (void*)foo;
bla = test;
return 1;
}
}
| using System;
public unsafe class Driver {
static int foo;
static void * bla;
public static int Main (string[] args) {
void * test = (void*)foo;
bla = test;
return 1;
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/coreclr/tools/Common/TypeSystem/Common/TypeDesc.ToString.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Internal.TypeSystem
{
partial class TypeDesc
{
public override string ToString()
{
return DebugNameFormatter.Instance.FormatName(this, DebugNameFormatter.FormatOptions.Default);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Internal.TypeSystem
{
partial class TypeDesc
{
public override string ToString()
{
return DebugNameFormatter.Instance.FormatName(this, DebugNameFormatter.FormatOptions.Default);
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Private.Xml.Linq/tests/xNodeReader/ClassStamp.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.IO;
using Microsoft.Test.ModuleCore;
using System.Xml.Linq;
using Xunit;
namespace CoreXml.Test.XLinq
{
public class FunctionalTests_XNodeReaderTests_TCRegressions1
{
[Fact]
public void IncorrentBehaviorOfReadAttributeValue()
{
string xml = @"<?xml version='1.0' encoding='utf-8' ?>
<!DOCTYPE text [
<!ATTLIST book id CDATA #REQUIRED>
<!ENTITY a '123'>
]>
<text id1='a 123 b' id2='2'/>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = DtdProcessing.Ignore;
using (XmlReader tr = XmlReader.Create(new StringReader(xml), rs))
{
using (XmlReader reader = XDocument.Load(tr).CreateReader())
{
reader.ReadToFollowing("text");
Assert.True(reader.MoveToNextAttribute());
Assert.Equal(XmlNodeType.Attribute, reader.NodeType);
Assert.Equal("id1", reader.Name);
Assert.Equal("a 123 b", reader.Value);
Assert.True(reader.ReadAttributeValue());
Assert.Equal(XmlNodeType.Text, reader.NodeType);
Assert.Equal("", reader.Name);
Assert.Equal("a 123 b", reader.Value);
Assert.True(reader.MoveToNextAttribute());
Assert.Equal(XmlNodeType.Attribute, reader.NodeType);
Assert.Equal("id2", reader.Name);
Assert.Equal("2", reader.Value);
Assert.True(reader.ReadAttributeValue());
Assert.Equal(XmlNodeType.Text, reader.NodeType);
Assert.Equal("", reader.Name);
Assert.Equal("2", reader.Value);
Assert.False(reader.MoveToNextAttribute());
Assert.Equal(XmlNodeType.Text, reader.NodeType);
Assert.Equal("", reader.Name);
Assert.Equal("2", reader.Value);
Assert.False(reader.ReadAttributeValue());
}
}
}
[Fact]
public void EnsureReadToFollowingMovesToAttributeAndNotToDtd()
{
string xml = @"<?xml version='1.0' encoding='utf-8' ?>
<!DOCTYPE text [
<!ATTLIST book id CDATA #REQUIRED>
<!ENTITY a '123'>
]>
<text id1='a 123 b' id2='2'/>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = DtdProcessing.Ignore;
using (XmlReader tr = XmlReader.Create(new StringReader(xml), rs))
{
using (XmlReader reader = XDocument.Load(tr).CreateReader())
{
reader.ReadToFollowing("text");
Assert.True(reader.MoveToNextAttribute());
Assert.True(reader.ReadAttributeValue());
Assert.Equal(XmlNodeType.Text, reader.NodeType);
Assert.Equal("", reader.Name);
Assert.Equal("a 123 b", reader.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.Xml;
using System.IO;
using Microsoft.Test.ModuleCore;
using System.Xml.Linq;
using Xunit;
namespace CoreXml.Test.XLinq
{
public class FunctionalTests_XNodeReaderTests_TCRegressions1
{
[Fact]
public void IncorrentBehaviorOfReadAttributeValue()
{
string xml = @"<?xml version='1.0' encoding='utf-8' ?>
<!DOCTYPE text [
<!ATTLIST book id CDATA #REQUIRED>
<!ENTITY a '123'>
]>
<text id1='a 123 b' id2='2'/>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = DtdProcessing.Ignore;
using (XmlReader tr = XmlReader.Create(new StringReader(xml), rs))
{
using (XmlReader reader = XDocument.Load(tr).CreateReader())
{
reader.ReadToFollowing("text");
Assert.True(reader.MoveToNextAttribute());
Assert.Equal(XmlNodeType.Attribute, reader.NodeType);
Assert.Equal("id1", reader.Name);
Assert.Equal("a 123 b", reader.Value);
Assert.True(reader.ReadAttributeValue());
Assert.Equal(XmlNodeType.Text, reader.NodeType);
Assert.Equal("", reader.Name);
Assert.Equal("a 123 b", reader.Value);
Assert.True(reader.MoveToNextAttribute());
Assert.Equal(XmlNodeType.Attribute, reader.NodeType);
Assert.Equal("id2", reader.Name);
Assert.Equal("2", reader.Value);
Assert.True(reader.ReadAttributeValue());
Assert.Equal(XmlNodeType.Text, reader.NodeType);
Assert.Equal("", reader.Name);
Assert.Equal("2", reader.Value);
Assert.False(reader.MoveToNextAttribute());
Assert.Equal(XmlNodeType.Text, reader.NodeType);
Assert.Equal("", reader.Name);
Assert.Equal("2", reader.Value);
Assert.False(reader.ReadAttributeValue());
}
}
}
[Fact]
public void EnsureReadToFollowingMovesToAttributeAndNotToDtd()
{
string xml = @"<?xml version='1.0' encoding='utf-8' ?>
<!DOCTYPE text [
<!ATTLIST book id CDATA #REQUIRED>
<!ENTITY a '123'>
]>
<text id1='a 123 b' id2='2'/>";
XmlReaderSettings rs = new XmlReaderSettings();
rs.DtdProcessing = DtdProcessing.Ignore;
using (XmlReader tr = XmlReader.Create(new StringReader(xml), rs))
{
using (XmlReader reader = XDocument.Load(tr).CreateReader())
{
reader.ReadToFollowing("text");
Assert.True(reader.MoveToNextAttribute());
Assert.True(reader.ReadAttributeValue());
Assert.Equal(XmlNodeType.Text, reader.NodeType);
Assert.Equal("", reader.Name);
Assert.Equal("a 123 b", reader.Value);
}
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/General/Vector256_1/GetAndWithElement.UInt64.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\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementUInt640()
{
var test = new VectorGetAndWithElement__GetAndWithElementUInt640();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementUInt640
{
private static readonly int LargestVectorSize = 32;
private static readonly int ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 0, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
UInt64[] values = new UInt64[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt64();
}
Vector256<UInt64> value = Vector256.Create(values[0], values[1], values[2], values[3]);
bool succeeded = !expectedOutOfRangeException;
try
{
UInt64 result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt64 insertedValue = TestLibrary.Generator.GetUInt64();
try
{
Vector256<UInt64> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 0, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
UInt64[] values = new UInt64[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt64();
}
Vector256<UInt64> value = Vector256.Create(values[0], values[1], values[2], values[3]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector256)
.GetMethod(nameof(Vector256.GetElement))
.MakeGenericMethod(typeof(UInt64))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((UInt64)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt64 insertedValue = TestLibrary.Generator.GetUInt64();
try
{
object result2 = typeof(Vector256)
.GetMethod(nameof(Vector256.WithElement))
.MakeGenericMethod(typeof(UInt64))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector256<UInt64>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(0 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(0 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(0 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(0 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(UInt64 result, UInt64[] values, [CallerMemberName] string method = "")
{
if (result != values[0])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.GetElement(0): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector256<UInt64> result, UInt64[] values, UInt64 insertedValue, [CallerMemberName] string method = "")
{
UInt64[] resultElements = new UInt64[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(UInt64[] result, UInt64[] values, UInt64 insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 0) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[0] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.WithElement(0): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
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\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementUInt640()
{
var test = new VectorGetAndWithElement__GetAndWithElementUInt640();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementUInt640
{
private static readonly int LargestVectorSize = 32;
private static readonly int ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 0, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
UInt64[] values = new UInt64[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt64();
}
Vector256<UInt64> value = Vector256.Create(values[0], values[1], values[2], values[3]);
bool succeeded = !expectedOutOfRangeException;
try
{
UInt64 result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt64 insertedValue = TestLibrary.Generator.GetUInt64();
try
{
Vector256<UInt64> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 0, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
UInt64[] values = new UInt64[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt64();
}
Vector256<UInt64> value = Vector256.Create(values[0], values[1], values[2], values[3]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector256)
.GetMethod(nameof(Vector256.GetElement))
.MakeGenericMethod(typeof(UInt64))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((UInt64)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt64 insertedValue = TestLibrary.Generator.GetUInt64();
try
{
object result2 = typeof(Vector256)
.GetMethod(nameof(Vector256.WithElement))
.MakeGenericMethod(typeof(UInt64))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector256<UInt64>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(0 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(0 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(0 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(0 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(UInt64 result, UInt64[] values, [CallerMemberName] string method = "")
{
if (result != values[0])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.GetElement(0): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector256<UInt64> result, UInt64[] values, UInt64 insertedValue, [CallerMemberName] string method = "")
{
UInt64[] resultElements = new UInt64[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(UInt64[] result, UInt64[] values, UInt64 insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 0) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[0] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt64.WithElement(0): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/CodeGenBringUpTests/FPRem_d.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>Full</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="FPRem.cs" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>Full</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="FPRem.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/General/Vector128_1/op_OnesComplement.Double.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void op_OnesComplementDouble()
{
var test = new VectorUnaryOpTest__op_OnesComplementDouble();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorUnaryOpTest__op_OnesComplementDouble
{
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 != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<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(VectorUnaryOpTest__op_OnesComplementDouble testClass)
{
var result = ~_fld1;
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 VectorUnaryOpTest__op_OnesComplementDouble()
{
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 VectorUnaryOpTest__op_OnesComplementDouble()
{
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 Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = ~Unsafe.Read<Vector128<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(Vector128<Double>).GetMethod("op_OnesComplement", 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 RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = ~_clsVar1;
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 = ~op1;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorUnaryOpTest__op_OnesComplementDouble();
var result = ~test._fld1;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = ~_fld1;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = ~test._fld1;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(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;
if (BitConverter.DoubleToInt64Bits(result[0]) != ~BitConverter.DoubleToInt64Bits(firstOp[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != ~BitConverter.DoubleToInt64Bits(firstOp[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.op_OnesComplement<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\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void op_OnesComplementDouble()
{
var test = new VectorUnaryOpTest__op_OnesComplementDouble();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorUnaryOpTest__op_OnesComplementDouble
{
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 != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<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(VectorUnaryOpTest__op_OnesComplementDouble testClass)
{
var result = ~_fld1;
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 VectorUnaryOpTest__op_OnesComplementDouble()
{
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 VectorUnaryOpTest__op_OnesComplementDouble()
{
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 Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = ~Unsafe.Read<Vector128<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(Vector128<Double>).GetMethod("op_OnesComplement", 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 RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = ~_clsVar1;
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 = ~op1;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorUnaryOpTest__op_OnesComplementDouble();
var result = ~test._fld1;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = ~_fld1;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = ~test._fld1;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(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;
if (BitConverter.DoubleToInt64Bits(result[0]) != ~BitConverter.DoubleToInt64Bits(firstOp[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != ~BitConverter.DoubleToInt64Bits(firstOp[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.op_OnesComplement<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 | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/CodeGenBringUpTests/DblSubConst_d.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>Full</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="DblSubConst.cs" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>Full</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="DblSubConst.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/GC/LargeMemory/API/gc/suppressfinalize.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<GCStressIncompatible>true</GCStressIncompatible>
<CLRTestExecutionArguments>2048</CLRTestExecutionArguments>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="suppressfinalize.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../../largeobject.csproj" />
<ProjectReference Include="../../memcheck.csproj" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<GCStressIncompatible>true</GCStressIncompatible>
<CLRTestExecutionArguments>2048</CLRTestExecutionArguments>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="suppressfinalize.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../../largeobject.csproj" />
<ProjectReference Include="../../memcheck.csproj" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/MultiplyBySelectedScalarWideningUpperAndSubtract.Vector128.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 MultiplyBySelectedScalarWideningUpperAndSubtract_Vector128_UInt16_Vector128_UInt16_7()
{
var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndSubtract_Vector128_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__MultiplyBySelectedScalarWideningUpperAndSubtract_Vector128_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 Vector128<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<Vector128<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<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__MultiplyBySelectedScalarWideningUpperAndSubtract_Vector128_UInt16_Vector128_UInt16_7 testClass)
{
var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndSubtract(_fld1, _fld2, _fld3, 7);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndSubtract_Vector128_UInt16_Vector128_UInt16_7 testClass)
{
fixed (Vector128<UInt32>* pFld1 = &_fld1)
fixed (Vector128<UInt16>* pFld2 = &_fld2)
fixed (Vector128<UInt16>* pFld3 = &_fld3)
{
var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndSubtract(
AdvSimd.LoadVector128((UInt32*)(pFld1)),
AdvSimd.LoadVector128((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<Vector128<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 Vector128<UInt16> _clsVar2;
private static Vector128<UInt16> _clsVar3;
private Vector128<UInt32> _fld1;
private Vector128<UInt16> _fld2;
private Vector128<UInt16> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndSubtract_Vector128_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<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<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__MultiplyBySelectedScalarWideningUpperAndSubtract_Vector128_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<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<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.MultiplyBySelectedScalarWideningUpperAndSubtract(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<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.MultiplyBySelectedScalarWideningUpperAndSubtract(
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((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.MultiplyBySelectedScalarWideningUpperAndSubtract), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt16>), typeof(Vector128<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<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.MultiplyBySelectedScalarWideningUpperAndSubtract), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt16>), typeof(Vector128<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((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.MultiplyBySelectedScalarWideningUpperAndSubtract(
_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 (Vector128<UInt16>* pClsVar2 = &_clsVar2)
fixed (Vector128<UInt16>* pClsVar3 = &_clsVar3)
{
var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndSubtract(
AdvSimd.LoadVector128((UInt32*)(pClsVar1)),
AdvSimd.LoadVector128((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<Vector128<UInt16>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray3Ptr);
var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndSubtract(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.LoadVector128((UInt16*)(_dataTable.inArray2Ptr));
var op3 = AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray3Ptr));
var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndSubtract(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__MultiplyBySelectedScalarWideningUpperAndSubtract_Vector128_UInt16_Vector128_UInt16_7();
var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndSubtract(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__MultiplyBySelectedScalarWideningUpperAndSubtract_Vector128_UInt16_Vector128_UInt16_7();
fixed (Vector128<UInt32>* pFld1 = &test._fld1)
fixed (Vector128<UInt16>* pFld2 = &test._fld2)
fixed (Vector128<UInt16>* pFld3 = &test._fld3)
{
var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndSubtract(
AdvSimd.LoadVector128((UInt32*)(pFld1)),
AdvSimd.LoadVector128((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.MultiplyBySelectedScalarWideningUpperAndSubtract(_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 (Vector128<UInt16>* pFld2 = &_fld2)
fixed (Vector128<UInt16>* pFld3 = &_fld3)
{
var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndSubtract(
AdvSimd.LoadVector128((UInt32*)(pFld1)),
AdvSimd.LoadVector128((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.MultiplyBySelectedScalarWideningUpperAndSubtract(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.MultiplyBySelectedScalarWideningUpperAndSubtract(
AdvSimd.LoadVector128((UInt32*)(&test._fld1)),
AdvSimd.LoadVector128((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, Vector128<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<Vector128<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.MultiplyByScalarWideningUpperAndSubtract(firstOp, secondOp, thirdOp[Imm], i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyBySelectedScalarWideningUpperAndSubtract)}<UInt32>(Vector128<UInt32>, Vector128<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 MultiplyBySelectedScalarWideningUpperAndSubtract_Vector128_UInt16_Vector128_UInt16_7()
{
var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndSubtract_Vector128_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__MultiplyBySelectedScalarWideningUpperAndSubtract_Vector128_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 Vector128<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<Vector128<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<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__MultiplyBySelectedScalarWideningUpperAndSubtract_Vector128_UInt16_Vector128_UInt16_7 testClass)
{
var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndSubtract(_fld1, _fld2, _fld3, 7);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndSubtract_Vector128_UInt16_Vector128_UInt16_7 testClass)
{
fixed (Vector128<UInt32>* pFld1 = &_fld1)
fixed (Vector128<UInt16>* pFld2 = &_fld2)
fixed (Vector128<UInt16>* pFld3 = &_fld3)
{
var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndSubtract(
AdvSimd.LoadVector128((UInt32*)(pFld1)),
AdvSimd.LoadVector128((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<Vector128<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 Vector128<UInt16> _clsVar2;
private static Vector128<UInt16> _clsVar3;
private Vector128<UInt32> _fld1;
private Vector128<UInt16> _fld2;
private Vector128<UInt16> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__MultiplyBySelectedScalarWideningUpperAndSubtract_Vector128_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<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<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__MultiplyBySelectedScalarWideningUpperAndSubtract_Vector128_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<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<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.MultiplyBySelectedScalarWideningUpperAndSubtract(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<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.MultiplyBySelectedScalarWideningUpperAndSubtract(
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((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.MultiplyBySelectedScalarWideningUpperAndSubtract), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt16>), typeof(Vector128<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<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.MultiplyBySelectedScalarWideningUpperAndSubtract), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt16>), typeof(Vector128<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((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.MultiplyBySelectedScalarWideningUpperAndSubtract(
_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 (Vector128<UInt16>* pClsVar2 = &_clsVar2)
fixed (Vector128<UInt16>* pClsVar3 = &_clsVar3)
{
var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndSubtract(
AdvSimd.LoadVector128((UInt32*)(pClsVar1)),
AdvSimd.LoadVector128((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<Vector128<UInt16>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray3Ptr);
var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndSubtract(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.LoadVector128((UInt16*)(_dataTable.inArray2Ptr));
var op3 = AdvSimd.LoadVector128((UInt16*)(_dataTable.inArray3Ptr));
var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndSubtract(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__MultiplyBySelectedScalarWideningUpperAndSubtract_Vector128_UInt16_Vector128_UInt16_7();
var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndSubtract(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__MultiplyBySelectedScalarWideningUpperAndSubtract_Vector128_UInt16_Vector128_UInt16_7();
fixed (Vector128<UInt32>* pFld1 = &test._fld1)
fixed (Vector128<UInt16>* pFld2 = &test._fld2)
fixed (Vector128<UInt16>* pFld3 = &test._fld3)
{
var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndSubtract(
AdvSimd.LoadVector128((UInt32*)(pFld1)),
AdvSimd.LoadVector128((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.MultiplyBySelectedScalarWideningUpperAndSubtract(_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 (Vector128<UInt16>* pFld2 = &_fld2)
fixed (Vector128<UInt16>* pFld3 = &_fld3)
{
var result = AdvSimd.MultiplyBySelectedScalarWideningUpperAndSubtract(
AdvSimd.LoadVector128((UInt32*)(pFld1)),
AdvSimd.LoadVector128((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.MultiplyBySelectedScalarWideningUpperAndSubtract(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.MultiplyBySelectedScalarWideningUpperAndSubtract(
AdvSimd.LoadVector128((UInt32*)(&test._fld1)),
AdvSimd.LoadVector128((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, Vector128<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<Vector128<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.MultiplyByScalarWideningUpperAndSubtract(firstOp, secondOp, thirdOp[Imm], i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyBySelectedScalarWideningUpperAndSubtract)}<UInt32>(Vector128<UInt32>, Vector128<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 | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/coreclr/tools/Common/Sorting/ISortableDataStructureAccessor.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.Threading.Tasks;
namespace ILCompiler
{
internal interface ISortableDataStructureAccessor<T, TDataStructure>
{
T GetElement(TDataStructure dataStructure, int i);
void SetElement(TDataStructure dataStructure, int i, T value);
void SwapElements(TDataStructure dataStructure, int i, int i2);
void Copy(TDataStructure source, int sourceIndex, T[] target, int destIndex, int length);
void Copy(T[] source, int sourceIndex, TDataStructure target, int destIndex, int length);
int GetLength(TDataStructure dataStructure);
}
}
| // 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.Threading.Tasks;
namespace ILCompiler
{
internal interface ISortableDataStructureAccessor<T, TDataStructure>
{
T GetElement(TDataStructure dataStructure, int i);
void SetElement(TDataStructure dataStructure, int i, T value);
void SwapElements(TDataStructure dataStructure, int i, int i2);
void Copy(TDataStructure source, int sourceIndex, T[] target, int destIndex, int length);
void Copy(T[] source, int sourceIndex, TDataStructure target, int destIndex, int length);
int GetLength(TDataStructure dataStructure);
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/jit64/valuetypes/nullable/box-unbox/null/box-unbox-null023.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 NotEmptyStructQ using is operator
// </Description>
// <RelatedBugs> </RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
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 ((NotEmptyStructQ?)o) == null;
}
private static int Main()
{
NotEmptyStructQ? 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.
// <Area> Nullable - Box-Unbox </Area>
// <Title> Nullable type with unbox box expr </Title>
// <Description>
// checking type of NotEmptyStructQ using is operator
// </Description>
// <RelatedBugs> </RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
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 ((NotEmptyStructQ?)o) == null;
}
private static int Main()
{
NotEmptyStructQ? s = null;
if (BoxUnboxToNQ(s) && BoxUnboxToQ(s) && BoxUnboxToNQGen(s) && BoxUnboxToQGen(s))
return ExitCode.Passed;
else
return ExitCode.Failed;
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.IO.Ports/tests/SerialPort/ReadTo.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.IO.PortsTests;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class ReadTo : PortsTest
{
//The number of random bytes to receive for read method testing
private const int DEFAULT_NUM_CHARS_TO_READ = 8;
//The number of new lines to insert into the string not including the one at the end
private const int DEFAULT_NUMBER_NEW_LINES = 2;
//The number of random bytes to receive for large input buffer testing
private const int LARGE_NUM_CHARS_TO_READ = 2048;
private const int MIN_NUM_NEWLINE_CHARS = 1;
private const int MAX_NUM_NEWLINE_CHARS = 5;
private enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered };
#region Test Cases
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void NewLine_Contains_nullChar()
{
VerifyRead(new ASCIIEncoding(), "\0");
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void NewLine_CR()
{
VerifyRead(new ASCIIEncoding(), "\r");
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void NewLine_LF()
{
VerifyRead(new ASCIIEncoding(), "\n");
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void NewLine_CRLF_RndStr()
{
VerifyRead(new ASCIIEncoding(), "\r\n");
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void NewLine_CRLF_CRStr()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Debug.WriteLine("Verifying read method with \\r\\n NewLine and a string containing just \\r");
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
VerifyReadTo(com1, com2, "TEST\r", "\r\n");
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void NewLine_CRLF_LFStr()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Debug.WriteLine("Verifying read method with \\r\\n NewLine and a string containing just \\n");
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
VerifyReadTo(com1, com2, "TEST\n", "\r\n");
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void NewLine_END()
{
VerifyRead(new ASCIIEncoding(), "END");
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ASCIIEncoding()
{
VerifyRead(new ASCIIEncoding(), GenRandomNewLine(true));
}
/*
public void UTF7Encoding()
{
VerifyRead(new System.Text.UTF7Encoding(), GenRandomNewLine(false));
}
*/
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void UTF8Encoding()
{
VerifyRead(new UTF8Encoding(), GenRandomNewLine(false));
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void UTF32Encoding()
{
VerifyRead(new UTF32Encoding(), GenRandomNewLine(false));
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void UnicodeEncoding()
{
VerifyRead(new UnicodeEncoding(), GenRandomNewLine(false));
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void LargeInputBuffer()
{
VerifyRead(LARGE_NUM_CHARS_TO_READ);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadToWriteLine_ASCII()
{
VerifyReadToWithWriteLine(new ASCIIEncoding(), GenRandomNewLine(true));
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadToWriteLine_UTF8()
{
VerifyReadToWithWriteLine(new UTF8Encoding(), GenRandomNewLine(true));
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadToWriteLine_UTF32()
{
VerifyReadToWithWriteLine(new UTF32Encoding(), GenRandomNewLine(true));
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadToWriteLine_Unicode()
{
VerifyReadToWithWriteLine(new UnicodeEncoding(), GenRandomNewLine(true));
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_ReadBufferedData()
{
int numBytesToRead = 32;
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Random rndGen = new Random(-55);
StringBuilder strBldrToWrite = new StringBuilder();
//Genrate random characters
for (int i = 0; i < numBytesToRead; i++)
{
strBldrToWrite.Append((char)rndGen.Next(40, 60));
}
int newLineIndex;
while (-1 != (newLineIndex = strBldrToWrite.ToString().IndexOf(com1.NewLine)))
{
strBldrToWrite[newLineIndex] = (char)rndGen.Next(40, 60);
}
com1.ReadTimeout = 500;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
strBldrToWrite.Append(com1.NewLine);
BufferData(com1, com2, strBldrToWrite.ToString());
PerformReadOnCom1FromCom2(com1, com2, strBldrToWrite.ToString(), com1.NewLine);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_IterativeReadBufferedData()
{
int numBytesToRead = 32;
VerifyRead(Encoding.ASCII, GenRandomNewLine(true), numBytesToRead, 1, ReadDataFromEnum.Buffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_ReadBufferedAndNonBufferedData()
{
int numBytesToRead = 32;
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Random rndGen = new Random(-55);
StringBuilder strBldrToWrite = new StringBuilder();
StringBuilder strBldrExpected = new StringBuilder();
//Genrate random characters
for (int i = 0; i < numBytesToRead; i++)
{
strBldrToWrite.Append((char)rndGen.Next(0, 256));
}
int newLineIndex;
while (-1 != (newLineIndex = strBldrToWrite.ToString().IndexOf(com1.NewLine)))
{
strBldrToWrite[newLineIndex] = (char)rndGen.Next(0, 256);
}
com1.ReadTimeout = 500;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
BufferData(com1, com2, strBldrToWrite.ToString());
strBldrExpected.Append(strBldrToWrite);
strBldrToWrite.Append(com1.NewLine);
strBldrExpected.Append(strBldrToWrite);
VerifyReadTo(com1, com2, strBldrToWrite.ToString(), strBldrExpected.ToString(), com1.NewLine);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_IterativeReadBufferedAndNonBufferedData()
{
int numBytesToRead = 3;
VerifyRead(Encoding.ASCII, GenRandomNewLine(true), numBytesToRead, 1, ReadDataFromEnum.BufferedAndNonBuffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void GreedyRead()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] charXmitBuffer = TCSupport.GetRandomChars(128, TCSupport.CharacterOptions.Surrogates);
byte[] byteXmitBuffer = new byte[1024];
char utf32Char = TCSupport.GenerateRandomCharNonSurrogate();
byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char });
int numBytes;
Debug.WriteLine("Verifying that ReadTo() will read everything from internal buffer and drivers buffer");
//Put the first byte of the utf32 encoder char in the last byte of this buffer
//when we read this later the buffer will have to be resized
byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0];
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length);
TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length);
//Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's
//internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so
//the other 3 bytes of the ut32 encoded char can be in the buffer
com1.Read(new char[1023], 0, 1023);
Assert.Equal(1, com1.BytesToRead);
com1.Encoding = Encoding.UTF32;
com2.Encoding = Encoding.UTF32;
com2.Write(utf32CharBytes, 1, 3);
com2.Write(charXmitBuffer, 0, charXmitBuffer.Length);
com2.WriteLine(string.Empty);
numBytes = Encoding.UTF32.GetByteCount(charXmitBuffer);
byte[] byteBuffer = Encoding.UTF32.GetBytes(charXmitBuffer);
char[] expectedChars = new char[1 + Encoding.UTF32.GetCharCount(byteBuffer)];
expectedChars[0] = utf32Char;
Encoding.UTF32.GetChars(byteBuffer, 0, byteBuffer.Length, expectedChars, 1);
TCSupport.WaitForReadBufferToLoad(com1, 4 + numBytes);
string rcvString = com1.ReadTo(com2.NewLine);
Assert.NotNull(rcvString);
Assert.Equal(expectedChars, rcvString.ToCharArray());
Assert.Equal(0, com1.BytesToRead);
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void NullNewLine()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying read method throws ArgumentExcpetion with a null NewLine string");
com.Open();
VerifyReadException(com, null, typeof(ArgumentNullException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void EmptyNewLine()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying read method throws ArgumentExcpetion with an empty NewLine string");
com.Open();
VerifyReadException(com, "", typeof(ArgumentException));
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void NewLineSubstring()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Debug.WriteLine("Verifying read method with sub strings of the new line appearing in the string being read");
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
string newLine = "asfg";
string newLineSubStrings = "a" + "as" + "asf" + "sfg" + "fg" + "g"; //All the substrings of newLine
string testStr = newLineSubStrings + "asfg" + newLineSubStrings;
VerifyReadTo(com1, com2, testStr, newLine);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_DataReceivedBeforeTimeout()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None);
string endString = "END";
ASyncRead asyncRead = new ASyncRead(com1, endString);
var asyncReadTask = new Task(asyncRead.Read);
char endChar = endString[0];
char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None);
Debug.WriteLine(
"Verifying that ReadTo(string) will read characters that have been received after the call to Read was made");
//Ensure the new line is not in charXmitBuffer
for (int i = 0; i < charXmitBuffer.Length; ++i)
{
//Se any appearances of a character in the new line string to some other char
if (endChar == charXmitBuffer[i])
{
charXmitBuffer[i] = notEndChar;
}
}
com1.Encoding = Encoding.UTF8;
com2.Encoding = Encoding.UTF8;
com1.ReadTimeout = 20000; // 20 seconds
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
asyncReadTask.Start();
asyncRead.ReadStartedEvent.WaitOne();
//This only tells us that the thread has started to execute code in the method
Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort
com2.Write(charXmitBuffer, 0, charXmitBuffer.Length);
com2.Write(endString);
asyncRead.ReadCompletedEvent.WaitOne();
if (null != asyncRead.Exception)
{
Fail("Err_04448ajhied Unexpected exception thrown from async read:\n{0}", asyncRead.Exception);
}
else if (null == asyncRead.Result || 0 == asyncRead.Result.Length)
{
Fail("Err_0158ahei Expected Read to read at least one character");
}
else
{
char[] charRcvBuffer = asyncRead.Result.ToCharArray();
if (charRcvBuffer.Length != charXmitBuffer.Length)
{
Fail("Err_051884ajoedo Expected Read to read {0} characters actually read {1}", charXmitBuffer.Length, charRcvBuffer.Length);
}
else
{
for (int i = 0; i < charXmitBuffer.Length; ++i)
{
if (charRcvBuffer[i] != charXmitBuffer[i])
{
Fail(
"Err_0518895akiezp Characters differ at {0} expected:{1}({2:X}) actual:{3}({4:X})", i,
charXmitBuffer[i], (int)charXmitBuffer[i], charRcvBuffer[i], (int)charRcvBuffer[i]);
}
}
}
}
VerifyReadTo(com1, com2, new string(charXmitBuffer), endString);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_Timeout()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None);
string endString = "END";
char endChar = endString[0];
char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None);
Debug.WriteLine("Verifying that ReadTo(string) works appropriately after TimeoutException has been thrown");
// Ensure the new line is not in charXmitBuffer
for (int i = 0; i < charXmitBuffer.Length; ++i)
{
// Set any appearances of a character in the new line string to some other char
if (endChar == charXmitBuffer[i])
{
charXmitBuffer[i] = notEndChar;
}
}
com1.Encoding = Encoding.Unicode;
com2.Encoding = Encoding.Unicode;
com1.ReadTimeout = 2000;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
com2.Write(charXmitBuffer, 0, charXmitBuffer.Length);
Assert.Throws<TimeoutException>(() => com1.ReadTo(endString));
Assert.Equal(2 * charXmitBuffer.Length, com1.BytesToRead);
com2.Write(endString);
string result = com1.ReadTo(endString);
char[] charRcvBuffer = result.ToCharArray();
Assert.Equal(charRcvBuffer, charXmitBuffer);
VerifyReadTo(com1, com2, new string(charXmitBuffer), endString);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_LargeBuffer()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
const int bufferSize = 2048;
char[] buffer = new char[bufferSize];
for (int i = 0; i < bufferSize; i++)
{
buffer[i] = (char)('A' + (i % 5));
}
const char endChar = 'Z';
string endString = new string(endChar, 1);
com1.BaudRate = 115200;
com2.BaudRate = 115200;
com1.Encoding = Encoding.Unicode;
com2.Encoding = Encoding.Unicode;
com2.ReadTimeout = 10000;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
Task writeToCom2Task = Task.Run(() => {
com1.Write(buffer, 0, bufferSize);
});
Assert.Throws<TimeoutException>(() => com2.ReadTo(endString));
writeToCom2Task.Wait();
com1.Write(endString);
string received = com2.ReadTo(endString);
Assert.Equal(buffer, received);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_SurrogateCharacter()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Debug.WriteLine(
"Verifying read method with surrogate pair in the input and a surrogate pair for the newline");
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
string surrogatePair = "\uD800\uDC00";
string newLine = "\uD801\uDC01";
string input = TCSupport.GetRandomString(256, TCSupport.CharacterOptions.None) + surrogatePair + newLine;
com1.NewLine = newLine;
VerifyReadTo(com1, com2, input, newLine);
}
}
#endregion
#region Verification for Test Cases
private void VerifyReadException(SerialPort com, string newLine, Type expectedException)
{
Assert.Throws(expectedException, () => com.ReadTo(newLine));
}
private void VerifyRead(int numberOfBytesToRead)
{
VerifyRead(new ASCIIEncoding(), "\n", numberOfBytesToRead, DEFAULT_NUMBER_NEW_LINES, ReadDataFromEnum.NonBuffered);
}
private void VerifyRead(Encoding encoding)
{
VerifyRead(encoding, "\n", DEFAULT_NUM_CHARS_TO_READ, DEFAULT_NUMBER_NEW_LINES, ReadDataFromEnum.NonBuffered);
}
private void VerifyRead(Encoding encoding, string newLine)
{
VerifyRead(encoding, newLine, DEFAULT_NUM_CHARS_TO_READ, DEFAULT_NUMBER_NEW_LINES, ReadDataFromEnum.NonBuffered);
}
private void VerifyRead(Encoding encoding, string newLine, int numBytesRead, int numNewLines, ReadDataFromEnum readDataFrom)
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Random rndGen = new Random(-55);
StringBuilder strBldrToWrite;
int numNewLineChars = newLine.ToCharArray().Length;
int minLength = (1 + numNewLineChars) * numNewLines;
if (minLength < numBytesRead)
strBldrToWrite = TCSupport.GetRandomStringBuilder(numBytesRead, TCSupport.CharacterOptions.None);
else
strBldrToWrite = TCSupport.GetRandomStringBuilder(rndGen.Next(minLength, minLength * 2),
TCSupport.CharacterOptions.None);
//We need place the newLine so that they do not write over eachother
int divisionLength = strBldrToWrite.Length / numNewLines;
int range = divisionLength - numNewLineChars;
for (int i = 0; i < numNewLines; i++)
{
int newLineIndex = rndGen.Next(0, range + 1);
strBldrToWrite.Insert(newLineIndex + (i * divisionLength) + (i * numNewLineChars), newLine);
}
Debug.WriteLine("Verifying ReadTo encoding={0}, newLine={1}, numBytesRead={2}, numNewLines={3}", encoding,
newLine, numBytesRead, numNewLines);
com1.ReadTimeout = 500;
com1.Encoding = encoding;
TCSupport.SetHighSpeed(com1, com2);
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
switch (readDataFrom)
{
case ReadDataFromEnum.NonBuffered:
VerifyReadNonBuffered(com1, com2, strBldrToWrite.ToString(), newLine);
break;
case ReadDataFromEnum.Buffered:
VerifyReadBuffered(com1, com2, strBldrToWrite.ToString(), newLine);
break;
case ReadDataFromEnum.BufferedAndNonBuffered:
VerifyReadBufferedAndNonBuffered(com1, com2, strBldrToWrite.ToString(), newLine);
break;
default:
throw new ArgumentOutOfRangeException(nameof(readDataFrom), readDataFrom, null);
}
}
}
private void VerifyReadNonBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine)
{
VerifyReadTo(com1, com2, strToWrite, newLine);
}
private void VerifyReadBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine)
{
BufferData(com1, com2, strToWrite);
PerformReadOnCom1FromCom2(com1, com2, strToWrite, newLine);
}
private void VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine)
{
BufferData(com1, com2, strToWrite);
VerifyReadTo(com1, com2, strToWrite, strToWrite + strToWrite, newLine);
}
private void BufferData(SerialPort com1, SerialPort com2, string strToWrite)
{
char[] charsToWrite = strToWrite.ToCharArray();
byte[] bytesToWrite = com1.Encoding.GetBytes(charsToWrite);
com2.Write(bytesToWrite, 0, 1); // Write one byte at the beginning because we are going to read this to buffer the rest of the data
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
while (com1.BytesToRead < bytesToWrite.Length + 1)
{
Thread.Sleep(50);
}
com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPort's own internal buffer
Assert.Equal(bytesToWrite.Length, com1.BytesToRead);
}
private void VerifyReadTo(SerialPort com1, SerialPort com2, string strToWrite, string newLine)
{
VerifyReadTo(com1, com2, strToWrite, strToWrite, newLine);
}
private void VerifyReadTo(SerialPort com1, SerialPort com2, string strToWrite, string expectedString, string newLine)
{
char[] charsToWrite = strToWrite.ToCharArray();
byte[] bytesToWrite = com1.Encoding.GetBytes(charsToWrite);
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com1.ReadTimeout = 500;
Thread.Sleep((int)((((bytesToWrite.Length + 1) * 10.0) / com1.BaudRate) * 1000) + 250);
PerformReadOnCom1FromCom2(com1, com2, expectedString, newLine);
}
private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, string strToWrite, string newLine)
{
StringBuilder strBldrRead = new StringBuilder();
int newLineStringLength = newLine.Length;
int numNewLineChars = newLine.ToCharArray().Length;
int numNewLineBytes = com1.Encoding.GetByteCount(newLine.ToCharArray());
int totalBytesRead;
int totalCharsRead;
int lastIndexOfNewLine = -newLineStringLength;
string expectedString;
bool isUTF7Encoding = IsUTF7Encoding(com1.Encoding);
char[] charsToWrite = strToWrite.ToCharArray();
byte[] bytesToWrite = com1.Encoding.GetBytes(charsToWrite);
expectedString = new string(com1.Encoding.GetChars(bytesToWrite));
totalBytesRead = 0;
totalCharsRead = 0;
while (true)
{
string rcvString;
try
{
rcvString = com1.ReadTo(newLine);
}
catch (TimeoutException)
{
break;
}
//While their are more characters to be read
char[] rcvCharBuffer = rcvString.ToCharArray();
int charsRead = rcvCharBuffer.Length;
if (isUTF7Encoding)
{
totalBytesRead = GetUTF7EncodingBytes(charsToWrite, 0, totalCharsRead + charsRead + numNewLineChars);
}
else
{
int bytesRead = com1.Encoding.GetByteCount(rcvCharBuffer, 0, charsRead);
totalBytesRead += bytesRead + numNewLineBytes;
}
// indexOfNewLine = strToWrite.IndexOf(newLine, lastIndexOfNewLine + newLineStringLength);
int indexOfNewLine = TCSupport.OrdinalIndexOf(expectedString, lastIndexOfNewLine + newLineStringLength, newLine);
if ((indexOfNewLine - (lastIndexOfNewLine + newLineStringLength)) != charsRead)
{
//If we have not read all of the characters that we should have
Debug.WriteLine("indexOfNewLine={0} lastIndexOfNewLine={1} charsRead={2} numNewLineChars={3} newLineStringLength={4} strToWrite.Length={5}",
indexOfNewLine, lastIndexOfNewLine, charsRead, numNewLineChars, newLineStringLength, strToWrite.Length);
Debug.WriteLine(strToWrite);
Fail("Err_1707ahsp!!!: Read did not return all of the characters that were in SerialPort buffer");
}
if (charsToWrite.Length < totalCharsRead + charsRead)
{
//If we have read in more characters then we expect
Fail("Err_21707adad!!!: We have received more characters then were sent");
}
strBldrRead.Append(rcvString);
strBldrRead.Append(newLine);
totalCharsRead += charsRead + numNewLineChars;
lastIndexOfNewLine = indexOfNewLine;
if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead)
{
Fail("Err_99087ahpbx!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead);
}
}//End while there are more characters to read
if (0 != com1.BytesToRead)
{
//If there are more bytes to read but there must not be a new line char at the end
int charRead;
while (true)
{
try
{
charRead = com1.ReadChar();
strBldrRead.Append((char)charRead);
}
catch (TimeoutException) { break; }
}
}
if (0 != com1.BytesToRead && (!isUTF7Encoding || 1 != com1.BytesToRead))
{
Fail("Err_558596ahbpa!!!: BytesToRead is not zero");
}
if (0 != expectedString.CompareTo(strBldrRead.ToString()))
{
Fail("Err_7797ajpba!!!: Expected to read \"{0}\" actual read \"{1}\"", expectedString, strBldrRead.ToString());
}
/*
if (!retValue)
{
Debug.WriteLine("\nstrToWrite = ");
TCSupport.PrintChars(strToWrite.ToCharArray());
Debug.WriteLine("\nnewLine = ");
TCSupport.PrintChars(newLine.ToCharArray());
}
*/
}
private void VerifyReadToWithWriteLine(Encoding encoding, string newLine)
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Random rndGen = new Random(-55);
StringBuilder strBldrToWrite;
string strExpected;
bool isUTF7Encoding = IsUTF7Encoding(encoding);
Debug.WriteLine("Verifying ReadTo with WriteLine encoding={0}, newLine={1}", encoding, newLine);
com1.ReadTimeout = 500;
com2.NewLine = newLine;
com1.Encoding = encoding;
com2.Encoding = encoding;
//Generate random characters
do
{
strBldrToWrite = new StringBuilder();
for (int i = 0; i < DEFAULT_NUM_CHARS_TO_READ; i++)
{
strBldrToWrite.Append((char)rndGen.Next(0, 128));
}
} while (-1 != TCSupport.OrdinalIndexOf(strBldrToWrite.ToString(), newLine));
//SerialPort does a Ordinal comparison
string strWrite = strBldrToWrite.ToString();
strExpected = new string(com1.Encoding.GetChars(com1.Encoding.GetBytes(strWrite.ToCharArray())));
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
com2.WriteLine(strBldrToWrite.ToString());
string strRead = com1.ReadTo(newLine);
if (0 != strBldrToWrite.ToString().CompareTo(strRead))
{
Fail("ERROR!!! The string written: \"{0}\" and the string read \"{1}\" differ", strBldrToWrite, strRead);
}
if (0 != com1.BytesToRead && (!isUTF7Encoding || 1 != com1.BytesToRead))
{
Fail("ERROR!!! BytesToRead={0} expected 0", com1.BytesToRead);
}
}
}
private string GenRandomNewLine(bool validAscii)
{
Random rndGen = new Random(-55);
int newLineLength = rndGen.Next(MIN_NUM_NEWLINE_CHARS, MAX_NUM_NEWLINE_CHARS);
if (validAscii)
return new string(TCSupport.GetRandomChars(newLineLength, TCSupport.CharacterOptions.ASCII));
else
return new string(TCSupport.GetRandomChars(newLineLength, TCSupport.CharacterOptions.Surrogates));
}
private int GetUTF7EncodingBytes(char[] chars, int index, int count)
{
byte[] bytes = LegacyUTF7Encoding.GetBytes(chars, index, count);
int byteCount = bytes.Length;
while (LegacyUTF7Encoding.GetCharCount(bytes, 0, byteCount) == count)
{
--byteCount;
}
return byteCount + 1;
}
private class ASyncRead
{
private readonly SerialPort _com;
private readonly string _value;
private string _result;
private readonly AutoResetEvent _readCompletedEvent;
private readonly AutoResetEvent _readStartedEvent;
private Exception _exception;
public ASyncRead(SerialPort com, string value)
{
_com = com;
_value = value;
_result = null;
_readCompletedEvent = new AutoResetEvent(false);
_readStartedEvent = new AutoResetEvent(false);
_exception = null;
}
public void Read()
{
try
{
_readStartedEvent.Set();
_result = _com.ReadTo(_value);
}
catch (Exception e)
{
_exception = e;
}
finally
{
_readCompletedEvent.Set();
}
}
public AutoResetEvent ReadStartedEvent => _readStartedEvent;
public AutoResetEvent ReadCompletedEvent => _readCompletedEvent;
public string Result => _result;
public Exception Exception => _exception;
}
#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.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class ReadTo : PortsTest
{
//The number of random bytes to receive for read method testing
private const int DEFAULT_NUM_CHARS_TO_READ = 8;
//The number of new lines to insert into the string not including the one at the end
private const int DEFAULT_NUMBER_NEW_LINES = 2;
//The number of random bytes to receive for large input buffer testing
private const int LARGE_NUM_CHARS_TO_READ = 2048;
private const int MIN_NUM_NEWLINE_CHARS = 1;
private const int MAX_NUM_NEWLINE_CHARS = 5;
private enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered };
#region Test Cases
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void NewLine_Contains_nullChar()
{
VerifyRead(new ASCIIEncoding(), "\0");
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void NewLine_CR()
{
VerifyRead(new ASCIIEncoding(), "\r");
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void NewLine_LF()
{
VerifyRead(new ASCIIEncoding(), "\n");
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void NewLine_CRLF_RndStr()
{
VerifyRead(new ASCIIEncoding(), "\r\n");
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void NewLine_CRLF_CRStr()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Debug.WriteLine("Verifying read method with \\r\\n NewLine and a string containing just \\r");
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
VerifyReadTo(com1, com2, "TEST\r", "\r\n");
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void NewLine_CRLF_LFStr()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Debug.WriteLine("Verifying read method with \\r\\n NewLine and a string containing just \\n");
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
VerifyReadTo(com1, com2, "TEST\n", "\r\n");
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void NewLine_END()
{
VerifyRead(new ASCIIEncoding(), "END");
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ASCIIEncoding()
{
VerifyRead(new ASCIIEncoding(), GenRandomNewLine(true));
}
/*
public void UTF7Encoding()
{
VerifyRead(new System.Text.UTF7Encoding(), GenRandomNewLine(false));
}
*/
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void UTF8Encoding()
{
VerifyRead(new UTF8Encoding(), GenRandomNewLine(false));
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void UTF32Encoding()
{
VerifyRead(new UTF32Encoding(), GenRandomNewLine(false));
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void UnicodeEncoding()
{
VerifyRead(new UnicodeEncoding(), GenRandomNewLine(false));
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void LargeInputBuffer()
{
VerifyRead(LARGE_NUM_CHARS_TO_READ);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadToWriteLine_ASCII()
{
VerifyReadToWithWriteLine(new ASCIIEncoding(), GenRandomNewLine(true));
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadToWriteLine_UTF8()
{
VerifyReadToWithWriteLine(new UTF8Encoding(), GenRandomNewLine(true));
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadToWriteLine_UTF32()
{
VerifyReadToWithWriteLine(new UTF32Encoding(), GenRandomNewLine(true));
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void ReadToWriteLine_Unicode()
{
VerifyReadToWithWriteLine(new UnicodeEncoding(), GenRandomNewLine(true));
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_ReadBufferedData()
{
int numBytesToRead = 32;
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Random rndGen = new Random(-55);
StringBuilder strBldrToWrite = new StringBuilder();
//Genrate random characters
for (int i = 0; i < numBytesToRead; i++)
{
strBldrToWrite.Append((char)rndGen.Next(40, 60));
}
int newLineIndex;
while (-1 != (newLineIndex = strBldrToWrite.ToString().IndexOf(com1.NewLine)))
{
strBldrToWrite[newLineIndex] = (char)rndGen.Next(40, 60);
}
com1.ReadTimeout = 500;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
strBldrToWrite.Append(com1.NewLine);
BufferData(com1, com2, strBldrToWrite.ToString());
PerformReadOnCom1FromCom2(com1, com2, strBldrToWrite.ToString(), com1.NewLine);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_IterativeReadBufferedData()
{
int numBytesToRead = 32;
VerifyRead(Encoding.ASCII, GenRandomNewLine(true), numBytesToRead, 1, ReadDataFromEnum.Buffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_ReadBufferedAndNonBufferedData()
{
int numBytesToRead = 32;
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Random rndGen = new Random(-55);
StringBuilder strBldrToWrite = new StringBuilder();
StringBuilder strBldrExpected = new StringBuilder();
//Genrate random characters
for (int i = 0; i < numBytesToRead; i++)
{
strBldrToWrite.Append((char)rndGen.Next(0, 256));
}
int newLineIndex;
while (-1 != (newLineIndex = strBldrToWrite.ToString().IndexOf(com1.NewLine)))
{
strBldrToWrite[newLineIndex] = (char)rndGen.Next(0, 256);
}
com1.ReadTimeout = 500;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
BufferData(com1, com2, strBldrToWrite.ToString());
strBldrExpected.Append(strBldrToWrite);
strBldrToWrite.Append(com1.NewLine);
strBldrExpected.Append(strBldrToWrite);
VerifyReadTo(com1, com2, strBldrToWrite.ToString(), strBldrExpected.ToString(), com1.NewLine);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_IterativeReadBufferedAndNonBufferedData()
{
int numBytesToRead = 3;
VerifyRead(Encoding.ASCII, GenRandomNewLine(true), numBytesToRead, 1, ReadDataFromEnum.BufferedAndNonBuffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void GreedyRead()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] charXmitBuffer = TCSupport.GetRandomChars(128, TCSupport.CharacterOptions.Surrogates);
byte[] byteXmitBuffer = new byte[1024];
char utf32Char = TCSupport.GenerateRandomCharNonSurrogate();
byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char });
int numBytes;
Debug.WriteLine("Verifying that ReadTo() will read everything from internal buffer and drivers buffer");
//Put the first byte of the utf32 encoder char in the last byte of this buffer
//when we read this later the buffer will have to be resized
byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0];
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length);
TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length);
//Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's
//internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so
//the other 3 bytes of the ut32 encoded char can be in the buffer
com1.Read(new char[1023], 0, 1023);
Assert.Equal(1, com1.BytesToRead);
com1.Encoding = Encoding.UTF32;
com2.Encoding = Encoding.UTF32;
com2.Write(utf32CharBytes, 1, 3);
com2.Write(charXmitBuffer, 0, charXmitBuffer.Length);
com2.WriteLine(string.Empty);
numBytes = Encoding.UTF32.GetByteCount(charXmitBuffer);
byte[] byteBuffer = Encoding.UTF32.GetBytes(charXmitBuffer);
char[] expectedChars = new char[1 + Encoding.UTF32.GetCharCount(byteBuffer)];
expectedChars[0] = utf32Char;
Encoding.UTF32.GetChars(byteBuffer, 0, byteBuffer.Length, expectedChars, 1);
TCSupport.WaitForReadBufferToLoad(com1, 4 + numBytes);
string rcvString = com1.ReadTo(com2.NewLine);
Assert.NotNull(rcvString);
Assert.Equal(expectedChars, rcvString.ToCharArray());
Assert.Equal(0, com1.BytesToRead);
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void NullNewLine()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying read method throws ArgumentExcpetion with a null NewLine string");
com.Open();
VerifyReadException(com, null, typeof(ArgumentNullException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void EmptyNewLine()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying read method throws ArgumentExcpetion with an empty NewLine string");
com.Open();
VerifyReadException(com, "", typeof(ArgumentException));
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void NewLineSubstring()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Debug.WriteLine("Verifying read method with sub strings of the new line appearing in the string being read");
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
string newLine = "asfg";
string newLineSubStrings = "a" + "as" + "asf" + "sfg" + "fg" + "g"; //All the substrings of newLine
string testStr = newLineSubStrings + "asfg" + newLineSubStrings;
VerifyReadTo(com1, com2, testStr, newLine);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_DataReceivedBeforeTimeout()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None);
string endString = "END";
ASyncRead asyncRead = new ASyncRead(com1, endString);
var asyncReadTask = new Task(asyncRead.Read);
char endChar = endString[0];
char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None);
Debug.WriteLine(
"Verifying that ReadTo(string) will read characters that have been received after the call to Read was made");
//Ensure the new line is not in charXmitBuffer
for (int i = 0; i < charXmitBuffer.Length; ++i)
{
//Se any appearances of a character in the new line string to some other char
if (endChar == charXmitBuffer[i])
{
charXmitBuffer[i] = notEndChar;
}
}
com1.Encoding = Encoding.UTF8;
com2.Encoding = Encoding.UTF8;
com1.ReadTimeout = 20000; // 20 seconds
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
asyncReadTask.Start();
asyncRead.ReadStartedEvent.WaitOne();
//This only tells us that the thread has started to execute code in the method
Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort
com2.Write(charXmitBuffer, 0, charXmitBuffer.Length);
com2.Write(endString);
asyncRead.ReadCompletedEvent.WaitOne();
if (null != asyncRead.Exception)
{
Fail("Err_04448ajhied Unexpected exception thrown from async read:\n{0}", asyncRead.Exception);
}
else if (null == asyncRead.Result || 0 == asyncRead.Result.Length)
{
Fail("Err_0158ahei Expected Read to read at least one character");
}
else
{
char[] charRcvBuffer = asyncRead.Result.ToCharArray();
if (charRcvBuffer.Length != charXmitBuffer.Length)
{
Fail("Err_051884ajoedo Expected Read to read {0} characters actually read {1}", charXmitBuffer.Length, charRcvBuffer.Length);
}
else
{
for (int i = 0; i < charXmitBuffer.Length; ++i)
{
if (charRcvBuffer[i] != charXmitBuffer[i])
{
Fail(
"Err_0518895akiezp Characters differ at {0} expected:{1}({2:X}) actual:{3}({4:X})", i,
charXmitBuffer[i], (int)charXmitBuffer[i], charRcvBuffer[i], (int)charRcvBuffer[i]);
}
}
}
}
VerifyReadTo(com1, com2, new string(charXmitBuffer), endString);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_Timeout()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None);
string endString = "END";
char endChar = endString[0];
char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None);
Debug.WriteLine("Verifying that ReadTo(string) works appropriately after TimeoutException has been thrown");
// Ensure the new line is not in charXmitBuffer
for (int i = 0; i < charXmitBuffer.Length; ++i)
{
// Set any appearances of a character in the new line string to some other char
if (endChar == charXmitBuffer[i])
{
charXmitBuffer[i] = notEndChar;
}
}
com1.Encoding = Encoding.Unicode;
com2.Encoding = Encoding.Unicode;
com1.ReadTimeout = 2000;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
com2.Write(charXmitBuffer, 0, charXmitBuffer.Length);
Assert.Throws<TimeoutException>(() => com1.ReadTo(endString));
Assert.Equal(2 * charXmitBuffer.Length, com1.BytesToRead);
com2.Write(endString);
string result = com1.ReadTo(endString);
char[] charRcvBuffer = result.ToCharArray();
Assert.Equal(charRcvBuffer, charXmitBuffer);
VerifyReadTo(com1, com2, new string(charXmitBuffer), endString);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_LargeBuffer()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
const int bufferSize = 2048;
char[] buffer = new char[bufferSize];
for (int i = 0; i < bufferSize; i++)
{
buffer[i] = (char)('A' + (i % 5));
}
const char endChar = 'Z';
string endString = new string(endChar, 1);
com1.BaudRate = 115200;
com2.BaudRate = 115200;
com1.Encoding = Encoding.Unicode;
com2.Encoding = Encoding.Unicode;
com2.ReadTimeout = 10000;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
Task writeToCom2Task = Task.Run(() => {
com1.Write(buffer, 0, bufferSize);
});
Assert.Throws<TimeoutException>(() => com2.ReadTo(endString));
writeToCom2Task.Wait();
com1.Write(endString);
string received = com2.ReadTo(endString);
Assert.Equal(buffer, received);
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_SurrogateCharacter()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Debug.WriteLine(
"Verifying read method with surrogate pair in the input and a surrogate pair for the newline");
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
string surrogatePair = "\uD800\uDC00";
string newLine = "\uD801\uDC01";
string input = TCSupport.GetRandomString(256, TCSupport.CharacterOptions.None) + surrogatePair + newLine;
com1.NewLine = newLine;
VerifyReadTo(com1, com2, input, newLine);
}
}
#endregion
#region Verification for Test Cases
private void VerifyReadException(SerialPort com, string newLine, Type expectedException)
{
Assert.Throws(expectedException, () => com.ReadTo(newLine));
}
private void VerifyRead(int numberOfBytesToRead)
{
VerifyRead(new ASCIIEncoding(), "\n", numberOfBytesToRead, DEFAULT_NUMBER_NEW_LINES, ReadDataFromEnum.NonBuffered);
}
private void VerifyRead(Encoding encoding)
{
VerifyRead(encoding, "\n", DEFAULT_NUM_CHARS_TO_READ, DEFAULT_NUMBER_NEW_LINES, ReadDataFromEnum.NonBuffered);
}
private void VerifyRead(Encoding encoding, string newLine)
{
VerifyRead(encoding, newLine, DEFAULT_NUM_CHARS_TO_READ, DEFAULT_NUMBER_NEW_LINES, ReadDataFromEnum.NonBuffered);
}
private void VerifyRead(Encoding encoding, string newLine, int numBytesRead, int numNewLines, ReadDataFromEnum readDataFrom)
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Random rndGen = new Random(-55);
StringBuilder strBldrToWrite;
int numNewLineChars = newLine.ToCharArray().Length;
int minLength = (1 + numNewLineChars) * numNewLines;
if (minLength < numBytesRead)
strBldrToWrite = TCSupport.GetRandomStringBuilder(numBytesRead, TCSupport.CharacterOptions.None);
else
strBldrToWrite = TCSupport.GetRandomStringBuilder(rndGen.Next(minLength, minLength * 2),
TCSupport.CharacterOptions.None);
//We need place the newLine so that they do not write over eachother
int divisionLength = strBldrToWrite.Length / numNewLines;
int range = divisionLength - numNewLineChars;
for (int i = 0; i < numNewLines; i++)
{
int newLineIndex = rndGen.Next(0, range + 1);
strBldrToWrite.Insert(newLineIndex + (i * divisionLength) + (i * numNewLineChars), newLine);
}
Debug.WriteLine("Verifying ReadTo encoding={0}, newLine={1}, numBytesRead={2}, numNewLines={3}", encoding,
newLine, numBytesRead, numNewLines);
com1.ReadTimeout = 500;
com1.Encoding = encoding;
TCSupport.SetHighSpeed(com1, com2);
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
switch (readDataFrom)
{
case ReadDataFromEnum.NonBuffered:
VerifyReadNonBuffered(com1, com2, strBldrToWrite.ToString(), newLine);
break;
case ReadDataFromEnum.Buffered:
VerifyReadBuffered(com1, com2, strBldrToWrite.ToString(), newLine);
break;
case ReadDataFromEnum.BufferedAndNonBuffered:
VerifyReadBufferedAndNonBuffered(com1, com2, strBldrToWrite.ToString(), newLine);
break;
default:
throw new ArgumentOutOfRangeException(nameof(readDataFrom), readDataFrom, null);
}
}
}
private void VerifyReadNonBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine)
{
VerifyReadTo(com1, com2, strToWrite, newLine);
}
private void VerifyReadBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine)
{
BufferData(com1, com2, strToWrite);
PerformReadOnCom1FromCom2(com1, com2, strToWrite, newLine);
}
private void VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine)
{
BufferData(com1, com2, strToWrite);
VerifyReadTo(com1, com2, strToWrite, strToWrite + strToWrite, newLine);
}
private void BufferData(SerialPort com1, SerialPort com2, string strToWrite)
{
char[] charsToWrite = strToWrite.ToCharArray();
byte[] bytesToWrite = com1.Encoding.GetBytes(charsToWrite);
com2.Write(bytesToWrite, 0, 1); // Write one byte at the beginning because we are going to read this to buffer the rest of the data
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
while (com1.BytesToRead < bytesToWrite.Length + 1)
{
Thread.Sleep(50);
}
com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPort's own internal buffer
Assert.Equal(bytesToWrite.Length, com1.BytesToRead);
}
private void VerifyReadTo(SerialPort com1, SerialPort com2, string strToWrite, string newLine)
{
VerifyReadTo(com1, com2, strToWrite, strToWrite, newLine);
}
private void VerifyReadTo(SerialPort com1, SerialPort com2, string strToWrite, string expectedString, string newLine)
{
char[] charsToWrite = strToWrite.ToCharArray();
byte[] bytesToWrite = com1.Encoding.GetBytes(charsToWrite);
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com1.ReadTimeout = 500;
Thread.Sleep((int)((((bytesToWrite.Length + 1) * 10.0) / com1.BaudRate) * 1000) + 250);
PerformReadOnCom1FromCom2(com1, com2, expectedString, newLine);
}
private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, string strToWrite, string newLine)
{
StringBuilder strBldrRead = new StringBuilder();
int newLineStringLength = newLine.Length;
int numNewLineChars = newLine.ToCharArray().Length;
int numNewLineBytes = com1.Encoding.GetByteCount(newLine.ToCharArray());
int totalBytesRead;
int totalCharsRead;
int lastIndexOfNewLine = -newLineStringLength;
string expectedString;
bool isUTF7Encoding = IsUTF7Encoding(com1.Encoding);
char[] charsToWrite = strToWrite.ToCharArray();
byte[] bytesToWrite = com1.Encoding.GetBytes(charsToWrite);
expectedString = new string(com1.Encoding.GetChars(bytesToWrite));
totalBytesRead = 0;
totalCharsRead = 0;
while (true)
{
string rcvString;
try
{
rcvString = com1.ReadTo(newLine);
}
catch (TimeoutException)
{
break;
}
//While their are more characters to be read
char[] rcvCharBuffer = rcvString.ToCharArray();
int charsRead = rcvCharBuffer.Length;
if (isUTF7Encoding)
{
totalBytesRead = GetUTF7EncodingBytes(charsToWrite, 0, totalCharsRead + charsRead + numNewLineChars);
}
else
{
int bytesRead = com1.Encoding.GetByteCount(rcvCharBuffer, 0, charsRead);
totalBytesRead += bytesRead + numNewLineBytes;
}
// indexOfNewLine = strToWrite.IndexOf(newLine, lastIndexOfNewLine + newLineStringLength);
int indexOfNewLine = TCSupport.OrdinalIndexOf(expectedString, lastIndexOfNewLine + newLineStringLength, newLine);
if ((indexOfNewLine - (lastIndexOfNewLine + newLineStringLength)) != charsRead)
{
//If we have not read all of the characters that we should have
Debug.WriteLine("indexOfNewLine={0} lastIndexOfNewLine={1} charsRead={2} numNewLineChars={3} newLineStringLength={4} strToWrite.Length={5}",
indexOfNewLine, lastIndexOfNewLine, charsRead, numNewLineChars, newLineStringLength, strToWrite.Length);
Debug.WriteLine(strToWrite);
Fail("Err_1707ahsp!!!: Read did not return all of the characters that were in SerialPort buffer");
}
if (charsToWrite.Length < totalCharsRead + charsRead)
{
//If we have read in more characters then we expect
Fail("Err_21707adad!!!: We have received more characters then were sent");
}
strBldrRead.Append(rcvString);
strBldrRead.Append(newLine);
totalCharsRead += charsRead + numNewLineChars;
lastIndexOfNewLine = indexOfNewLine;
if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead)
{
Fail("Err_99087ahpbx!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead);
}
}//End while there are more characters to read
if (0 != com1.BytesToRead)
{
//If there are more bytes to read but there must not be a new line char at the end
int charRead;
while (true)
{
try
{
charRead = com1.ReadChar();
strBldrRead.Append((char)charRead);
}
catch (TimeoutException) { break; }
}
}
if (0 != com1.BytesToRead && (!isUTF7Encoding || 1 != com1.BytesToRead))
{
Fail("Err_558596ahbpa!!!: BytesToRead is not zero");
}
if (0 != expectedString.CompareTo(strBldrRead.ToString()))
{
Fail("Err_7797ajpba!!!: Expected to read \"{0}\" actual read \"{1}\"", expectedString, strBldrRead.ToString());
}
/*
if (!retValue)
{
Debug.WriteLine("\nstrToWrite = ");
TCSupport.PrintChars(strToWrite.ToCharArray());
Debug.WriteLine("\nnewLine = ");
TCSupport.PrintChars(newLine.ToCharArray());
}
*/
}
private void VerifyReadToWithWriteLine(Encoding encoding, string newLine)
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Random rndGen = new Random(-55);
StringBuilder strBldrToWrite;
string strExpected;
bool isUTF7Encoding = IsUTF7Encoding(encoding);
Debug.WriteLine("Verifying ReadTo with WriteLine encoding={0}, newLine={1}", encoding, newLine);
com1.ReadTimeout = 500;
com2.NewLine = newLine;
com1.Encoding = encoding;
com2.Encoding = encoding;
//Generate random characters
do
{
strBldrToWrite = new StringBuilder();
for (int i = 0; i < DEFAULT_NUM_CHARS_TO_READ; i++)
{
strBldrToWrite.Append((char)rndGen.Next(0, 128));
}
} while (-1 != TCSupport.OrdinalIndexOf(strBldrToWrite.ToString(), newLine));
//SerialPort does a Ordinal comparison
string strWrite = strBldrToWrite.ToString();
strExpected = new string(com1.Encoding.GetChars(com1.Encoding.GetBytes(strWrite.ToCharArray())));
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
com2.WriteLine(strBldrToWrite.ToString());
string strRead = com1.ReadTo(newLine);
if (0 != strBldrToWrite.ToString().CompareTo(strRead))
{
Fail("ERROR!!! The string written: \"{0}\" and the string read \"{1}\" differ", strBldrToWrite, strRead);
}
if (0 != com1.BytesToRead && (!isUTF7Encoding || 1 != com1.BytesToRead))
{
Fail("ERROR!!! BytesToRead={0} expected 0", com1.BytesToRead);
}
}
}
private string GenRandomNewLine(bool validAscii)
{
Random rndGen = new Random(-55);
int newLineLength = rndGen.Next(MIN_NUM_NEWLINE_CHARS, MAX_NUM_NEWLINE_CHARS);
if (validAscii)
return new string(TCSupport.GetRandomChars(newLineLength, TCSupport.CharacterOptions.ASCII));
else
return new string(TCSupport.GetRandomChars(newLineLength, TCSupport.CharacterOptions.Surrogates));
}
private int GetUTF7EncodingBytes(char[] chars, int index, int count)
{
byte[] bytes = LegacyUTF7Encoding.GetBytes(chars, index, count);
int byteCount = bytes.Length;
while (LegacyUTF7Encoding.GetCharCount(bytes, 0, byteCount) == count)
{
--byteCount;
}
return byteCount + 1;
}
private class ASyncRead
{
private readonly SerialPort _com;
private readonly string _value;
private string _result;
private readonly AutoResetEvent _readCompletedEvent;
private readonly AutoResetEvent _readStartedEvent;
private Exception _exception;
public ASyncRead(SerialPort com, string value)
{
_com = com;
_value = value;
_result = null;
_readCompletedEvent = new AutoResetEvent(false);
_readStartedEvent = new AutoResetEvent(false);
_exception = null;
}
public void Read()
{
try
{
_readStartedEvent.Set();
_result = _com.ReadTo(_value);
}
catch (Exception e)
{
_exception = e;
}
finally
{
_readCompletedEvent.Set();
}
}
public AutoResetEvent ReadStartedEvent => _readStartedEvent;
public AutoResetEvent ReadCompletedEvent => _readCompletedEvent;
public string Result => _result;
public Exception Exception => _exception;
}
#endregion
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Private.Xml/tests/XmlDocument/XmlNodeTests/NextSiblingTests.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 static class NextSiblingTests
{
[Fact]
public static void OnTextNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root>some text<child1/></root>");
Assert.Equal(XmlNodeType.Text, xmlDocument.DocumentElement.ChildNodes[0].NodeType);
Assert.Equal(xmlDocument.DocumentElement.ChildNodes[0].NextSibling, xmlDocument.DocumentElement.ChildNodes[1]);
}
[Fact]
public static void OnTextNodeSplit()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root>some text</root>");
var textNode = (XmlText)xmlDocument.DocumentElement.FirstChild;
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Null(textNode.NextSibling);
var split = textNode.SplitText(4);
Assert.Equal(2, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Equal(split, textNode.NextSibling);
Assert.Null(split.NextSibling);
}
[Fact]
public static void OnCommentNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><!--some text--><child1/></root>");
Assert.Equal(XmlNodeType.Comment, xmlDocument.DocumentElement.ChildNodes[0].NodeType);
Assert.Equal(xmlDocument.DocumentElement.ChildNodes[0].NextSibling, xmlDocument.DocumentElement.ChildNodes[1]);
}
[Fact]
public static void SiblingOfLastChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root>some text<child1/><child2/></root>");
Assert.Null(xmlDocument.DocumentElement.LastChild.NextSibling);
}
[Fact]
public static void OnCDataNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><![CDATA[ <opentag> without an </endtag> and & <! are all ok here ]]><child1/></root>");
Assert.Equal(XmlNodeType.CDATA, xmlDocument.DocumentElement.ChildNodes[0].NodeType);
Assert.Equal(xmlDocument.DocumentElement.ChildNodes[0].NextSibling, xmlDocument.DocumentElement.ChildNodes[1]);
}
[Fact]
public static void OnDocumentFragment()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/>some text<child2/><child3/></root>");
var documentFragment = xmlDocument.CreateDocumentFragment();
documentFragment.AppendChild(xmlDocument.DocumentElement);
Assert.Null(documentFragment.NextSibling);
}
[Fact]
public static void OnDocumentElement()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root/><?PI pi info?>");
var piInfo = xmlDocument.ChildNodes[1];
Assert.Equal(XmlNodeType.ProcessingInstruction, piInfo.NodeType);
Assert.Equal(piInfo, xmlDocument.DocumentElement.NextSibling);
}
[Fact]
public static void OnAttributeNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root attr1='test' attr2='test2' />");
var attr1 = xmlDocument.DocumentElement.Attributes[0];
Assert.Equal("attr1", attr1.Name);
Assert.Null(attr1.NextSibling);
}
[Fact]
public static void OnAttributeNodeWithChildren()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root attr1='test' attr2='test2'><child1/><child2/><child3/></root>");
var node = xmlDocument.DocumentElement.ChildNodes[2];
Assert.Equal("child3", node.Name);
Assert.Null(node.NextSibling);
}
[Fact]
public static void ElementOneChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child/></root>");
Assert.Null(xmlDocument.DocumentElement.ChildNodes[0].NextSibling);
}
[Fact]
public static void OnAllSiblings()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/><child3 attr='1'/>Some Text<child4/><!-- comment --><?PI processing info?></root>");
var count = xmlDocument.DocumentElement.ChildNodes.Count;
var previousNode = xmlDocument.DocumentElement.ChildNodes[0];
for (var idx = 1; idx < count; idx++)
{
var currentNode = xmlDocument.DocumentElement.ChildNodes[idx];
Assert.Equal(previousNode.NextSibling, currentNode);
previousNode = currentNode;
}
Assert.Null(previousNode.NextSibling);
}
[Fact]
public static void RemoveChildCheckSibling()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var child2 = xmlDocument.DocumentElement.ChildNodes[1];
Assert.Equal("child1", child1.Name);
Assert.Equal("child2", child2.Name);
Assert.Equal(child2, child1.NextSibling);
xmlDocument.DocumentElement.RemoveChild(child1);
Assert.Null(child1.NextSibling);
}
[Fact]
public static void ReplaceChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var child2 = xmlDocument.DocumentElement.ChildNodes[1];
var child3 = xmlDocument.DocumentElement.ChildNodes[2];
Assert.Equal(child2, child1.NextSibling);
Assert.Equal(child3, child2.NextSibling);
Assert.Null(child3.NextSibling);
xmlDocument.DocumentElement.RemoveChild(child2);
Assert.Equal(child3, child1.NextSibling);
Assert.Null(child2.NextSibling);
Assert.Null(child3.NextSibling);
}
[Fact]
public static void InsertChildAfter()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var newNode = xmlDocument.CreateElement("child2");
Assert.Null(child1.NextSibling);
xmlDocument.DocumentElement.InsertAfter(newNode, child1);
Assert.Equal(newNode, child1.NextSibling);
Assert.Null(newNode.NextSibling);
}
[Fact]
public static void AppendChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var newNode = xmlDocument.CreateElement("child2");
Assert.Null(child1.NextSibling);
xmlDocument.DocumentElement.AppendChild(newNode);
Assert.Equal(newNode, child1.NextSibling);
Assert.Null(newNode.NextSibling);
}
[Fact]
public static void NewlyCreatedElement()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateElement("element");
Assert.Null(node.NextSibling);
}
[Fact]
public static void NewlyCreatedAttribute()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateAttribute("attribute");
Assert.Null(node.NextSibling);
}
[Fact]
public static void NewlyCreatedTextNode()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateTextNode("textnode");
Assert.Null(node.NextSibling);
}
[Fact]
public static void NewlyCreatedCDataNode()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateCDataSection("cdata section");
Assert.Null(node.NextSibling);
}
[Fact]
public static void NewlyCreatedProcessingInstruction()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateProcessingInstruction("PI", "data");
Assert.Null(node.NextSibling);
}
[Fact]
public static void NewlyCreatedComment()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateComment("comment");
Assert.Null(node.NextSibling);
}
[Fact]
public static void NewlyCreatedDocumentFragment()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateDocumentFragment();
Assert.Null(node.NextSibling);
}
[Fact]
public static void FirstChildNextSibling()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>");
Assert.Equal(xmlDocument.DocumentElement.ChildNodes[1], xmlDocument.DocumentElement.FirstChild.NextSibling);
}
}
}
| // 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 static class NextSiblingTests
{
[Fact]
public static void OnTextNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root>some text<child1/></root>");
Assert.Equal(XmlNodeType.Text, xmlDocument.DocumentElement.ChildNodes[0].NodeType);
Assert.Equal(xmlDocument.DocumentElement.ChildNodes[0].NextSibling, xmlDocument.DocumentElement.ChildNodes[1]);
}
[Fact]
public static void OnTextNodeSplit()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root>some text</root>");
var textNode = (XmlText)xmlDocument.DocumentElement.FirstChild;
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Null(textNode.NextSibling);
var split = textNode.SplitText(4);
Assert.Equal(2, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Equal(split, textNode.NextSibling);
Assert.Null(split.NextSibling);
}
[Fact]
public static void OnCommentNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><!--some text--><child1/></root>");
Assert.Equal(XmlNodeType.Comment, xmlDocument.DocumentElement.ChildNodes[0].NodeType);
Assert.Equal(xmlDocument.DocumentElement.ChildNodes[0].NextSibling, xmlDocument.DocumentElement.ChildNodes[1]);
}
[Fact]
public static void SiblingOfLastChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root>some text<child1/><child2/></root>");
Assert.Null(xmlDocument.DocumentElement.LastChild.NextSibling);
}
[Fact]
public static void OnCDataNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><![CDATA[ <opentag> without an </endtag> and & <! are all ok here ]]><child1/></root>");
Assert.Equal(XmlNodeType.CDATA, xmlDocument.DocumentElement.ChildNodes[0].NodeType);
Assert.Equal(xmlDocument.DocumentElement.ChildNodes[0].NextSibling, xmlDocument.DocumentElement.ChildNodes[1]);
}
[Fact]
public static void OnDocumentFragment()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/>some text<child2/><child3/></root>");
var documentFragment = xmlDocument.CreateDocumentFragment();
documentFragment.AppendChild(xmlDocument.DocumentElement);
Assert.Null(documentFragment.NextSibling);
}
[Fact]
public static void OnDocumentElement()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root/><?PI pi info?>");
var piInfo = xmlDocument.ChildNodes[1];
Assert.Equal(XmlNodeType.ProcessingInstruction, piInfo.NodeType);
Assert.Equal(piInfo, xmlDocument.DocumentElement.NextSibling);
}
[Fact]
public static void OnAttributeNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root attr1='test' attr2='test2' />");
var attr1 = xmlDocument.DocumentElement.Attributes[0];
Assert.Equal("attr1", attr1.Name);
Assert.Null(attr1.NextSibling);
}
[Fact]
public static void OnAttributeNodeWithChildren()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root attr1='test' attr2='test2'><child1/><child2/><child3/></root>");
var node = xmlDocument.DocumentElement.ChildNodes[2];
Assert.Equal("child3", node.Name);
Assert.Null(node.NextSibling);
}
[Fact]
public static void ElementOneChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child/></root>");
Assert.Null(xmlDocument.DocumentElement.ChildNodes[0].NextSibling);
}
[Fact]
public static void OnAllSiblings()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/><child3 attr='1'/>Some Text<child4/><!-- comment --><?PI processing info?></root>");
var count = xmlDocument.DocumentElement.ChildNodes.Count;
var previousNode = xmlDocument.DocumentElement.ChildNodes[0];
for (var idx = 1; idx < count; idx++)
{
var currentNode = xmlDocument.DocumentElement.ChildNodes[idx];
Assert.Equal(previousNode.NextSibling, currentNode);
previousNode = currentNode;
}
Assert.Null(previousNode.NextSibling);
}
[Fact]
public static void RemoveChildCheckSibling()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var child2 = xmlDocument.DocumentElement.ChildNodes[1];
Assert.Equal("child1", child1.Name);
Assert.Equal("child2", child2.Name);
Assert.Equal(child2, child1.NextSibling);
xmlDocument.DocumentElement.RemoveChild(child1);
Assert.Null(child1.NextSibling);
}
[Fact]
public static void ReplaceChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var child2 = xmlDocument.DocumentElement.ChildNodes[1];
var child3 = xmlDocument.DocumentElement.ChildNodes[2];
Assert.Equal(child2, child1.NextSibling);
Assert.Equal(child3, child2.NextSibling);
Assert.Null(child3.NextSibling);
xmlDocument.DocumentElement.RemoveChild(child2);
Assert.Equal(child3, child1.NextSibling);
Assert.Null(child2.NextSibling);
Assert.Null(child3.NextSibling);
}
[Fact]
public static void InsertChildAfter()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var newNode = xmlDocument.CreateElement("child2");
Assert.Null(child1.NextSibling);
xmlDocument.DocumentElement.InsertAfter(newNode, child1);
Assert.Equal(newNode, child1.NextSibling);
Assert.Null(newNode.NextSibling);
}
[Fact]
public static void AppendChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/></root>");
var child1 = xmlDocument.DocumentElement.ChildNodes[0];
var newNode = xmlDocument.CreateElement("child2");
Assert.Null(child1.NextSibling);
xmlDocument.DocumentElement.AppendChild(newNode);
Assert.Equal(newNode, child1.NextSibling);
Assert.Null(newNode.NextSibling);
}
[Fact]
public static void NewlyCreatedElement()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateElement("element");
Assert.Null(node.NextSibling);
}
[Fact]
public static void NewlyCreatedAttribute()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateAttribute("attribute");
Assert.Null(node.NextSibling);
}
[Fact]
public static void NewlyCreatedTextNode()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateTextNode("textnode");
Assert.Null(node.NextSibling);
}
[Fact]
public static void NewlyCreatedCDataNode()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateCDataSection("cdata section");
Assert.Null(node.NextSibling);
}
[Fact]
public static void NewlyCreatedProcessingInstruction()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateProcessingInstruction("PI", "data");
Assert.Null(node.NextSibling);
}
[Fact]
public static void NewlyCreatedComment()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateComment("comment");
Assert.Null(node.NextSibling);
}
[Fact]
public static void NewlyCreatedDocumentFragment()
{
var xmlDocument = new XmlDocument();
var node = xmlDocument.CreateDocumentFragment();
Assert.Null(node.NextSibling);
}
[Fact]
public static void FirstChildNextSibling()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>");
Assert.Equal(xmlDocument.DocumentElement.ChildNodes[1], xmlDocument.DocumentElement.FirstChild.NextSibling);
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Net.Mail/tests/Unit/Base64EncodingTest.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 Xunit;
namespace System.Net.Mime.Tests
{
public class Base64EncodingTest
{
[Theory]
[InlineData("some test header to base64 encode")]
[InlineData("some test h\xE9ader to base64asdf\xE9\xE5")]
public void Base64Stream_WithBasicAsciiString_ShouldEncodeAndDecode(string testHeader)
{
var s = new Base64Stream(new Base64WriteStateInfo());
var testHeaderBytes = Encoding.UTF8.GetBytes(testHeader);
s.EncodeBytes(testHeaderBytes, 0, testHeaderBytes.Length);
string encodedString = s.GetEncodedString();
for (int i = 0; i < encodedString.Length; i++)
{
Assert.InRange((byte)encodedString[i], 0, 127);
}
byte[] stringToDecode = Encoding.ASCII.GetBytes(encodedString);
int result = s.DecodeBytes(stringToDecode, 0, encodedString.Length);
Assert.Equal(testHeader, Encoding.UTF8.GetString(stringToDecode, 0, result));
}
[Theory]
[InlineData("some test header to base64 encode")]
[InlineData("some test h\xE9ader to base64asdf\xE9\xE5")]
public void Base64Stream_EncodeString_WithBasicAsciiString_ShouldEncodeAndDecode(string testHeader)
{
var s = new Base64Stream(new Base64WriteStateInfo());
s.EncodeString(testHeader, Encoding.UTF8);
string encodedString = s.GetEncodedString();
for (int i = 0; i < encodedString.Length; i++)
{
Assert.InRange((byte)encodedString[i], 0, 127);
}
byte[] stringToDecode = Encoding.ASCII.GetBytes(encodedString);
int result = s.DecodeBytes(stringToDecode, 0, encodedString.Length);
Assert.Equal(testHeader, Encoding.UTF8.GetString(stringToDecode, 0, result));
}
[Fact]
public void Base64Stream_WithVerySmallBuffer_ShouldTriggerBufferResize_AndShouldEncodeProperly()
{
var s = new Base64Stream(new Base64WriteStateInfo(10, new byte[0], new byte[0], 70, 0));
const string TestString = "0123456789abcdef";
byte[] buffer = Encoding.UTF8.GetBytes(TestString);
s.EncodeBytes(buffer, 0, buffer.Length);
string encodedString = s.GetEncodedString();
Assert.Equal("MDEyMzQ1Njc4OWFiY2RlZg==", encodedString);
byte[] stringToDecode = Encoding.ASCII.GetBytes(encodedString);
int result = s.DecodeBytes(stringToDecode, 0, encodedString.Length);
Assert.Equal(TestString, Encoding.UTF8.GetString(stringToDecode, 0, result));
}
[Fact]
public void Base64Stream_EncodeString_WithVerySmallBuffer_ShouldTriggerBufferResize_AndShouldEncodeProperly()
{
var s = new Base64Stream(new Base64WriteStateInfo(10, new byte[0], new byte[0], 70, 0));
const string TestString = "0123456789abcdef";
s.EncodeString(TestString, Encoding.UTF8);
string encodedString = s.GetEncodedString();
Assert.Equal("MDEyMzQ1Njc4OWFiY2RlZg==", encodedString);
byte[] stringToDecode = Encoding.ASCII.GetBytes(encodedString);
int result = s.DecodeBytes(stringToDecode, 0, encodedString.Length);
Assert.Equal(TestString, Encoding.UTF8.GetString(stringToDecode, 0, result));
}
[Fact]
public void Base64Stream_WithVeryLongString_ShouldEncodeProperly()
{
var writeStateInfo = new Base64WriteStateInfo(10, new byte[0], new byte[0], 70, 0);
var s = new Base64Stream(writeStateInfo);
byte[] buffer = Encoding.UTF8.GetBytes(LongString);
s.EncodeBytes(buffer, 0, buffer.Length);
string encodedString = s.GetEncodedString();
byte[] stringToDecode = Encoding.ASCII.GetBytes(encodedString);
int result = s.DecodeBytes(stringToDecode, 0, encodedString.Length);
Assert.Equal(LongString, Encoding.UTF8.GetString(stringToDecode, 0, result));
}
[Fact]
public void Base64Stream_EncodeString_WithVeryLongString_ShouldEncodeProperly()
{
var writeStateInfo = new Base64WriteStateInfo(10, new byte[0], new byte[0], 70, 0);
var s = new Base64Stream(writeStateInfo);
s.EncodeString(LongString, Encoding.UTF8);
string encodedString = s.GetEncodedString();
byte[] stringToDecode = Encoding.ASCII.GetBytes(encodedString);
int result = s.DecodeBytes(stringToDecode, 0, encodedString.Length);
Assert.Equal(LongString, Encoding.UTF8.GetString(stringToDecode, 0, result));
}
private const string LongString =
@"01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567";
}
}
| // 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 Xunit;
namespace System.Net.Mime.Tests
{
public class Base64EncodingTest
{
[Theory]
[InlineData("some test header to base64 encode")]
[InlineData("some test h\xE9ader to base64asdf\xE9\xE5")]
public void Base64Stream_WithBasicAsciiString_ShouldEncodeAndDecode(string testHeader)
{
var s = new Base64Stream(new Base64WriteStateInfo());
var testHeaderBytes = Encoding.UTF8.GetBytes(testHeader);
s.EncodeBytes(testHeaderBytes, 0, testHeaderBytes.Length);
string encodedString = s.GetEncodedString();
for (int i = 0; i < encodedString.Length; i++)
{
Assert.InRange((byte)encodedString[i], 0, 127);
}
byte[] stringToDecode = Encoding.ASCII.GetBytes(encodedString);
int result = s.DecodeBytes(stringToDecode, 0, encodedString.Length);
Assert.Equal(testHeader, Encoding.UTF8.GetString(stringToDecode, 0, result));
}
[Theory]
[InlineData("some test header to base64 encode")]
[InlineData("some test h\xE9ader to base64asdf\xE9\xE5")]
public void Base64Stream_EncodeString_WithBasicAsciiString_ShouldEncodeAndDecode(string testHeader)
{
var s = new Base64Stream(new Base64WriteStateInfo());
s.EncodeString(testHeader, Encoding.UTF8);
string encodedString = s.GetEncodedString();
for (int i = 0; i < encodedString.Length; i++)
{
Assert.InRange((byte)encodedString[i], 0, 127);
}
byte[] stringToDecode = Encoding.ASCII.GetBytes(encodedString);
int result = s.DecodeBytes(stringToDecode, 0, encodedString.Length);
Assert.Equal(testHeader, Encoding.UTF8.GetString(stringToDecode, 0, result));
}
[Fact]
public void Base64Stream_WithVerySmallBuffer_ShouldTriggerBufferResize_AndShouldEncodeProperly()
{
var s = new Base64Stream(new Base64WriteStateInfo(10, new byte[0], new byte[0], 70, 0));
const string TestString = "0123456789abcdef";
byte[] buffer = Encoding.UTF8.GetBytes(TestString);
s.EncodeBytes(buffer, 0, buffer.Length);
string encodedString = s.GetEncodedString();
Assert.Equal("MDEyMzQ1Njc4OWFiY2RlZg==", encodedString);
byte[] stringToDecode = Encoding.ASCII.GetBytes(encodedString);
int result = s.DecodeBytes(stringToDecode, 0, encodedString.Length);
Assert.Equal(TestString, Encoding.UTF8.GetString(stringToDecode, 0, result));
}
[Fact]
public void Base64Stream_EncodeString_WithVerySmallBuffer_ShouldTriggerBufferResize_AndShouldEncodeProperly()
{
var s = new Base64Stream(new Base64WriteStateInfo(10, new byte[0], new byte[0], 70, 0));
const string TestString = "0123456789abcdef";
s.EncodeString(TestString, Encoding.UTF8);
string encodedString = s.GetEncodedString();
Assert.Equal("MDEyMzQ1Njc4OWFiY2RlZg==", encodedString);
byte[] stringToDecode = Encoding.ASCII.GetBytes(encodedString);
int result = s.DecodeBytes(stringToDecode, 0, encodedString.Length);
Assert.Equal(TestString, Encoding.UTF8.GetString(stringToDecode, 0, result));
}
[Fact]
public void Base64Stream_WithVeryLongString_ShouldEncodeProperly()
{
var writeStateInfo = new Base64WriteStateInfo(10, new byte[0], new byte[0], 70, 0);
var s = new Base64Stream(writeStateInfo);
byte[] buffer = Encoding.UTF8.GetBytes(LongString);
s.EncodeBytes(buffer, 0, buffer.Length);
string encodedString = s.GetEncodedString();
byte[] stringToDecode = Encoding.ASCII.GetBytes(encodedString);
int result = s.DecodeBytes(stringToDecode, 0, encodedString.Length);
Assert.Equal(LongString, Encoding.UTF8.GetString(stringToDecode, 0, result));
}
[Fact]
public void Base64Stream_EncodeString_WithVeryLongString_ShouldEncodeProperly()
{
var writeStateInfo = new Base64WriteStateInfo(10, new byte[0], new byte[0], 70, 0);
var s = new Base64Stream(writeStateInfo);
s.EncodeString(LongString, Encoding.UTF8);
string encodedString = s.GetEncodedString();
byte[] stringToDecode = Encoding.ASCII.GetBytes(encodedString);
int result = s.DecodeBytes(stringToDecode, 0, encodedString.Length);
Assert.Equal(LongString, Encoding.UTF8.GetString(stringToDecode, 0, result));
}
private const string LongString =
@"01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567
01234567
11234567
21234567
31234567
41234567
51234567
61234567
71234567
81234567
91234567";
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Globalization/tests/CultureInfo/CultureInfoIsNeutralCulture.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using Xunit;
namespace System.Globalization.Tests
{
public class CultureInfoIsNeutralCulture
{
public static IEnumerable<object[]> IsNeutralCulture_TestData()
{
yield return new object[] { new CultureInfo(CultureInfo.InvariantCulture.Name), false };
yield return new object[] { CultureInfo.InvariantCulture, false };
yield return new object[] { new CultureInfo("fr-FR"), false };
yield return new object[] { new CultureInfo("fr"), true };
}
[Theory]
[MemberData(nameof(IsNeutralCulture_TestData))]
public void IsNeutralCulture(CultureInfo culture, bool expected)
{
Assert.Equal(expected, culture.IsNeutralCulture);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using Xunit;
namespace System.Globalization.Tests
{
public class CultureInfoIsNeutralCulture
{
public static IEnumerable<object[]> IsNeutralCulture_TestData()
{
yield return new object[] { new CultureInfo(CultureInfo.InvariantCulture.Name), false };
yield return new object[] { CultureInfo.InvariantCulture, false };
yield return new object[] { new CultureInfo("fr-FR"), false };
yield return new object[] { new CultureInfo("fr"), true };
}
[Theory]
[MemberData(nameof(IsNeutralCulture_TestData))]
public void IsNeutralCulture(CultureInfo culture, bool expected)
{
Assert.Equal(expected, culture.IsNeutralCulture);
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Speech/src/Internal/SapiInterop/SapiRecognizer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Speech.Internal.ObjectTokens;
using System.Speech.Recognition;
namespace System.Speech.Internal.SapiInterop
{
internal class SapiRecognizer : IDisposable
{
#region Constructors
internal SapiRecognizer(RecognizerType type)
{
ISpRecognizer recognizer;
try
{
if (type == RecognizerType.InProc)
{
recognizer = (ISpRecognizer)new SpInprocRecognizer();
}
else
{
recognizer = (ISpRecognizer)new SpSharedRecognizer();
}
_isSap53 = recognizer is ISpRecognizer2;
}
catch (COMException e)
{
throw RecognizerBase.ExceptionFromSapiCreateRecognizerError(e);
}
// Back out if the recognizer we have SAPI 5.1
if (!IsSapi53 && System.Threading.Thread.CurrentThread.GetApartmentState() == System.Threading.ApartmentState.STA)
{
// must be recreated on a different thread
Marshal.ReleaseComObject(recognizer);
_proxy = new SapiProxy.MTAThread(type);
}
else
{
_proxy = new SapiProxy.PassThrough(recognizer);
}
}
public void Dispose()
{
if (!_disposed)
{
_proxy.Dispose();
_disposed = true;
}
GC.SuppressFinalize(this);
}
#endregion
#region Internal Methods
// ISpProperties Methods
internal void SetPropertyNum(string name, int value)
{
_proxy.Invoke2(delegate { SetProperty(_proxy.Recognizer, name, value); });
}
internal int GetPropertyNum(string name)
{
return (int)_proxy.Invoke(delegate { return GetProperty(_proxy.Recognizer, name, true); });
}
internal void SetPropertyString(string name, string value)
{
_proxy.Invoke2(delegate { SetProperty(_proxy.Recognizer, name, value); });
}
internal string GetPropertyString(string name)
{
return (string)_proxy.Invoke(delegate { return GetProperty(_proxy.Recognizer, name, false); });
}
// ISpRecognizer Methods
internal void SetRecognizer(ISpObjectToken recognizer)
{
try
{
_proxy.Invoke2(delegate { _proxy.Recognizer.SetRecognizer(recognizer); });
}
catch (InvalidCastException)
{
// The Interop layer maps the SAPI error that an interface cannot by QI to an Invalid cast exception
// Map the InvalidCastException
throw new PlatformNotSupportedException(SR.Get(SRID.NotSupportedWithThisVersionOfSAPI));
}
}
internal RecognizerInfo GetRecognizerInfo()
{
ISpObjectToken sapiObjectToken;
return (RecognizerInfo)_proxy.Invoke(delegate
{
RecognizerInfo recognizerInfo;
_proxy.Recognizer.GetRecognizer(out sapiObjectToken);
IntPtr sapiTokenId;
try
{
sapiObjectToken.GetId(out sapiTokenId);
string tokenId = Marshal.PtrToStringUni(sapiTokenId);
recognizerInfo = RecognizerInfo.Create(ObjectToken.Open(null, tokenId, false));
if (recognizerInfo == null)
{
throw new InvalidOperationException(SR.Get(SRID.RecognizerNotFound));
}
Marshal.FreeCoTaskMem(sapiTokenId);
}
finally
{
Marshal.ReleaseComObject(sapiObjectToken);
}
return recognizerInfo;
});
}
internal void SetInput(object input, bool allowFormatChanges)
{
_proxy.Invoke2(delegate { _proxy.Recognizer.SetInput(input, allowFormatChanges); });
}
internal SapiRecoContext CreateRecoContext()
{
ISpRecoContext context;
return (SapiRecoContext)_proxy.Invoke(delegate { _proxy.Recognizer.CreateRecoContext(out context); return new SapiRecoContext(context, _proxy); });
}
internal SPRECOSTATE GetRecoState()
{
SPRECOSTATE state;
return (SPRECOSTATE)_proxy.Invoke(delegate { _proxy.Recognizer.GetRecoState(out state); return state; });
}
internal void SetRecoState(SPRECOSTATE state)
{
_proxy.Invoke2(delegate { _proxy.Recognizer.SetRecoState(state); });
}
internal SPRECOGNIZERSTATUS GetStatus()
{
SPRECOGNIZERSTATUS status;
return (SPRECOGNIZERSTATUS)_proxy.Invoke(delegate { _proxy.Recognizer.GetStatus(out status); return status; });
}
internal IntPtr GetFormat(SPSTREAMFORMATTYPE WaveFormatType)
{
return (IntPtr)_proxy.Invoke(delegate
{
Guid formatId;
IntPtr ppCoMemWFEX;
_proxy.Recognizer.GetFormat(WaveFormatType, out formatId, out ppCoMemWFEX); return ppCoMemWFEX;
});
}
internal SAPIErrorCodes EmulateRecognition(string phrase)
{
object displayAttributes = " "; // Passing a null object here doesn't work because EmulateRecognition doesn't handle VT_EMPTY
return (SAPIErrorCodes)_proxy.Invoke(delegate { return _proxy.SapiSpeechRecognizer.EmulateRecognition(phrase, ref displayAttributes, 0); });
}
internal SAPIErrorCodes EmulateRecognition(ISpPhrase iSpPhrase, uint dwCompareFlags)
{
return (SAPIErrorCodes)_proxy.Invoke(delegate { return _proxy.Recognizer2.EmulateRecognitionEx(iSpPhrase, dwCompareFlags); });
}
#endregion
#region Internal Properties
internal bool IsSapi53
{
get
{
return _isSap53;
}
}
#endregion
#region Internal Types
internal enum RecognizerType
{
InProc,
Shared
}
#endregion
#region Private Methods
private static void SetProperty(ISpRecognizer sapiRecognizer, string name, object value)
{
SAPIErrorCodes errorCode;
if (value is int)
{
errorCode = (SAPIErrorCodes)sapiRecognizer.SetPropertyNum(name, (int)value);
}
else
{
errorCode = (SAPIErrorCodes)sapiRecognizer.SetPropertyString(name, (string)value);
}
if (errorCode == SAPIErrorCodes.S_FALSE)
{
throw new KeyNotFoundException(SR.Get(SRID.RecognizerSettingNotSupported));
}
else if (errorCode < SAPIErrorCodes.S_OK)
{
throw RecognizerBase.ExceptionFromSapiCreateRecognizerError(new COMException(SR.Get(SRID.RecognizerSettingUpdateError), (int)errorCode));
}
}
private static object GetProperty(ISpRecognizer sapiRecognizer, string name, bool integer)
{
SAPIErrorCodes errorCode;
object result = null;
if (integer)
{
int value;
errorCode = (SAPIErrorCodes)sapiRecognizer.GetPropertyNum(name, out value);
result = value;
}
else
{
string value;
errorCode = (SAPIErrorCodes)sapiRecognizer.GetPropertyString(name, out value);
result = value;
}
if (errorCode == SAPIErrorCodes.S_FALSE)
{
throw new KeyNotFoundException(SR.Get(SRID.RecognizerSettingNotSupported));
}
else if (errorCode < SAPIErrorCodes.S_OK)
{
throw RecognizerBase.ExceptionFromSapiCreateRecognizerError(new COMException(SR.Get(SRID.RecognizerSettingUpdateError), (int)errorCode));
}
return result;
}
#endregion
#region Private Fields
private SapiProxy _proxy;
private bool _disposed;
private bool _isSap53;
#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.Runtime.InteropServices;
using System.Speech.Internal.ObjectTokens;
using System.Speech.Recognition;
namespace System.Speech.Internal.SapiInterop
{
internal class SapiRecognizer : IDisposable
{
#region Constructors
internal SapiRecognizer(RecognizerType type)
{
ISpRecognizer recognizer;
try
{
if (type == RecognizerType.InProc)
{
recognizer = (ISpRecognizer)new SpInprocRecognizer();
}
else
{
recognizer = (ISpRecognizer)new SpSharedRecognizer();
}
_isSap53 = recognizer is ISpRecognizer2;
}
catch (COMException e)
{
throw RecognizerBase.ExceptionFromSapiCreateRecognizerError(e);
}
// Back out if the recognizer we have SAPI 5.1
if (!IsSapi53 && System.Threading.Thread.CurrentThread.GetApartmentState() == System.Threading.ApartmentState.STA)
{
// must be recreated on a different thread
Marshal.ReleaseComObject(recognizer);
_proxy = new SapiProxy.MTAThread(type);
}
else
{
_proxy = new SapiProxy.PassThrough(recognizer);
}
}
public void Dispose()
{
if (!_disposed)
{
_proxy.Dispose();
_disposed = true;
}
GC.SuppressFinalize(this);
}
#endregion
#region Internal Methods
// ISpProperties Methods
internal void SetPropertyNum(string name, int value)
{
_proxy.Invoke2(delegate { SetProperty(_proxy.Recognizer, name, value); });
}
internal int GetPropertyNum(string name)
{
return (int)_proxy.Invoke(delegate { return GetProperty(_proxy.Recognizer, name, true); });
}
internal void SetPropertyString(string name, string value)
{
_proxy.Invoke2(delegate { SetProperty(_proxy.Recognizer, name, value); });
}
internal string GetPropertyString(string name)
{
return (string)_proxy.Invoke(delegate { return GetProperty(_proxy.Recognizer, name, false); });
}
// ISpRecognizer Methods
internal void SetRecognizer(ISpObjectToken recognizer)
{
try
{
_proxy.Invoke2(delegate { _proxy.Recognizer.SetRecognizer(recognizer); });
}
catch (InvalidCastException)
{
// The Interop layer maps the SAPI error that an interface cannot by QI to an Invalid cast exception
// Map the InvalidCastException
throw new PlatformNotSupportedException(SR.Get(SRID.NotSupportedWithThisVersionOfSAPI));
}
}
internal RecognizerInfo GetRecognizerInfo()
{
ISpObjectToken sapiObjectToken;
return (RecognizerInfo)_proxy.Invoke(delegate
{
RecognizerInfo recognizerInfo;
_proxy.Recognizer.GetRecognizer(out sapiObjectToken);
IntPtr sapiTokenId;
try
{
sapiObjectToken.GetId(out sapiTokenId);
string tokenId = Marshal.PtrToStringUni(sapiTokenId);
recognizerInfo = RecognizerInfo.Create(ObjectToken.Open(null, tokenId, false));
if (recognizerInfo == null)
{
throw new InvalidOperationException(SR.Get(SRID.RecognizerNotFound));
}
Marshal.FreeCoTaskMem(sapiTokenId);
}
finally
{
Marshal.ReleaseComObject(sapiObjectToken);
}
return recognizerInfo;
});
}
internal void SetInput(object input, bool allowFormatChanges)
{
_proxy.Invoke2(delegate { _proxy.Recognizer.SetInput(input, allowFormatChanges); });
}
internal SapiRecoContext CreateRecoContext()
{
ISpRecoContext context;
return (SapiRecoContext)_proxy.Invoke(delegate { _proxy.Recognizer.CreateRecoContext(out context); return new SapiRecoContext(context, _proxy); });
}
internal SPRECOSTATE GetRecoState()
{
SPRECOSTATE state;
return (SPRECOSTATE)_proxy.Invoke(delegate { _proxy.Recognizer.GetRecoState(out state); return state; });
}
internal void SetRecoState(SPRECOSTATE state)
{
_proxy.Invoke2(delegate { _proxy.Recognizer.SetRecoState(state); });
}
internal SPRECOGNIZERSTATUS GetStatus()
{
SPRECOGNIZERSTATUS status;
return (SPRECOGNIZERSTATUS)_proxy.Invoke(delegate { _proxy.Recognizer.GetStatus(out status); return status; });
}
internal IntPtr GetFormat(SPSTREAMFORMATTYPE WaveFormatType)
{
return (IntPtr)_proxy.Invoke(delegate
{
Guid formatId;
IntPtr ppCoMemWFEX;
_proxy.Recognizer.GetFormat(WaveFormatType, out formatId, out ppCoMemWFEX); return ppCoMemWFEX;
});
}
internal SAPIErrorCodes EmulateRecognition(string phrase)
{
object displayAttributes = " "; // Passing a null object here doesn't work because EmulateRecognition doesn't handle VT_EMPTY
return (SAPIErrorCodes)_proxy.Invoke(delegate { return _proxy.SapiSpeechRecognizer.EmulateRecognition(phrase, ref displayAttributes, 0); });
}
internal SAPIErrorCodes EmulateRecognition(ISpPhrase iSpPhrase, uint dwCompareFlags)
{
return (SAPIErrorCodes)_proxy.Invoke(delegate { return _proxy.Recognizer2.EmulateRecognitionEx(iSpPhrase, dwCompareFlags); });
}
#endregion
#region Internal Properties
internal bool IsSapi53
{
get
{
return _isSap53;
}
}
#endregion
#region Internal Types
internal enum RecognizerType
{
InProc,
Shared
}
#endregion
#region Private Methods
private static void SetProperty(ISpRecognizer sapiRecognizer, string name, object value)
{
SAPIErrorCodes errorCode;
if (value is int)
{
errorCode = (SAPIErrorCodes)sapiRecognizer.SetPropertyNum(name, (int)value);
}
else
{
errorCode = (SAPIErrorCodes)sapiRecognizer.SetPropertyString(name, (string)value);
}
if (errorCode == SAPIErrorCodes.S_FALSE)
{
throw new KeyNotFoundException(SR.Get(SRID.RecognizerSettingNotSupported));
}
else if (errorCode < SAPIErrorCodes.S_OK)
{
throw RecognizerBase.ExceptionFromSapiCreateRecognizerError(new COMException(SR.Get(SRID.RecognizerSettingUpdateError), (int)errorCode));
}
}
private static object GetProperty(ISpRecognizer sapiRecognizer, string name, bool integer)
{
SAPIErrorCodes errorCode;
object result = null;
if (integer)
{
int value;
errorCode = (SAPIErrorCodes)sapiRecognizer.GetPropertyNum(name, out value);
result = value;
}
else
{
string value;
errorCode = (SAPIErrorCodes)sapiRecognizer.GetPropertyString(name, out value);
result = value;
}
if (errorCode == SAPIErrorCodes.S_FALSE)
{
throw new KeyNotFoundException(SR.Get(SRID.RecognizerSettingNotSupported));
}
else if (errorCode < SAPIErrorCodes.S_OK)
{
throw RecognizerBase.ExceptionFromSapiCreateRecognizerError(new COMException(SR.Get(SRID.RecognizerSettingUpdateError), (int)errorCode));
}
return result;
}
#endregion
#region Private Fields
private SapiProxy _proxy;
private bool _disposed;
private bool _isSap53;
#endregion
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/CodeGenBringUpTests/mul2_r.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="mul2.cs" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="mul2.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b52572/b52572.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
namespace Test
{
using System;
class AA
{
static void Grind() { throw new Exception(); }
static void Main1()
{
int A = 1;
int B = 0;
while (B > -1) { Grind(); }
while (A > 0)
{
do
{
while (B != A) Grind();
} while (B > A);
}
}
static int Main()
{
try
{
Main1();
return 101;
}
catch (Exception)
{
return 100;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
namespace Test
{
using System;
class AA
{
static void Grind() { throw new Exception(); }
static void Main1()
{
int A = 1;
int B = 0;
while (B > -1) { Grind(); }
while (A > 0)
{
do
{
while (B != A) Grind();
} while (B > A);
}
}
static int Main()
{
try
{
Main1();
return 101;
}
catch (Exception)
{
return 100;
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/ShiftRightLogicalRoundedNarrowingSaturateScalar.Vector64.Byte.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 ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1()
{
var test = new ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1
{
private struct DataTable
{
private byte[] inArray;
private byte[] outArray;
private GCHandle inHandle;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt16[] inArray, Byte[] outArray, int alignment)
{
int sizeOfinArray = inArray.Length * Unsafe.SizeOf<UInt16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<UInt16, byte>(ref inArray[0]), (uint)sizeOfinArray);
}
public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<UInt16> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1 testClass)
{
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(_fld, 3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1 testClass)
{
fixed (Vector64<UInt16>* pFld = &_fld)
{
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(
AdvSimd.LoadVector64((UInt16*)(pFld)),
3
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte);
private static readonly byte Imm = 3;
private static UInt16[] _data = new UInt16[Op1ElementCount];
private static Vector64<UInt16> _clsVar;
private Vector64<UInt16> _fld;
private DataTable _dataTable;
static ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
}
public ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data, new Byte[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.ShiftRightLogicalRoundedNarrowingSaturateScalar(
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArrayPtr),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArrayPtr)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar), new Type[] { typeof(Vector64<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArrayPtr),
(byte)3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar), new Type[] { typeof(Vector64<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArrayPtr)),
(byte)3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(
_clsVar,
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<UInt16>* pClsVar = &_clsVar)
{
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(
AdvSimd.LoadVector64((UInt16*)(pClsVar)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArrayPtr);
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(firstOp, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArrayPtr));
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(firstOp, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1();
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(test._fld, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1();
fixed (Vector64<UInt16>* pFld = &test._fld)
{
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(
AdvSimd.LoadVector64((UInt16*)(pFld)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(_fld, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<UInt16>* pFld = &_fld)
{
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(
AdvSimd.LoadVector64((UInt16*)(pFld)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(test._fld, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(
AdvSimd.LoadVector64((UInt16*)(&test._fld)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<UInt16> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt16[] firstOp, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Helpers.ShiftRightLogicalRoundedNarrowingSaturate(firstOp[0], Imm) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != 0)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar)}<Byte>(Vector64<UInt16>, 3): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1()
{
var test = new ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1
{
private struct DataTable
{
private byte[] inArray;
private byte[] outArray;
private GCHandle inHandle;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt16[] inArray, Byte[] outArray, int alignment)
{
int sizeOfinArray = inArray.Length * Unsafe.SizeOf<UInt16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<UInt16, byte>(ref inArray[0]), (uint)sizeOfinArray);
}
public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<UInt16> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1 testClass)
{
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(_fld, 3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1 testClass)
{
fixed (Vector64<UInt16>* pFld = &_fld)
{
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(
AdvSimd.LoadVector64((UInt16*)(pFld)),
3
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte);
private static readonly byte Imm = 3;
private static UInt16[] _data = new UInt16[Op1ElementCount];
private static Vector64<UInt16> _clsVar;
private Vector64<UInt16> _fld;
private DataTable _dataTable;
static ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
}
public ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data, new Byte[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.ShiftRightLogicalRoundedNarrowingSaturateScalar(
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArrayPtr),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArrayPtr)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar), new Type[] { typeof(Vector64<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<UInt16>>(_dataTable.inArrayPtr),
(byte)3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar), new Type[] { typeof(Vector64<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((UInt16*)(_dataTable.inArrayPtr)),
(byte)3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(
_clsVar,
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<UInt16>* pClsVar = &_clsVar)
{
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(
AdvSimd.LoadVector64((UInt16*)(pClsVar)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArrayPtr);
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(firstOp, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArrayPtr));
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(firstOp, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1();
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(test._fld, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1();
fixed (Vector64<UInt16>* pFld = &test._fld)
{
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(
AdvSimd.LoadVector64((UInt16*)(pFld)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(_fld, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<UInt16>* pFld = &_fld)
{
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(
AdvSimd.LoadVector64((UInt16*)(pFld)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(test._fld, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(
AdvSimd.LoadVector64((UInt16*)(&test._fld)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<UInt16> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt16[] firstOp, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Helpers.ShiftRightLogicalRoundedNarrowingSaturate(firstOp[0], Imm) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != 0)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar)}<Byte>(Vector64<UInt16>, 3): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/Microsoft.NETCore.Platforms/src/Microsoft.NETCore.Platforms.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(NetCoreAppToolCurrent);$(NetFrameworkToolCurrent)</TargetFrameworks>
<EnableBinPlacing>false</EnableBinPlacing>
<!-- This project should not build against the live built .NETCoreApp targeting pack as it contributes to the build itself. -->
<UseLocalTargetingRuntimePack>false</UseLocalTargetingRuntimePack>
<!-- Use targeting pack references instead of granular ones in the project file. -->
<DisableImplicitAssemblyReferences>false</DisableImplicitAssemblyReferences>
<AssemblyName>Microsoft.NETCore.Platforms.BuildTasks</AssemblyName>
<IncludeBuildOutput>false</IncludeBuildOutput>
<IncludeSymbols>false</IncludeSymbols>
<IsPackable>true</IsPackable>
<PackageId>$(MSBuildProjectName)</PackageId>
<SuppressDependenciesWhenPacking>true</SuppressDependenciesWhenPacking>
<PackageDescription>Provides runtime information required to resolve target framework, platform, and runtime specific implementations of .NETCore packages.</PackageDescription>
<NoWarn>$(NoWarn);NU5128</NoWarn> <!-- No Dependencies-->
<AvoidRestoreCycleOnSelfReference>true</AvoidRestoreCycleOnSelfReference>
<!-- TODO: Remove with AvoidRestoreCycleOnSelfReference hack. -->
<PackageValidationBaselineName>$(MSBuildProjectName)</PackageValidationBaselineName>
<BeforePack>GenerateRuntimeJson;UpdateRuntimeJson;$(BeforePack)</BeforePack>
<_generateRuntimeGraphTargetFramework Condition="'$(MSBuildRuntimeType)' == 'core'">$(NetCoreAppToolCurrent)</_generateRuntimeGraphTargetFramework>
<_generateRuntimeGraphTargetFramework Condition="'$(MSBuildRuntimeType)' != 'core'">net472</_generateRuntimeGraphTargetFramework>
<_generateRuntimeGraphTask>$([MSBuild]::NormalizePath('$(BaseOutputPath)', $(Configuration), '$(_generateRuntimeGraphTargetFramework)', '$(AssemblyName).dll'))</_generateRuntimeGraphTask>
<!-- When building from source, ensure the RID we're building for is part of the RID graph -->
<AdditionalRuntimeIdentifiers Condition="'$(DotNetBuildFromSource)' == 'true'">$(AdditionalRuntimeIdentifiers);$(OutputRID)</AdditionalRuntimeIdentifiers>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
<Compile Include="BuildTask.Desktop.cs" />
<Compile Include="AssemblyResolver.cs" />
<Compile Include="$(CoreLibSharedDir)System\Diagnostics\CodeAnalysis\UnconditionalSuppressMessageAttribute.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="BuildTask.cs" />
<Compile Include="Extensions.cs" />
<Compile Include="GenerateRuntimeGraph.cs" />
<Compile Include="RID.cs" />
<Compile Include="RuntimeGroupCollection.cs" />
<Compile Include="RuntimeGroup.cs" />
<Compile Include="RuntimeVersion.cs" />
</ItemGroup>
<ItemGroup>
<Content Condition="'$(AdditionalRuntimeIdentifiers)' == ''" Include="runtime.json" PackagePath="/" />
<Content Condition="'$(AdditionalRuntimeIdentifiers)' != ''" Include="$(IntermediateOutputPath)runtime.json" PackagePath="/" />
<Content Include="$(PlaceholderFile)" PackagePath="lib/netstandard1.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Build.Tasks.Core" Version="$(MicrosoftBuildTasksCoreVersion)" />
<PackageReference Include="NuGet.ProjectModel" Version="$(NugetProjectModelVersion)" />
<PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" />
</ItemGroup>
<Import Project="runtimeGroups.props" />
<UsingTask TaskName="GenerateRuntimeGraph" AssemblyFile="$(_generateRuntimeGraphTask)"/>
<Target Name="GenerateRuntimeJson" Condition="'$(AdditionalRuntimeIdentifiers)' != ''">
<MakeDir Directories="$(IntermediateOutputPath)" />
<GenerateRuntimeGraph RuntimeGroups="@(RuntimeGroupWithQualifiers)"
AdditionalRuntimeIdentifiers="$(AdditionalRuntimeIdentifiers)"
AdditionalRuntimeIdentifierParent="$(AdditionalRuntimeIdentifierParent)"
RuntimeJson="$(IntermediateOutputPath)runtime.json"
UpdateRuntimeFiles="True" />
</Target>
<Target Name="UpdateRuntimeJson">
<!-- Generates a Runtime graph using RuntimeGroups and diffs it with the graph described by runtime.json and runtime.compatibility.json
Specifying UpdateRuntimeFiles=true skips the diff and updates those files.
The graph can be visualized using the generated dmgl -->
<MakeDir Directories="$(OutputPath)" />
<GenerateRuntimeGraph RuntimeGroups="@(RuntimeGroupWithQualifiers)"
RuntimeJson="runtime.json"
CompatibilityMap="runtime.compatibility.json"
RuntimeDirectedGraph="$(OutputPath)runtime.json.dgml"
UpdateRuntimeFiles="$(UpdateRuntimeFiles)" />
</Target>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(NetCoreAppToolCurrent);$(NetFrameworkToolCurrent)</TargetFrameworks>
<EnableBinPlacing>false</EnableBinPlacing>
<!-- This project should not build against the live built .NETCoreApp targeting pack as it contributes to the build itself. -->
<UseLocalTargetingRuntimePack>false</UseLocalTargetingRuntimePack>
<!-- Use targeting pack references instead of granular ones in the project file. -->
<DisableImplicitAssemblyReferences>false</DisableImplicitAssemblyReferences>
<AssemblyName>Microsoft.NETCore.Platforms.BuildTasks</AssemblyName>
<IncludeBuildOutput>false</IncludeBuildOutput>
<IncludeSymbols>false</IncludeSymbols>
<IsPackable>true</IsPackable>
<PackageId>$(MSBuildProjectName)</PackageId>
<SuppressDependenciesWhenPacking>true</SuppressDependenciesWhenPacking>
<PackageDescription>Provides runtime information required to resolve target framework, platform, and runtime specific implementations of .NETCore packages.</PackageDescription>
<NoWarn>$(NoWarn);NU5128</NoWarn> <!-- No Dependencies-->
<AvoidRestoreCycleOnSelfReference>true</AvoidRestoreCycleOnSelfReference>
<!-- TODO: Remove with AvoidRestoreCycleOnSelfReference hack. -->
<PackageValidationBaselineName>$(MSBuildProjectName)</PackageValidationBaselineName>
<BeforePack>GenerateRuntimeJson;UpdateRuntimeJson;$(BeforePack)</BeforePack>
<_generateRuntimeGraphTargetFramework Condition="'$(MSBuildRuntimeType)' == 'core'">$(NetCoreAppToolCurrent)</_generateRuntimeGraphTargetFramework>
<_generateRuntimeGraphTargetFramework Condition="'$(MSBuildRuntimeType)' != 'core'">net472</_generateRuntimeGraphTargetFramework>
<_generateRuntimeGraphTask>$([MSBuild]::NormalizePath('$(BaseOutputPath)', $(Configuration), '$(_generateRuntimeGraphTargetFramework)', '$(AssemblyName).dll'))</_generateRuntimeGraphTask>
<!-- When building from source, ensure the RID we're building for is part of the RID graph -->
<AdditionalRuntimeIdentifiers Condition="'$(DotNetBuildFromSource)' == 'true'">$(AdditionalRuntimeIdentifiers);$(OutputRID)</AdditionalRuntimeIdentifiers>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
<Compile Include="BuildTask.Desktop.cs" />
<Compile Include="AssemblyResolver.cs" />
<Compile Include="$(CoreLibSharedDir)System\Diagnostics\CodeAnalysis\UnconditionalSuppressMessageAttribute.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="BuildTask.cs" />
<Compile Include="Extensions.cs" />
<Compile Include="GenerateRuntimeGraph.cs" />
<Compile Include="RID.cs" />
<Compile Include="RuntimeGroupCollection.cs" />
<Compile Include="RuntimeGroup.cs" />
<Compile Include="RuntimeVersion.cs" />
</ItemGroup>
<ItemGroup>
<Content Condition="'$(AdditionalRuntimeIdentifiers)' == ''" Include="runtime.json" PackagePath="/" />
<Content Condition="'$(AdditionalRuntimeIdentifiers)' != ''" Include="$(IntermediateOutputPath)runtime.json" PackagePath="/" />
<Content Include="$(PlaceholderFile)" PackagePath="lib/netstandard1.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Build.Tasks.Core" Version="$(MicrosoftBuildTasksCoreVersion)" />
<PackageReference Include="NuGet.ProjectModel" Version="$(NugetProjectModelVersion)" />
<PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" />
</ItemGroup>
<Import Project="runtimeGroups.props" />
<UsingTask TaskName="GenerateRuntimeGraph" AssemblyFile="$(_generateRuntimeGraphTask)"/>
<Target Name="GenerateRuntimeJson" Condition="'$(AdditionalRuntimeIdentifiers)' != ''">
<MakeDir Directories="$(IntermediateOutputPath)" />
<GenerateRuntimeGraph RuntimeGroups="@(RuntimeGroupWithQualifiers)"
AdditionalRuntimeIdentifiers="$(AdditionalRuntimeIdentifiers)"
AdditionalRuntimeIdentifierParent="$(AdditionalRuntimeIdentifierParent)"
RuntimeJson="$(IntermediateOutputPath)runtime.json"
UpdateRuntimeFiles="True" />
</Target>
<Target Name="UpdateRuntimeJson">
<!-- Generates a Runtime graph using RuntimeGroups and diffs it with the graph described by runtime.json and runtime.compatibility.json
Specifying UpdateRuntimeFiles=true skips the diff and updates those files.
The graph can be visualized using the generated dmgl -->
<MakeDir Directories="$(OutputPath)" />
<GenerateRuntimeGraph RuntimeGroups="@(RuntimeGroupWithQualifiers)"
RuntimeJson="runtime.json"
CompatibilityMap="runtime.compatibility.json"
RuntimeDirectedGraph="$(OutputPath)runtime.json.dgml"
UpdateRuntimeFiles="$(UpdateRuntimeFiles)" />
</Target>
</Project>
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/General/Vector128/GreaterThanAll.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\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 GreaterThanAllByte()
{
var test = new VectorBooleanBinaryOpTest__GreaterThanAllByte();
// 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__GreaterThanAllByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
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<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, 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<Byte> _fld1;
public Vector128<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(VectorBooleanBinaryOpTest__GreaterThanAllByte testClass)
{
var result = Vector128.GreaterThanAll(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private DataTable _dataTable;
static VectorBooleanBinaryOpTest__GreaterThanAllByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public VectorBooleanBinaryOpTest__GreaterThanAllByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector128.GreaterThanAll(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_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.GreaterThanAll), new Type[] {
typeof(Vector128<Byte>),
typeof(Vector128<Byte>)
});
if (method is null)
{
method = typeof(Vector128).GetMethod(nameof(Vector128.GreaterThanAll), 1, new Type[] {
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Byte));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector128.GreaterThanAll(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Vector128.GreaterThanAll(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBooleanBinaryOpTest__GreaterThanAllByte();
var result = Vector128.GreaterThanAll(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector128.GreaterThanAll(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector128.GreaterThanAll(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<Byte> op1, Vector128<Byte> op2, bool result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Byte[] left, Byte[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult &= (left[i] > right[i]);
}
succeeded = (expectedResult == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.GreaterThanAll)}<Byte>(Vector128<Byte>, Vector128<Byte>): {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 GreaterThanAllByte()
{
var test = new VectorBooleanBinaryOpTest__GreaterThanAllByte();
// 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__GreaterThanAllByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
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<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, 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<Byte> _fld1;
public Vector128<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(VectorBooleanBinaryOpTest__GreaterThanAllByte testClass)
{
var result = Vector128.GreaterThanAll(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private DataTable _dataTable;
static VectorBooleanBinaryOpTest__GreaterThanAllByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public VectorBooleanBinaryOpTest__GreaterThanAllByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector128.GreaterThanAll(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_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.GreaterThanAll), new Type[] {
typeof(Vector128<Byte>),
typeof(Vector128<Byte>)
});
if (method is null)
{
method = typeof(Vector128).GetMethod(nameof(Vector128.GreaterThanAll), 1, new Type[] {
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Byte));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector128.GreaterThanAll(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Vector128.GreaterThanAll(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBooleanBinaryOpTest__GreaterThanAllByte();
var result = Vector128.GreaterThanAll(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector128.GreaterThanAll(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector128.GreaterThanAll(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<Byte> op1, Vector128<Byte> op2, bool result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Byte[] left, Byte[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult &= (left[i] > right[i]);
}
succeeded = (expectedResult == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.GreaterThanAll)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/X86/Avx2/ConvertToVector256Int64.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.Reflection;
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 ConvertToVector256Int64UInt16()
{
var test = new SimpleUnaryOpTest__ConvertToVector256Int64UInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using the pointer overload
test.RunBasicScenario_Ptr();
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();
// Validates calling via reflection works, using the pointer overload
test.RunReflectionScenario_Ptr();
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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
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__ConvertToVector256Int64UInt16
{
private const int VectorSize = 32;
private const int Op1ElementCount = 16 / sizeof(UInt16);
private const int RetElementCount = VectorSize / sizeof(Int64);
private static UInt16[] _data = new UInt16[Op1ElementCount];
private static Vector128<UInt16> _clsVar;
private Vector128<UInt16> _fld;
private SimpleUnaryOpTest__DataTable<UInt64, UInt16> _dataTable;
static SimpleUnaryOpTest__ConvertToVector256Int64UInt16()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), 16);
}
public SimpleUnaryOpTest__ConvertToVector256Int64UInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), 16);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt64, UInt16>(_data, new UInt64[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.ConvertToVector256Int64(
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Ptr()
{
var result = Avx2.ConvertToVector256Int64(
(UInt16*)(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.ConvertToVector256Int64(
Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.ConvertToVector256Int64(
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Ptr()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(UInt16*) })
.Invoke(null, new object[] {
Pointer.Box(_dataTable.inArrayPtr, typeof(UInt16*))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.ConvertToVector256Int64(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr);
var result = Avx2.ConvertToVector256Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr));
var result = Avx2.ConvertToVector256Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr));
var result = Avx2.ConvertToVector256Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ConvertToVector256Int64UInt16();
var result = Avx2.ConvertToVector256Int64(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.ConvertToVector256Int64(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt16> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), 16);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt16[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
if (result[0] != firstOp[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != firstOp[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ConvertToVector256Int64)}<UInt64>(Vector128<UInt16>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| // 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.Reflection;
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 ConvertToVector256Int64UInt16()
{
var test = new SimpleUnaryOpTest__ConvertToVector256Int64UInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using the pointer overload
test.RunBasicScenario_Ptr();
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();
// Validates calling via reflection works, using the pointer overload
test.RunReflectionScenario_Ptr();
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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
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__ConvertToVector256Int64UInt16
{
private const int VectorSize = 32;
private const int Op1ElementCount = 16 / sizeof(UInt16);
private const int RetElementCount = VectorSize / sizeof(Int64);
private static UInt16[] _data = new UInt16[Op1ElementCount];
private static Vector128<UInt16> _clsVar;
private Vector128<UInt16> _fld;
private SimpleUnaryOpTest__DataTable<UInt64, UInt16> _dataTable;
static SimpleUnaryOpTest__ConvertToVector256Int64UInt16()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), 16);
}
public SimpleUnaryOpTest__ConvertToVector256Int64UInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), 16);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt64, UInt16>(_data, new UInt64[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.ConvertToVector256Int64(
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Ptr()
{
var result = Avx2.ConvertToVector256Int64(
(UInt16*)(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.ConvertToVector256Int64(
Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.ConvertToVector256Int64(
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Ptr()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(UInt16*) })
.Invoke(null, new object[] {
Pointer.Box(_dataTable.inArrayPtr, typeof(UInt16*))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.ConvertToVector256Int64(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr);
var result = Avx2.ConvertToVector256Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr));
var result = Avx2.ConvertToVector256Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr));
var result = Avx2.ConvertToVector256Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ConvertToVector256Int64UInt16();
var result = Avx2.ConvertToVector256Int64(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.ConvertToVector256Int64(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt16> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), 16);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt16[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
if (result[0] != firstOp[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != firstOp[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ConvertToVector256Int64)}<UInt64>(Vector128<UInt16>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/installer/tests/Assets/TestProjects/RuntimeProperties/RuntimeProperties.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>$(NetCoreAppCurrent)</TargetFramework>
<OutputType>Exe</OutputType>
<RuntimeFrameworkVersion>$(MNAVersion)</RuntimeFrameworkVersion>
</PropertyGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>$(NetCoreAppCurrent)</TargetFramework>
<OutputType>Exe</OutputType>
<RuntimeFrameworkVersion>$(MNAVersion)</RuntimeFrameworkVersion>
</PropertyGroup>
</Project>
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnCharacterStringEncodings.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.Runtime.InteropServices;
using System.Text;
namespace System.Formats.Asn1
{
internal static class AsnCharacterStringEncodings
{
private static readonly Encoding s_utf8Encoding =
new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
private static readonly Encoding s_bmpEncoding = new BMPEncoding();
private static readonly Encoding s_ia5Encoding = new IA5Encoding();
private static readonly Encoding s_visibleStringEncoding = new VisibleStringEncoding();
private static readonly Encoding s_numericStringEncoding = new NumericStringEncoding();
private static readonly Encoding s_printableStringEncoding = new PrintableStringEncoding();
private static readonly Encoding s_t61Encoding = new T61Encoding();
internal static Encoding GetEncoding(UniversalTagNumber encodingType) =>
encodingType switch
{
UniversalTagNumber.UTF8String => s_utf8Encoding,
UniversalTagNumber.NumericString => s_numericStringEncoding,
UniversalTagNumber.PrintableString => s_printableStringEncoding,
UniversalTagNumber.IA5String => s_ia5Encoding,
UniversalTagNumber.VisibleString => s_visibleStringEncoding,
UniversalTagNumber.BMPString => s_bmpEncoding,
UniversalTagNumber.T61String => s_t61Encoding,
_ => throw new ArgumentOutOfRangeException(nameof(encodingType), encodingType, null),
};
internal static int GetByteCount(this Encoding encoding, ReadOnlySpan<char> str)
{
if (str.IsEmpty)
{
// Ensure a non-null pointer is obtained, even though the expected answer is 0.
str = string.Empty.AsSpan();
}
unsafe
{
fixed (char* strPtr = &MemoryMarshal.GetReference(str))
{
return encoding.GetByteCount(strPtr, str.Length);
}
}
}
internal static int GetBytes(this Encoding encoding, ReadOnlySpan<char> chars, Span<byte> bytes)
{
if (chars.IsEmpty)
{
// Ensure a non-null pointer is obtained.
chars = string.Empty.AsSpan();
}
if (bytes.IsEmpty)
{
// Ensure a non-null pointer is obtained.
bytes = Array.Empty<byte>();
}
unsafe
{
fixed (char* charsPtr = &MemoryMarshal.GetReference(chars))
fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes))
{
return encoding.GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length);
}
}
}
}
internal abstract class SpanBasedEncoding : Encoding
{
protected SpanBasedEncoding()
: base(0, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback)
{
}
protected abstract int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, bool write);
protected abstract int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars, bool write);
public override int GetByteCount(char[] chars, int index, int count)
{
return GetByteCount(new ReadOnlySpan<char>(chars, index, count));
}
public override unsafe int GetByteCount(char* chars, int count)
{
return GetByteCount(new ReadOnlySpan<char>(chars, count));
}
public override int GetByteCount(string s)
{
return GetByteCount(s.AsSpan());
}
public
#if NETCOREAPP || NETSTANDARD2_1
override
#endif
int GetByteCount(ReadOnlySpan<char> chars)
{
return GetBytes(chars, Span<byte>.Empty, write: false);
}
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
return GetBytes(
new ReadOnlySpan<char>(chars, charIndex, charCount),
new Span<byte>(bytes, byteIndex, bytes.Length - byteIndex),
write: true);
}
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
return GetBytes(
new ReadOnlySpan<char>(chars, charCount),
new Span<byte>(bytes, byteCount),
write: true);
}
public override int GetCharCount(byte[] bytes, int index, int count)
{
return GetCharCount(new ReadOnlySpan<byte>(bytes, index, count));
}
public override unsafe int GetCharCount(byte* bytes, int count)
{
return GetCharCount(new ReadOnlySpan<byte>(bytes, count));
}
public
#if NETCOREAPP || NETSTANDARD2_1
override
#endif
int GetCharCount(ReadOnlySpan<byte> bytes)
{
return GetChars(bytes, Span<char>.Empty, write: false);
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
return GetChars(
new ReadOnlySpan<byte>(bytes, byteIndex, byteCount),
new Span<char>(chars, charIndex, chars.Length - charIndex),
write: true);
}
public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
return GetChars(
new ReadOnlySpan<byte>(bytes, byteCount),
new Span<char>(chars, charCount),
write: true);
}
}
internal sealed class IA5Encoding : RestrictedAsciiStringEncoding
{
// T-REC-X.680-201508 sec 41, Table 8.
// ISO International Register of Coded Character Sets to be used with Escape Sequences 001
// is ASCII 0x00 - 0x1F
// ISO International Register of Coded Character Sets to be used with Escape Sequences 006
// is ASCII 0x21 - 0x7E
// Space is ASCII 0x20, delete is ASCII 0x7F.
//
// The net result is all of 7-bit ASCII
internal IA5Encoding()
: base(0x00, 0x7F)
{
}
}
internal sealed class VisibleStringEncoding : RestrictedAsciiStringEncoding
{
// T-REC-X.680-201508 sec 41, Table 8.
// ISO International Register of Coded Character Sets to be used with Escape Sequences 006
// is ASCII 0x21 - 0x7E
// Space is ASCII 0x20.
internal VisibleStringEncoding()
: base(0x20, 0x7E)
{
}
}
internal sealed class NumericStringEncoding : RestrictedAsciiStringEncoding
{
// T-REC-X.680-201508 sec 41.2 (Table 9)
// 0, 1, ... 9 + space
internal NumericStringEncoding()
: base("0123456789 ")
{
}
}
internal sealed class PrintableStringEncoding : RestrictedAsciiStringEncoding
{
// T-REC-X.680-201508 sec 41.4
internal PrintableStringEncoding()
: base("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 '()+,-./:=?")
{
}
}
internal abstract class RestrictedAsciiStringEncoding : SpanBasedEncoding
{
private readonly bool[] _isAllowed;
protected RestrictedAsciiStringEncoding(byte minCharAllowed, byte maxCharAllowed)
{
Debug.Assert(minCharAllowed <= maxCharAllowed);
Debug.Assert(maxCharAllowed <= 0x7F);
bool[] isAllowed = new bool[0x80];
for (byte charCode = minCharAllowed; charCode <= maxCharAllowed; charCode++)
{
isAllowed[charCode] = true;
}
_isAllowed = isAllowed;
}
protected RestrictedAsciiStringEncoding(IEnumerable<char> allowedChars)
{
bool[] isAllowed = new bool[0x7F];
foreach (char c in allowedChars)
{
if (c >= isAllowed.Length)
{
throw new ArgumentOutOfRangeException(nameof(allowedChars));
}
Debug.Assert(isAllowed[c] == false);
isAllowed[c] = true;
}
_isAllowed = isAllowed;
}
public override int GetMaxByteCount(int charCount)
{
return charCount;
}
public override int GetMaxCharCount(int byteCount)
{
return byteCount;
}
protected override int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, bool write)
{
if (chars.IsEmpty)
{
return 0;
}
for (int i = 0; i < chars.Length; i++)
{
char c = chars[i];
if ((uint)c >= (uint)_isAllowed.Length || !_isAllowed[c])
{
EncoderFallback.CreateFallbackBuffer().Fallback(c, i);
Debug.Fail("Fallback should have thrown");
throw new InvalidOperationException();
}
if (write)
{
bytes[i] = (byte)c;
}
}
return chars.Length;
}
protected override int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars, bool write)
{
if (bytes.IsEmpty)
{
return 0;
}
for (int i = 0; i < bytes.Length; i++)
{
byte b = bytes[i];
if ((uint)b >= (uint)_isAllowed.Length || !_isAllowed[b])
{
DecoderFallback.CreateFallbackBuffer().Fallback(
new[] { b },
i);
Debug.Fail("Fallback should have thrown");
throw new InvalidOperationException();
}
if (write)
{
chars[i] = (char)b;
}
}
return bytes.Length;
}
}
/// <summary>
/// Big-Endian UCS-2 encoding (the same as UTF-16BE, but disallowing surrogate pairs to leave plane 0)
/// </summary>
// T-REC-X.690-201508 sec 8.23.8 says to see ISO/IEC 10646:2003 section 13.1.
// ISO/IEC 10646:2003 sec 13.1 says each character is represented by "two octets".
// ISO/IEC 10646:2003 sec 6.3 says that when serialized as octets to use big endian.
internal sealed class BMPEncoding : SpanBasedEncoding
{
protected override int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, bool write)
{
if (chars.IsEmpty)
{
return 0;
}
int writeIdx = 0;
for (int i = 0; i < chars.Length; i++)
{
char c = chars[i];
if (char.IsSurrogate(c))
{
EncoderFallback.CreateFallbackBuffer().Fallback(c, i);
Debug.Fail("Fallback should have thrown");
throw new InvalidOperationException();
}
ushort val16 = c;
if (write)
{
bytes[writeIdx + 1] = (byte)val16;
bytes[writeIdx] = (byte)(val16 >> 8);
}
writeIdx += 2;
}
return writeIdx;
}
protected override int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars, bool write)
{
if (bytes.IsEmpty)
{
return 0;
}
if (bytes.Length % 2 != 0)
{
DecoderFallback.CreateFallbackBuffer().Fallback(
bytes.Slice(bytes.Length - 1).ToArray(),
bytes.Length - 1);
Debug.Fail("Fallback should have thrown");
throw new InvalidOperationException();
}
int writeIdx = 0;
for (int i = 0; i < bytes.Length; i += 2)
{
int val = bytes[i] << 8 | bytes[i + 1];
char c = (char)val;
if (char.IsSurrogate(c))
{
DecoderFallback.CreateFallbackBuffer().Fallback(
bytes.Slice(i, 2).ToArray(),
i);
Debug.Fail("Fallback should have thrown");
throw new InvalidOperationException();
}
if (write)
{
chars[writeIdx] = c;
}
writeIdx++;
}
return writeIdx;
}
public override int GetMaxByteCount(int charCount)
{
checked
{
return charCount * 2;
}
}
public override int GetMaxCharCount(int byteCount)
{
return byteCount / 2;
}
}
/// <summary>
/// Compatibility encoding for T61Strings. Interprets the characters as UTF-8 or
/// ISO-8859-1 as a fallback.
/// </summary>
internal sealed class T61Encoding : Encoding
{
private static readonly Encoding s_utf8Encoding = new UTF8Encoding(false, throwOnInvalidBytes: true);
private static readonly Encoding s_latin1Encoding = GetEncoding("iso-8859-1");
public override int GetByteCount(char[] chars, int index, int count)
{
return s_utf8Encoding.GetByteCount(chars, index, count);
}
public override unsafe int GetByteCount(char* chars, int count)
{
return s_utf8Encoding.GetByteCount(chars, count);
}
public override int GetByteCount(string s)
{
return s_utf8Encoding.GetByteCount(s);
}
#if NETCOREAPP || NETSTANDARD2_1
public override int GetByteCount(ReadOnlySpan<char> chars)
{
return s_utf8Encoding.GetByteCount(chars);
}
#endif
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
return s_utf8Encoding.GetBytes(chars, charIndex, charCount, bytes, byteIndex);
}
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
return s_utf8Encoding.GetBytes(chars, charCount, bytes, byteCount);
}
public override int GetCharCount(byte[] bytes, int index, int count)
{
try
{
return s_utf8Encoding.GetCharCount(bytes, index, count);
}
catch (DecoderFallbackException)
{
return s_latin1Encoding.GetCharCount(bytes, index, count);
}
}
public override unsafe int GetCharCount(byte* bytes, int count)
{
try
{
return s_utf8Encoding.GetCharCount(bytes, count);
}
catch (DecoderFallbackException)
{
return s_latin1Encoding.GetCharCount(bytes, count);
}
}
#if NETCOREAPP || NETSTANDARD2_1
public override int GetCharCount(ReadOnlySpan<byte> bytes)
{
try
{
return s_utf8Encoding.GetCharCount(bytes);
}
catch (DecoderFallbackException)
{
return s_latin1Encoding.GetCharCount(bytes);
}
}
#endif
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
try
{
return s_utf8Encoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
}
catch (DecoderFallbackException)
{
return s_latin1Encoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
}
}
public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
try
{
return s_utf8Encoding.GetChars(bytes, byteCount, chars, charCount);
}
catch (DecoderFallbackException)
{
return s_latin1Encoding.GetChars(bytes, byteCount, chars, charCount);
}
}
public override int GetMaxByteCount(int charCount)
{
return s_utf8Encoding.GetMaxByteCount(charCount);
}
public override int GetMaxCharCount(int byteCount)
{
// Latin-1 is single byte encoding, so byteCount == charCount
// UTF-8 is multi-byte encoding, so byteCount >= charCount
// We want to return the maximum of those two, which happens to be byteCount.
return byteCount;
}
}
}
| // 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.Runtime.InteropServices;
using System.Text;
namespace System.Formats.Asn1
{
internal static class AsnCharacterStringEncodings
{
private static readonly Encoding s_utf8Encoding =
new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
private static readonly Encoding s_bmpEncoding = new BMPEncoding();
private static readonly Encoding s_ia5Encoding = new IA5Encoding();
private static readonly Encoding s_visibleStringEncoding = new VisibleStringEncoding();
private static readonly Encoding s_numericStringEncoding = new NumericStringEncoding();
private static readonly Encoding s_printableStringEncoding = new PrintableStringEncoding();
private static readonly Encoding s_t61Encoding = new T61Encoding();
internal static Encoding GetEncoding(UniversalTagNumber encodingType) =>
encodingType switch
{
UniversalTagNumber.UTF8String => s_utf8Encoding,
UniversalTagNumber.NumericString => s_numericStringEncoding,
UniversalTagNumber.PrintableString => s_printableStringEncoding,
UniversalTagNumber.IA5String => s_ia5Encoding,
UniversalTagNumber.VisibleString => s_visibleStringEncoding,
UniversalTagNumber.BMPString => s_bmpEncoding,
UniversalTagNumber.T61String => s_t61Encoding,
_ => throw new ArgumentOutOfRangeException(nameof(encodingType), encodingType, null),
};
internal static int GetByteCount(this Encoding encoding, ReadOnlySpan<char> str)
{
if (str.IsEmpty)
{
// Ensure a non-null pointer is obtained, even though the expected answer is 0.
str = string.Empty.AsSpan();
}
unsafe
{
fixed (char* strPtr = &MemoryMarshal.GetReference(str))
{
return encoding.GetByteCount(strPtr, str.Length);
}
}
}
internal static int GetBytes(this Encoding encoding, ReadOnlySpan<char> chars, Span<byte> bytes)
{
if (chars.IsEmpty)
{
// Ensure a non-null pointer is obtained.
chars = string.Empty.AsSpan();
}
if (bytes.IsEmpty)
{
// Ensure a non-null pointer is obtained.
bytes = Array.Empty<byte>();
}
unsafe
{
fixed (char* charsPtr = &MemoryMarshal.GetReference(chars))
fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes))
{
return encoding.GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length);
}
}
}
}
internal abstract class SpanBasedEncoding : Encoding
{
protected SpanBasedEncoding()
: base(0, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback)
{
}
protected abstract int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, bool write);
protected abstract int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars, bool write);
public override int GetByteCount(char[] chars, int index, int count)
{
return GetByteCount(new ReadOnlySpan<char>(chars, index, count));
}
public override unsafe int GetByteCount(char* chars, int count)
{
return GetByteCount(new ReadOnlySpan<char>(chars, count));
}
public override int GetByteCount(string s)
{
return GetByteCount(s.AsSpan());
}
public
#if NETCOREAPP || NETSTANDARD2_1
override
#endif
int GetByteCount(ReadOnlySpan<char> chars)
{
return GetBytes(chars, Span<byte>.Empty, write: false);
}
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
return GetBytes(
new ReadOnlySpan<char>(chars, charIndex, charCount),
new Span<byte>(bytes, byteIndex, bytes.Length - byteIndex),
write: true);
}
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
return GetBytes(
new ReadOnlySpan<char>(chars, charCount),
new Span<byte>(bytes, byteCount),
write: true);
}
public override int GetCharCount(byte[] bytes, int index, int count)
{
return GetCharCount(new ReadOnlySpan<byte>(bytes, index, count));
}
public override unsafe int GetCharCount(byte* bytes, int count)
{
return GetCharCount(new ReadOnlySpan<byte>(bytes, count));
}
public
#if NETCOREAPP || NETSTANDARD2_1
override
#endif
int GetCharCount(ReadOnlySpan<byte> bytes)
{
return GetChars(bytes, Span<char>.Empty, write: false);
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
return GetChars(
new ReadOnlySpan<byte>(bytes, byteIndex, byteCount),
new Span<char>(chars, charIndex, chars.Length - charIndex),
write: true);
}
public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
return GetChars(
new ReadOnlySpan<byte>(bytes, byteCount),
new Span<char>(chars, charCount),
write: true);
}
}
internal sealed class IA5Encoding : RestrictedAsciiStringEncoding
{
// T-REC-X.680-201508 sec 41, Table 8.
// ISO International Register of Coded Character Sets to be used with Escape Sequences 001
// is ASCII 0x00 - 0x1F
// ISO International Register of Coded Character Sets to be used with Escape Sequences 006
// is ASCII 0x21 - 0x7E
// Space is ASCII 0x20, delete is ASCII 0x7F.
//
// The net result is all of 7-bit ASCII
internal IA5Encoding()
: base(0x00, 0x7F)
{
}
}
internal sealed class VisibleStringEncoding : RestrictedAsciiStringEncoding
{
// T-REC-X.680-201508 sec 41, Table 8.
// ISO International Register of Coded Character Sets to be used with Escape Sequences 006
// is ASCII 0x21 - 0x7E
// Space is ASCII 0x20.
internal VisibleStringEncoding()
: base(0x20, 0x7E)
{
}
}
internal sealed class NumericStringEncoding : RestrictedAsciiStringEncoding
{
// T-REC-X.680-201508 sec 41.2 (Table 9)
// 0, 1, ... 9 + space
internal NumericStringEncoding()
: base("0123456789 ")
{
}
}
internal sealed class PrintableStringEncoding : RestrictedAsciiStringEncoding
{
// T-REC-X.680-201508 sec 41.4
internal PrintableStringEncoding()
: base("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 '()+,-./:=?")
{
}
}
internal abstract class RestrictedAsciiStringEncoding : SpanBasedEncoding
{
private readonly bool[] _isAllowed;
protected RestrictedAsciiStringEncoding(byte minCharAllowed, byte maxCharAllowed)
{
Debug.Assert(minCharAllowed <= maxCharAllowed);
Debug.Assert(maxCharAllowed <= 0x7F);
bool[] isAllowed = new bool[0x80];
for (byte charCode = minCharAllowed; charCode <= maxCharAllowed; charCode++)
{
isAllowed[charCode] = true;
}
_isAllowed = isAllowed;
}
protected RestrictedAsciiStringEncoding(IEnumerable<char> allowedChars)
{
bool[] isAllowed = new bool[0x7F];
foreach (char c in allowedChars)
{
if (c >= isAllowed.Length)
{
throw new ArgumentOutOfRangeException(nameof(allowedChars));
}
Debug.Assert(isAllowed[c] == false);
isAllowed[c] = true;
}
_isAllowed = isAllowed;
}
public override int GetMaxByteCount(int charCount)
{
return charCount;
}
public override int GetMaxCharCount(int byteCount)
{
return byteCount;
}
protected override int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, bool write)
{
if (chars.IsEmpty)
{
return 0;
}
for (int i = 0; i < chars.Length; i++)
{
char c = chars[i];
if ((uint)c >= (uint)_isAllowed.Length || !_isAllowed[c])
{
EncoderFallback.CreateFallbackBuffer().Fallback(c, i);
Debug.Fail("Fallback should have thrown");
throw new InvalidOperationException();
}
if (write)
{
bytes[i] = (byte)c;
}
}
return chars.Length;
}
protected override int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars, bool write)
{
if (bytes.IsEmpty)
{
return 0;
}
for (int i = 0; i < bytes.Length; i++)
{
byte b = bytes[i];
if ((uint)b >= (uint)_isAllowed.Length || !_isAllowed[b])
{
DecoderFallback.CreateFallbackBuffer().Fallback(
new[] { b },
i);
Debug.Fail("Fallback should have thrown");
throw new InvalidOperationException();
}
if (write)
{
chars[i] = (char)b;
}
}
return bytes.Length;
}
}
/// <summary>
/// Big-Endian UCS-2 encoding (the same as UTF-16BE, but disallowing surrogate pairs to leave plane 0)
/// </summary>
// T-REC-X.690-201508 sec 8.23.8 says to see ISO/IEC 10646:2003 section 13.1.
// ISO/IEC 10646:2003 sec 13.1 says each character is represented by "two octets".
// ISO/IEC 10646:2003 sec 6.3 says that when serialized as octets to use big endian.
internal sealed class BMPEncoding : SpanBasedEncoding
{
protected override int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, bool write)
{
if (chars.IsEmpty)
{
return 0;
}
int writeIdx = 0;
for (int i = 0; i < chars.Length; i++)
{
char c = chars[i];
if (char.IsSurrogate(c))
{
EncoderFallback.CreateFallbackBuffer().Fallback(c, i);
Debug.Fail("Fallback should have thrown");
throw new InvalidOperationException();
}
ushort val16 = c;
if (write)
{
bytes[writeIdx + 1] = (byte)val16;
bytes[writeIdx] = (byte)(val16 >> 8);
}
writeIdx += 2;
}
return writeIdx;
}
protected override int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars, bool write)
{
if (bytes.IsEmpty)
{
return 0;
}
if (bytes.Length % 2 != 0)
{
DecoderFallback.CreateFallbackBuffer().Fallback(
bytes.Slice(bytes.Length - 1).ToArray(),
bytes.Length - 1);
Debug.Fail("Fallback should have thrown");
throw new InvalidOperationException();
}
int writeIdx = 0;
for (int i = 0; i < bytes.Length; i += 2)
{
int val = bytes[i] << 8 | bytes[i + 1];
char c = (char)val;
if (char.IsSurrogate(c))
{
DecoderFallback.CreateFallbackBuffer().Fallback(
bytes.Slice(i, 2).ToArray(),
i);
Debug.Fail("Fallback should have thrown");
throw new InvalidOperationException();
}
if (write)
{
chars[writeIdx] = c;
}
writeIdx++;
}
return writeIdx;
}
public override int GetMaxByteCount(int charCount)
{
checked
{
return charCount * 2;
}
}
public override int GetMaxCharCount(int byteCount)
{
return byteCount / 2;
}
}
/// <summary>
/// Compatibility encoding for T61Strings. Interprets the characters as UTF-8 or
/// ISO-8859-1 as a fallback.
/// </summary>
internal sealed class T61Encoding : Encoding
{
private static readonly Encoding s_utf8Encoding = new UTF8Encoding(false, throwOnInvalidBytes: true);
private static readonly Encoding s_latin1Encoding = GetEncoding("iso-8859-1");
public override int GetByteCount(char[] chars, int index, int count)
{
return s_utf8Encoding.GetByteCount(chars, index, count);
}
public override unsafe int GetByteCount(char* chars, int count)
{
return s_utf8Encoding.GetByteCount(chars, count);
}
public override int GetByteCount(string s)
{
return s_utf8Encoding.GetByteCount(s);
}
#if NETCOREAPP || NETSTANDARD2_1
public override int GetByteCount(ReadOnlySpan<char> chars)
{
return s_utf8Encoding.GetByteCount(chars);
}
#endif
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
return s_utf8Encoding.GetBytes(chars, charIndex, charCount, bytes, byteIndex);
}
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
return s_utf8Encoding.GetBytes(chars, charCount, bytes, byteCount);
}
public override int GetCharCount(byte[] bytes, int index, int count)
{
try
{
return s_utf8Encoding.GetCharCount(bytes, index, count);
}
catch (DecoderFallbackException)
{
return s_latin1Encoding.GetCharCount(bytes, index, count);
}
}
public override unsafe int GetCharCount(byte* bytes, int count)
{
try
{
return s_utf8Encoding.GetCharCount(bytes, count);
}
catch (DecoderFallbackException)
{
return s_latin1Encoding.GetCharCount(bytes, count);
}
}
#if NETCOREAPP || NETSTANDARD2_1
public override int GetCharCount(ReadOnlySpan<byte> bytes)
{
try
{
return s_utf8Encoding.GetCharCount(bytes);
}
catch (DecoderFallbackException)
{
return s_latin1Encoding.GetCharCount(bytes);
}
}
#endif
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
try
{
return s_utf8Encoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
}
catch (DecoderFallbackException)
{
return s_latin1Encoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
}
}
public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
try
{
return s_utf8Encoding.GetChars(bytes, byteCount, chars, charCount);
}
catch (DecoderFallbackException)
{
return s_latin1Encoding.GetChars(bytes, byteCount, chars, charCount);
}
}
public override int GetMaxByteCount(int charCount)
{
return s_utf8Encoding.GetMaxByteCount(charCount);
}
public override int GetMaxCharCount(int byteCount)
{
// Latin-1 is single byte encoding, so byteCount == charCount
// UTF-8 is multi-byte encoding, so byteCount >= charCount
// We want to return the maximum of those two, which happens to be byteCount.
return byteCount;
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/mono/mono/tests/unhandled-exception-4.cs | using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
class CustomException : Exception
{
}
class Driver
{
/* expected exit code: 255 */
static void Main (string[] args)
{
if (Environment.GetEnvironmentVariable ("TEST_UNHANDLED_EXCEPTION_HANDLER") != null)
AppDomain.CurrentDomain.UnhandledException += (s, e) => {};
ManualResetEvent mre = new ManualResetEvent (false);
var t = Task.Factory.StartNew (new Action (() => { try { throw new CustomException (); } finally { mre.Set (); } }));
if (!mre.WaitOne (5000))
Environment.Exit (2);
try {
t.Wait ();
Environment.Exit (5);
} catch (AggregateException ae) {
Console.WriteLine (ae);
if (ae.InnerExceptions [0] is CustomException) {
/* expected behaviour */
Environment.Exit (255);
}
} catch (Exception ex) {
Console.WriteLine (ex);
Environment.Exit (3);
}
Environment.Exit (6);
}
}
| using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
class CustomException : Exception
{
}
class Driver
{
/* expected exit code: 255 */
static void Main (string[] args)
{
if (Environment.GetEnvironmentVariable ("TEST_UNHANDLED_EXCEPTION_HANDLER") != null)
AppDomain.CurrentDomain.UnhandledException += (s, e) => {};
ManualResetEvent mre = new ManualResetEvent (false);
var t = Task.Factory.StartNew (new Action (() => { try { throw new CustomException (); } finally { mre.Set (); } }));
if (!mre.WaitOne (5000))
Environment.Exit (2);
try {
t.Wait ();
Environment.Exit (5);
} catch (AggregateException ae) {
Console.WriteLine (ae);
if (ae.InnerExceptions [0] is CustomException) {
/* expected behaviour */
Environment.Exit (255);
}
} catch (Exception ex) {
Console.WriteLine (ex);
Environment.Exit (3);
}
Environment.Exit (6);
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Runtime/tests/System/Text/ASCIIUtilityTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Numerics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Xunit;
namespace System.Text.Tests
{
// Since many of the methods we'll be testing are internal, we'll need to invoke
// them via reflection.
public static unsafe class AsciiUtilityTests
{
private const int SizeOfVector128 = 128 / 8;
// The delegate definitions and members below provide us access to CoreLib's internals.
// We use UIntPtr instead of nuint everywhere here since we don't know what our target arch is.
private delegate UIntPtr FnGetIndexOfFirstNonAsciiByte(byte* pBuffer, UIntPtr bufferLength);
private static readonly UnsafeLazyDelegate<FnGetIndexOfFirstNonAsciiByte> _fnGetIndexOfFirstNonAsciiByte = new UnsafeLazyDelegate<FnGetIndexOfFirstNonAsciiByte>("GetIndexOfFirstNonAsciiByte");
private delegate UIntPtr FnGetIndexOfFirstNonAsciiChar(char* pBuffer, UIntPtr bufferLength);
private static readonly UnsafeLazyDelegate<FnGetIndexOfFirstNonAsciiChar> _fnGetIndexOfFirstNonAsciiChar = new UnsafeLazyDelegate<FnGetIndexOfFirstNonAsciiChar>("GetIndexOfFirstNonAsciiChar");
private delegate UIntPtr FnNarrowUtf16ToAscii(char* pUtf16Buffer, byte* pAsciiBuffer, UIntPtr elementCount);
private static readonly UnsafeLazyDelegate<FnNarrowUtf16ToAscii> _fnNarrowUtf16ToAscii = new UnsafeLazyDelegate<FnNarrowUtf16ToAscii>("NarrowUtf16ToAscii");
private delegate UIntPtr FnWidenAsciiToUtf16(byte* pAsciiBuffer, char* pUtf16Buffer, UIntPtr elementCount);
private static readonly UnsafeLazyDelegate<FnWidenAsciiToUtf16> _fnWidenAsciiToUtf16 = new UnsafeLazyDelegate<FnWidenAsciiToUtf16>("WidenAsciiToUtf16");
[Fact]
public static void GetIndexOfFirstNonAsciiByte_EmptyInput_NullReference()
{
Assert.Equal(UIntPtr.Zero, _fnGetIndexOfFirstNonAsciiByte.Delegate(null, UIntPtr.Zero));
}
[Fact]
public static void GetIndexOfFirstNonAsciiByte_EmptyInput_NonNullReference()
{
byte b = default;
Assert.Equal(UIntPtr.Zero, _fnGetIndexOfFirstNonAsciiByte.Delegate(&b, UIntPtr.Zero));
}
[Fact]
public static void GetIndexOfFirstNonAsciiByte_Vector128InnerLoop()
{
// The purpose of this test is to make sure we're identifying the correct
// vector (of the two that we're reading simultaneously) when performing
// the final ASCII drain at the end of the method once we've broken out
// of the inner loop.
using (BoundedMemory<byte> mem = BoundedMemory.Allocate<byte>(1024))
{
Span<byte> bytes = mem.Span;
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] &= 0x7F; // make sure each byte (of the pre-populated random data) is ASCII
}
// Two vectors have offsets 0 .. 31. We'll go backward to avoid having to
// re-clear the vector every time.
for (int i = 2 * SizeOfVector128 - 1; i >= 0; i--)
{
bytes[100 + i * 13] = 0x80; // 13 is relatively prime to 32, so it ensures all possible positions are hit
Assert.Equal(100 + i * 13, CallGetIndexOfFirstNonAsciiByte(bytes));
}
}
}
[Fact]
public static void GetIndexOfFirstNonAsciiByte_Boundaries()
{
// The purpose of this test is to make sure we're hitting all of the vectorized
// and draining logic correctly both in the SSE2 and in the non-SSE2 enlightened
// code paths. We shouldn't be reading beyond the boundaries we were given.
// The 5 * Vector test should make sure that we're exercising all possible
// code paths across both implementations.
using (BoundedMemory<byte> mem = BoundedMemory.Allocate<byte>(5 * Vector<byte>.Count))
{
Span<byte> bytes = mem.Span;
// First, try it with all-ASCII buffers.
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] &= 0x7F; // make sure each byte (of the pre-populated random data) is ASCII
}
for (int i = bytes.Length; i >= 0; i--)
{
Assert.Equal(i, CallGetIndexOfFirstNonAsciiByte(bytes.Slice(0, i)));
}
// Then, try it with non-ASCII bytes.
for (int i = bytes.Length; i >= 1; i--)
{
bytes[i - 1] = 0x80; // set non-ASCII
Assert.Equal(i - 1, CallGetIndexOfFirstNonAsciiByte(bytes.Slice(0, i)));
}
}
}
[Fact]
public static void GetIndexOfFirstNonAsciiChar_EmptyInput_NullReference()
{
Assert.Equal(UIntPtr.Zero, _fnGetIndexOfFirstNonAsciiChar.Delegate(null, UIntPtr.Zero));
}
[Fact]
public static void GetIndexOfFirstNonAsciiChar_EmptyInput_NonNullReference()
{
char c = default;
Assert.Equal(UIntPtr.Zero, _fnGetIndexOfFirstNonAsciiChar.Delegate(&c, UIntPtr.Zero));
}
[Fact]
public static void GetIndexOfFirstNonAsciiChar_Vector128InnerLoop()
{
// The purpose of this test is to make sure we're identifying the correct
// vector (of the two that we're reading simultaneously) when performing
// the final ASCII drain at the end of the method once we've broken out
// of the inner loop.
//
// Use U+0123 instead of U+0080 for this test because if our implementation
// uses pminuw / pmovmskb incorrectly, U+0123 will incorrectly show up as ASCII,
// causing our test to produce a false negative.
using (BoundedMemory<char> mem = BoundedMemory.Allocate<char>(1024))
{
Span<char> chars = mem.Span;
for (int i = 0; i < chars.Length; i++)
{
chars[i] &= '\u007F'; // make sure each char (of the pre-populated random data) is ASCII
}
// Two vectors have offsets 0 .. 31. We'll go backward to avoid having to
// re-clear the vector every time.
for (int i = 2 * SizeOfVector128 - 1; i >= 0; i--)
{
chars[100 + i * 13] = '\u0123'; // 13 is relatively prime to 32, so it ensures all possible positions are hit
Assert.Equal(100 + i * 13, CallGetIndexOfFirstNonAsciiChar(chars));
}
}
}
[Fact]
public static void GetIndexOfFirstNonAsciiChar_Boundaries()
{
// The purpose of this test is to make sure we're hitting all of the vectorized
// and draining logic correctly both in the SSE2 and in the non-SSE2 enlightened
// code paths. We shouldn't be reading beyond the boundaries we were given.
//
// The 5 * Vector test should make sure that we're exercising all possible
// code paths across both implementations. The sizeof(char) is because we're
// specifying element count, but underlying implementation reintepret casts to bytes.
//
// Use U+0123 instead of U+0080 for this test because if our implementation
// uses pminuw / pmovmskb incorrectly, U+0123 will incorrectly show up as ASCII,
// causing our test to produce a false negative.
using (BoundedMemory<char> mem = BoundedMemory.Allocate<char>(5 * Vector<byte>.Count / sizeof(char)))
{
Span<char> chars = mem.Span;
for (int i = 0; i < chars.Length; i++)
{
chars[i] &= '\u007F'; // make sure each char (of the pre-populated random data) is ASCII
}
for (int i = chars.Length; i >= 0; i--)
{
Assert.Equal(i, CallGetIndexOfFirstNonAsciiChar(chars.Slice(0, i)));
}
// Then, try it with non-ASCII bytes.
for (int i = chars.Length; i >= 1; i--)
{
chars[i - 1] = '\u0123'; // set non-ASCII
Assert.Equal(i - 1, CallGetIndexOfFirstNonAsciiChar(chars.Slice(0, i)));
}
}
}
[Fact]
public static void WidenAsciiToUtf16_EmptyInput_NullReferences()
{
Assert.Equal(UIntPtr.Zero, _fnWidenAsciiToUtf16.Delegate(null, null, UIntPtr.Zero));
}
[Fact]
public static void WidenAsciiToUtf16_EmptyInput_NonNullReference()
{
byte b = default;
char c = default;
Assert.Equal(UIntPtr.Zero, _fnWidenAsciiToUtf16.Delegate(&b, &c, UIntPtr.Zero));
}
[Fact]
public static void WidenAsciiToUtf16_AllAsciiInput()
{
using BoundedMemory<byte> asciiMem = BoundedMemory.Allocate<byte>(128);
using BoundedMemory<char> utf16Mem = BoundedMemory.Allocate<char>(128);
// Fill source with 00 .. 7F, then trap future writes.
Span<byte> asciiSpan = asciiMem.Span;
for (int i = 0; i < asciiSpan.Length; i++)
{
asciiSpan[i] = (byte)i;
}
asciiMem.MakeReadonly();
// We'll write to the UTF-16 span.
// We test with a variety of span lengths to test alignment and fallthrough code paths.
Span<char> utf16Span = utf16Mem.Span;
for (int i = 0; i < asciiSpan.Length; i++)
{
utf16Span.Clear(); // remove any data from previous iteration
// First, validate that the workhorse saw the incoming data as all-ASCII.
Assert.Equal(128 - i, CallWidenAsciiToUtf16(asciiSpan.Slice(i), utf16Span.Slice(i)));
// Then, validate that the data was transcoded properly.
for (int j = i; j < 128; j++)
{
Assert.Equal((ushort)asciiSpan[i], (ushort)utf16Span[i]);
}
}
}
[Fact]
public static void WidenAsciiToUtf16_SomeNonAsciiInput()
{
using BoundedMemory<byte> asciiMem = BoundedMemory.Allocate<byte>(128);
using BoundedMemory<char> utf16Mem = BoundedMemory.Allocate<char>(128);
// Fill source with 00 .. 7F, then trap future writes.
Span<byte> asciiSpan = asciiMem.Span;
for (int i = 0; i < asciiSpan.Length; i++)
{
asciiSpan[i] = (byte)i;
}
// We'll write to the UTF-16 span.
Span<char> utf16Span = utf16Mem.Span;
for (int i = asciiSpan.Length - 1; i >= 0; i--)
{
RandomNumberGenerator.Fill(MemoryMarshal.Cast<char, byte>(utf16Span)); // fill with garbage
// First, keep track of the garbage we wrote to the destination.
// We want to ensure it wasn't overwritten.
char[] expectedTrailingData = utf16Span.Slice(i).ToArray();
// Then, set the desired byte as non-ASCII, then check that the workhorse
// correctly saw the data as non-ASCII.
asciiSpan[i] |= (byte)0x80;
Assert.Equal(i, CallWidenAsciiToUtf16(asciiSpan, utf16Span));
// Next, validate that the ASCII data was transcoded properly.
for (int j = 0; j < i; j++)
{
Assert.Equal((ushort)asciiSpan[j], (ushort)utf16Span[j]);
}
// Finally, validate that the trailing data wasn't overwritten with non-ASCII data.
Assert.Equal(expectedTrailingData, utf16Span.Slice(i).ToArray());
}
}
[Fact]
public static unsafe void NarrowUtf16ToAscii_EmptyInput_NullReferences()
{
Assert.Equal(UIntPtr.Zero, _fnNarrowUtf16ToAscii.Delegate(null, null, UIntPtr.Zero));
}
[Fact]
public static void NarrowUtf16ToAscii_EmptyInput_NonNullReference()
{
char c = default;
byte b = default;
Assert.Equal(UIntPtr.Zero, _fnNarrowUtf16ToAscii.Delegate(&c, &b, UIntPtr.Zero));
}
[Fact]
public static void NarrowUtf16ToAscii_AllAsciiInput()
{
using BoundedMemory<char> utf16Mem = BoundedMemory.Allocate<char>(128);
using BoundedMemory<byte> asciiMem = BoundedMemory.Allocate<byte>(128);
// Fill source with 00 .. 7F.
Span<char> utf16Span = utf16Mem.Span;
for (int i = 0; i < utf16Span.Length; i++)
{
utf16Span[i] = (char)i;
}
utf16Mem.MakeReadonly();
// We'll write to the ASCII span.
// We test with a variety of span lengths to test alignment and fallthrough code paths.
Span<byte> asciiSpan = asciiMem.Span;
for (int i = 0; i < utf16Span.Length; i++)
{
asciiSpan.Clear(); // remove any data from previous iteration
// First, validate that the workhorse saw the incoming data as all-ASCII.
Assert.Equal(128 - i, CallNarrowUtf16ToAscii(utf16Span.Slice(i), asciiSpan.Slice(i)));
// Then, validate that the data was transcoded properly.
for (int j = i; j < 128; j++)
{
Assert.Equal((ushort)utf16Span[i], (ushort)asciiSpan[i]);
}
}
}
[Fact]
public static void NarrowUtf16ToAscii_SomeNonAsciiInput()
{
using BoundedMemory<char> utf16Mem = BoundedMemory.Allocate<char>(128);
using BoundedMemory<byte> asciiMem = BoundedMemory.Allocate<byte>(128);
// Fill source with 00 .. 7F.
Span<char> utf16Span = utf16Mem.Span;
for (int i = 0; i < utf16Span.Length; i++)
{
utf16Span[i] = (char)i;
}
// We'll write to the ASCII span.
Span<byte> asciiSpan = asciiMem.Span;
for (int i = utf16Span.Length - 1; i >= 0; i--)
{
RandomNumberGenerator.Fill(asciiSpan); // fill with garbage
// First, keep track of the garbage we wrote to the destination.
// We want to ensure it wasn't overwritten.
byte[] expectedTrailingData = asciiSpan.Slice(i).ToArray();
// Then, set the desired byte as non-ASCII, then check that the workhorse
// correctly saw the data as non-ASCII.
utf16Span[i] = '\u0123'; // use U+0123 instead of U+0080 since it catches inappropriate pmovmskb usage
Assert.Equal(i, CallNarrowUtf16ToAscii(utf16Span, asciiSpan));
// Next, validate that the ASCII data was transcoded properly.
for (int j = 0; j < i; j++)
{
Assert.Equal((ushort)utf16Span[j], (ushort)asciiSpan[j]);
}
// Finally, validate that the trailing data wasn't overwritten with non-ASCII data.
Assert.Equal(expectedTrailingData, asciiSpan.Slice(i).ToArray());
}
}
private static int CallGetIndexOfFirstNonAsciiByte(ReadOnlySpan<byte> buffer)
{
fixed (byte* pBuffer = &MemoryMarshal.GetReference(buffer))
{
// Conversions between UIntPtr <-> int are not checked by default.
return checked((int)_fnGetIndexOfFirstNonAsciiByte.Delegate(pBuffer, (UIntPtr)buffer.Length));
}
}
private static int CallGetIndexOfFirstNonAsciiChar(ReadOnlySpan<char> buffer)
{
fixed (char* pBuffer = &MemoryMarshal.GetReference(buffer))
{
// Conversions between UIntPtr <-> int are not checked by default.
return checked((int)_fnGetIndexOfFirstNonAsciiChar.Delegate(pBuffer, (UIntPtr)buffer.Length));
}
}
private static int CallNarrowUtf16ToAscii(ReadOnlySpan<char> utf16, Span<byte> ascii)
{
Assert.Equal(utf16.Length, ascii.Length);
fixed (char* pUtf16 = &MemoryMarshal.GetReference(utf16))
fixed (byte* pAscii = &MemoryMarshal.GetReference(ascii))
{
// Conversions between UIntPtr <-> int are not checked by default.
return checked((int)_fnNarrowUtf16ToAscii.Delegate(pUtf16, pAscii, (UIntPtr)utf16.Length));
}
}
private static int CallWidenAsciiToUtf16(ReadOnlySpan<byte> ascii, Span<char> utf16)
{
Assert.Equal(ascii.Length, utf16.Length);
fixed (byte* pAscii = &MemoryMarshal.GetReference(ascii))
fixed (char* pUtf16 = &MemoryMarshal.GetReference(utf16))
{
// Conversions between UIntPtr <-> int are not checked by default.
return checked((int)_fnWidenAsciiToUtf16.Delegate(pAscii, pUtf16, (UIntPtr)ascii.Length));
}
}
private static Type GetAsciiUtilityType()
{
return typeof(object).Assembly.GetType("System.Text.ASCIIUtility");
}
private sealed class UnsafeLazyDelegate<TDelegate> where TDelegate : Delegate
{
private readonly Lazy<TDelegate> _lazyDelegate;
public UnsafeLazyDelegate(string methodName)
{
_lazyDelegate = new Lazy<TDelegate>(() =>
{
Assert.True(typeof(TDelegate).IsSubclassOf(typeof(MulticastDelegate)));
// Get the MethodInfo for the target method
MethodInfo methodInfo = GetAsciiUtilityType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
Assert.NotNull(methodInfo);
// Construct the TDelegate pointing to this method
return methodInfo.CreateDelegate<TDelegate>();
});
}
public TDelegate Delegate => _lazyDelegate.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.Buffers;
using System.Numerics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Xunit;
namespace System.Text.Tests
{
// Since many of the methods we'll be testing are internal, we'll need to invoke
// them via reflection.
public static unsafe class AsciiUtilityTests
{
private const int SizeOfVector128 = 128 / 8;
// The delegate definitions and members below provide us access to CoreLib's internals.
// We use UIntPtr instead of nuint everywhere here since we don't know what our target arch is.
private delegate UIntPtr FnGetIndexOfFirstNonAsciiByte(byte* pBuffer, UIntPtr bufferLength);
private static readonly UnsafeLazyDelegate<FnGetIndexOfFirstNonAsciiByte> _fnGetIndexOfFirstNonAsciiByte = new UnsafeLazyDelegate<FnGetIndexOfFirstNonAsciiByte>("GetIndexOfFirstNonAsciiByte");
private delegate UIntPtr FnGetIndexOfFirstNonAsciiChar(char* pBuffer, UIntPtr bufferLength);
private static readonly UnsafeLazyDelegate<FnGetIndexOfFirstNonAsciiChar> _fnGetIndexOfFirstNonAsciiChar = new UnsafeLazyDelegate<FnGetIndexOfFirstNonAsciiChar>("GetIndexOfFirstNonAsciiChar");
private delegate UIntPtr FnNarrowUtf16ToAscii(char* pUtf16Buffer, byte* pAsciiBuffer, UIntPtr elementCount);
private static readonly UnsafeLazyDelegate<FnNarrowUtf16ToAscii> _fnNarrowUtf16ToAscii = new UnsafeLazyDelegate<FnNarrowUtf16ToAscii>("NarrowUtf16ToAscii");
private delegate UIntPtr FnWidenAsciiToUtf16(byte* pAsciiBuffer, char* pUtf16Buffer, UIntPtr elementCount);
private static readonly UnsafeLazyDelegate<FnWidenAsciiToUtf16> _fnWidenAsciiToUtf16 = new UnsafeLazyDelegate<FnWidenAsciiToUtf16>("WidenAsciiToUtf16");
[Fact]
public static void GetIndexOfFirstNonAsciiByte_EmptyInput_NullReference()
{
Assert.Equal(UIntPtr.Zero, _fnGetIndexOfFirstNonAsciiByte.Delegate(null, UIntPtr.Zero));
}
[Fact]
public static void GetIndexOfFirstNonAsciiByte_EmptyInput_NonNullReference()
{
byte b = default;
Assert.Equal(UIntPtr.Zero, _fnGetIndexOfFirstNonAsciiByte.Delegate(&b, UIntPtr.Zero));
}
[Fact]
public static void GetIndexOfFirstNonAsciiByte_Vector128InnerLoop()
{
// The purpose of this test is to make sure we're identifying the correct
// vector (of the two that we're reading simultaneously) when performing
// the final ASCII drain at the end of the method once we've broken out
// of the inner loop.
using (BoundedMemory<byte> mem = BoundedMemory.Allocate<byte>(1024))
{
Span<byte> bytes = mem.Span;
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] &= 0x7F; // make sure each byte (of the pre-populated random data) is ASCII
}
// Two vectors have offsets 0 .. 31. We'll go backward to avoid having to
// re-clear the vector every time.
for (int i = 2 * SizeOfVector128 - 1; i >= 0; i--)
{
bytes[100 + i * 13] = 0x80; // 13 is relatively prime to 32, so it ensures all possible positions are hit
Assert.Equal(100 + i * 13, CallGetIndexOfFirstNonAsciiByte(bytes));
}
}
}
[Fact]
public static void GetIndexOfFirstNonAsciiByte_Boundaries()
{
// The purpose of this test is to make sure we're hitting all of the vectorized
// and draining logic correctly both in the SSE2 and in the non-SSE2 enlightened
// code paths. We shouldn't be reading beyond the boundaries we were given.
// The 5 * Vector test should make sure that we're exercising all possible
// code paths across both implementations.
using (BoundedMemory<byte> mem = BoundedMemory.Allocate<byte>(5 * Vector<byte>.Count))
{
Span<byte> bytes = mem.Span;
// First, try it with all-ASCII buffers.
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] &= 0x7F; // make sure each byte (of the pre-populated random data) is ASCII
}
for (int i = bytes.Length; i >= 0; i--)
{
Assert.Equal(i, CallGetIndexOfFirstNonAsciiByte(bytes.Slice(0, i)));
}
// Then, try it with non-ASCII bytes.
for (int i = bytes.Length; i >= 1; i--)
{
bytes[i - 1] = 0x80; // set non-ASCII
Assert.Equal(i - 1, CallGetIndexOfFirstNonAsciiByte(bytes.Slice(0, i)));
}
}
}
[Fact]
public static void GetIndexOfFirstNonAsciiChar_EmptyInput_NullReference()
{
Assert.Equal(UIntPtr.Zero, _fnGetIndexOfFirstNonAsciiChar.Delegate(null, UIntPtr.Zero));
}
[Fact]
public static void GetIndexOfFirstNonAsciiChar_EmptyInput_NonNullReference()
{
char c = default;
Assert.Equal(UIntPtr.Zero, _fnGetIndexOfFirstNonAsciiChar.Delegate(&c, UIntPtr.Zero));
}
[Fact]
public static void GetIndexOfFirstNonAsciiChar_Vector128InnerLoop()
{
// The purpose of this test is to make sure we're identifying the correct
// vector (of the two that we're reading simultaneously) when performing
// the final ASCII drain at the end of the method once we've broken out
// of the inner loop.
//
// Use U+0123 instead of U+0080 for this test because if our implementation
// uses pminuw / pmovmskb incorrectly, U+0123 will incorrectly show up as ASCII,
// causing our test to produce a false negative.
using (BoundedMemory<char> mem = BoundedMemory.Allocate<char>(1024))
{
Span<char> chars = mem.Span;
for (int i = 0; i < chars.Length; i++)
{
chars[i] &= '\u007F'; // make sure each char (of the pre-populated random data) is ASCII
}
// Two vectors have offsets 0 .. 31. We'll go backward to avoid having to
// re-clear the vector every time.
for (int i = 2 * SizeOfVector128 - 1; i >= 0; i--)
{
chars[100 + i * 13] = '\u0123'; // 13 is relatively prime to 32, so it ensures all possible positions are hit
Assert.Equal(100 + i * 13, CallGetIndexOfFirstNonAsciiChar(chars));
}
}
}
[Fact]
public static void GetIndexOfFirstNonAsciiChar_Boundaries()
{
// The purpose of this test is to make sure we're hitting all of the vectorized
// and draining logic correctly both in the SSE2 and in the non-SSE2 enlightened
// code paths. We shouldn't be reading beyond the boundaries we were given.
//
// The 5 * Vector test should make sure that we're exercising all possible
// code paths across both implementations. The sizeof(char) is because we're
// specifying element count, but underlying implementation reintepret casts to bytes.
//
// Use U+0123 instead of U+0080 for this test because if our implementation
// uses pminuw / pmovmskb incorrectly, U+0123 will incorrectly show up as ASCII,
// causing our test to produce a false negative.
using (BoundedMemory<char> mem = BoundedMemory.Allocate<char>(5 * Vector<byte>.Count / sizeof(char)))
{
Span<char> chars = mem.Span;
for (int i = 0; i < chars.Length; i++)
{
chars[i] &= '\u007F'; // make sure each char (of the pre-populated random data) is ASCII
}
for (int i = chars.Length; i >= 0; i--)
{
Assert.Equal(i, CallGetIndexOfFirstNonAsciiChar(chars.Slice(0, i)));
}
// Then, try it with non-ASCII bytes.
for (int i = chars.Length; i >= 1; i--)
{
chars[i - 1] = '\u0123'; // set non-ASCII
Assert.Equal(i - 1, CallGetIndexOfFirstNonAsciiChar(chars.Slice(0, i)));
}
}
}
[Fact]
public static void WidenAsciiToUtf16_EmptyInput_NullReferences()
{
Assert.Equal(UIntPtr.Zero, _fnWidenAsciiToUtf16.Delegate(null, null, UIntPtr.Zero));
}
[Fact]
public static void WidenAsciiToUtf16_EmptyInput_NonNullReference()
{
byte b = default;
char c = default;
Assert.Equal(UIntPtr.Zero, _fnWidenAsciiToUtf16.Delegate(&b, &c, UIntPtr.Zero));
}
[Fact]
public static void WidenAsciiToUtf16_AllAsciiInput()
{
using BoundedMemory<byte> asciiMem = BoundedMemory.Allocate<byte>(128);
using BoundedMemory<char> utf16Mem = BoundedMemory.Allocate<char>(128);
// Fill source with 00 .. 7F, then trap future writes.
Span<byte> asciiSpan = asciiMem.Span;
for (int i = 0; i < asciiSpan.Length; i++)
{
asciiSpan[i] = (byte)i;
}
asciiMem.MakeReadonly();
// We'll write to the UTF-16 span.
// We test with a variety of span lengths to test alignment and fallthrough code paths.
Span<char> utf16Span = utf16Mem.Span;
for (int i = 0; i < asciiSpan.Length; i++)
{
utf16Span.Clear(); // remove any data from previous iteration
// First, validate that the workhorse saw the incoming data as all-ASCII.
Assert.Equal(128 - i, CallWidenAsciiToUtf16(asciiSpan.Slice(i), utf16Span.Slice(i)));
// Then, validate that the data was transcoded properly.
for (int j = i; j < 128; j++)
{
Assert.Equal((ushort)asciiSpan[i], (ushort)utf16Span[i]);
}
}
}
[Fact]
public static void WidenAsciiToUtf16_SomeNonAsciiInput()
{
using BoundedMemory<byte> asciiMem = BoundedMemory.Allocate<byte>(128);
using BoundedMemory<char> utf16Mem = BoundedMemory.Allocate<char>(128);
// Fill source with 00 .. 7F, then trap future writes.
Span<byte> asciiSpan = asciiMem.Span;
for (int i = 0; i < asciiSpan.Length; i++)
{
asciiSpan[i] = (byte)i;
}
// We'll write to the UTF-16 span.
Span<char> utf16Span = utf16Mem.Span;
for (int i = asciiSpan.Length - 1; i >= 0; i--)
{
RandomNumberGenerator.Fill(MemoryMarshal.Cast<char, byte>(utf16Span)); // fill with garbage
// First, keep track of the garbage we wrote to the destination.
// We want to ensure it wasn't overwritten.
char[] expectedTrailingData = utf16Span.Slice(i).ToArray();
// Then, set the desired byte as non-ASCII, then check that the workhorse
// correctly saw the data as non-ASCII.
asciiSpan[i] |= (byte)0x80;
Assert.Equal(i, CallWidenAsciiToUtf16(asciiSpan, utf16Span));
// Next, validate that the ASCII data was transcoded properly.
for (int j = 0; j < i; j++)
{
Assert.Equal((ushort)asciiSpan[j], (ushort)utf16Span[j]);
}
// Finally, validate that the trailing data wasn't overwritten with non-ASCII data.
Assert.Equal(expectedTrailingData, utf16Span.Slice(i).ToArray());
}
}
[Fact]
public static unsafe void NarrowUtf16ToAscii_EmptyInput_NullReferences()
{
Assert.Equal(UIntPtr.Zero, _fnNarrowUtf16ToAscii.Delegate(null, null, UIntPtr.Zero));
}
[Fact]
public static void NarrowUtf16ToAscii_EmptyInput_NonNullReference()
{
char c = default;
byte b = default;
Assert.Equal(UIntPtr.Zero, _fnNarrowUtf16ToAscii.Delegate(&c, &b, UIntPtr.Zero));
}
[Fact]
public static void NarrowUtf16ToAscii_AllAsciiInput()
{
using BoundedMemory<char> utf16Mem = BoundedMemory.Allocate<char>(128);
using BoundedMemory<byte> asciiMem = BoundedMemory.Allocate<byte>(128);
// Fill source with 00 .. 7F.
Span<char> utf16Span = utf16Mem.Span;
for (int i = 0; i < utf16Span.Length; i++)
{
utf16Span[i] = (char)i;
}
utf16Mem.MakeReadonly();
// We'll write to the ASCII span.
// We test with a variety of span lengths to test alignment and fallthrough code paths.
Span<byte> asciiSpan = asciiMem.Span;
for (int i = 0; i < utf16Span.Length; i++)
{
asciiSpan.Clear(); // remove any data from previous iteration
// First, validate that the workhorse saw the incoming data as all-ASCII.
Assert.Equal(128 - i, CallNarrowUtf16ToAscii(utf16Span.Slice(i), asciiSpan.Slice(i)));
// Then, validate that the data was transcoded properly.
for (int j = i; j < 128; j++)
{
Assert.Equal((ushort)utf16Span[i], (ushort)asciiSpan[i]);
}
}
}
[Fact]
public static void NarrowUtf16ToAscii_SomeNonAsciiInput()
{
using BoundedMemory<char> utf16Mem = BoundedMemory.Allocate<char>(128);
using BoundedMemory<byte> asciiMem = BoundedMemory.Allocate<byte>(128);
// Fill source with 00 .. 7F.
Span<char> utf16Span = utf16Mem.Span;
for (int i = 0; i < utf16Span.Length; i++)
{
utf16Span[i] = (char)i;
}
// We'll write to the ASCII span.
Span<byte> asciiSpan = asciiMem.Span;
for (int i = utf16Span.Length - 1; i >= 0; i--)
{
RandomNumberGenerator.Fill(asciiSpan); // fill with garbage
// First, keep track of the garbage we wrote to the destination.
// We want to ensure it wasn't overwritten.
byte[] expectedTrailingData = asciiSpan.Slice(i).ToArray();
// Then, set the desired byte as non-ASCII, then check that the workhorse
// correctly saw the data as non-ASCII.
utf16Span[i] = '\u0123'; // use U+0123 instead of U+0080 since it catches inappropriate pmovmskb usage
Assert.Equal(i, CallNarrowUtf16ToAscii(utf16Span, asciiSpan));
// Next, validate that the ASCII data was transcoded properly.
for (int j = 0; j < i; j++)
{
Assert.Equal((ushort)utf16Span[j], (ushort)asciiSpan[j]);
}
// Finally, validate that the trailing data wasn't overwritten with non-ASCII data.
Assert.Equal(expectedTrailingData, asciiSpan.Slice(i).ToArray());
}
}
private static int CallGetIndexOfFirstNonAsciiByte(ReadOnlySpan<byte> buffer)
{
fixed (byte* pBuffer = &MemoryMarshal.GetReference(buffer))
{
// Conversions between UIntPtr <-> int are not checked by default.
return checked((int)_fnGetIndexOfFirstNonAsciiByte.Delegate(pBuffer, (UIntPtr)buffer.Length));
}
}
private static int CallGetIndexOfFirstNonAsciiChar(ReadOnlySpan<char> buffer)
{
fixed (char* pBuffer = &MemoryMarshal.GetReference(buffer))
{
// Conversions between UIntPtr <-> int are not checked by default.
return checked((int)_fnGetIndexOfFirstNonAsciiChar.Delegate(pBuffer, (UIntPtr)buffer.Length));
}
}
private static int CallNarrowUtf16ToAscii(ReadOnlySpan<char> utf16, Span<byte> ascii)
{
Assert.Equal(utf16.Length, ascii.Length);
fixed (char* pUtf16 = &MemoryMarshal.GetReference(utf16))
fixed (byte* pAscii = &MemoryMarshal.GetReference(ascii))
{
// Conversions between UIntPtr <-> int are not checked by default.
return checked((int)_fnNarrowUtf16ToAscii.Delegate(pUtf16, pAscii, (UIntPtr)utf16.Length));
}
}
private static int CallWidenAsciiToUtf16(ReadOnlySpan<byte> ascii, Span<char> utf16)
{
Assert.Equal(ascii.Length, utf16.Length);
fixed (byte* pAscii = &MemoryMarshal.GetReference(ascii))
fixed (char* pUtf16 = &MemoryMarshal.GetReference(utf16))
{
// Conversions between UIntPtr <-> int are not checked by default.
return checked((int)_fnWidenAsciiToUtf16.Delegate(pAscii, pUtf16, (UIntPtr)ascii.Length));
}
}
private static Type GetAsciiUtilityType()
{
return typeof(object).Assembly.GetType("System.Text.ASCIIUtility");
}
private sealed class UnsafeLazyDelegate<TDelegate> where TDelegate : Delegate
{
private readonly Lazy<TDelegate> _lazyDelegate;
public UnsafeLazyDelegate(string methodName)
{
_lazyDelegate = new Lazy<TDelegate>(() =>
{
Assert.True(typeof(TDelegate).IsSubclassOf(typeof(MulticastDelegate)));
// Get the MethodInfo for the target method
MethodInfo methodInfo = GetAsciiUtilityType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
Assert.NotNull(methodInfo);
// Construct the TDelegate pointing to this method
return methodInfo.CreateDelegate<TDelegate>();
});
}
public TDelegate Delegate => _lazyDelegate.Value;
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Reflection/tests/PropertyInfoTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Reflection.Tests
{
public class PropertyInfoTests
{
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.IntProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.StringProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.DoubleProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.FloatProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.EnumProperty))]
public void GetConstantValue_NotConstant_ThrowsInvalidOperationException(Type type, string name)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Throws<InvalidOperationException>(() => propertyInfo.GetConstantValue());
Assert.Throws<InvalidOperationException>(() => propertyInfo.GetRawConstantValue());
}
[Theory]
[InlineData(typeof(GetSetClass), nameof(GetSetClass.ReadWriteProperty), true, true)]
[InlineData(typeof(GetSetClass), nameof(GetSetClass.ReadOnlyProperty), true, false)]
[InlineData(typeof(GetSetClass), nameof(GetSetClass.WriteOnlyProperty), false, true)]
[InlineData(typeof(GetSetClass), "Item", true, true)]
[InlineData(typeof(GetSetStruct), nameof(GetSetStruct.ReadWriteProperty), true, true)]
[InlineData(typeof(GetSetStruct), nameof(GetSetStruct.ReadOnlyProperty), true, false)]
[InlineData(typeof(GetSetStruct), nameof(GetSetStruct.WriteOnlyProperty), false, true)]
[InlineData(typeof(GetSetStruct), "Item", true, false)]
[InlineData(typeof(GetSetInterface), nameof(GetSetInterface.ReadWriteProperty), true, true)]
[InlineData(typeof(GetSetInterface), nameof(GetSetInterface.ReadOnlyProperty), true, false)]
[InlineData(typeof(GetSetInterface), nameof(GetSetInterface.WriteOnlyProperty), false, true)]
[InlineData(typeof(GetSetInterface), "Item", false, true)]
public void GetMethod_SetMethod(Type type, string name, bool hasGetter, bool hasSetter)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(hasGetter, propertyInfo.GetMethod != null);
Assert.Equal(hasSetter, propertyInfo.SetMethod != null);
}
public static IEnumerable<object[]> GetValue_TestData()
{
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ReadWriteProperty2), new BaseClass(), null, -1.0 };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ReadWriteProperty3), typeof(BaseClass), null, -2 };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.Name), new BaseClass(), null, "hello" };
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", new CustomIndexerNameClass(), new object[] { 1, "2" }, null };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), new BaseClass(), null, 100 };
}
[Theory]
[MemberData(nameof(GetValue_TestData))]
public void GetValue(Type type, string name, object obj, object[] index, object expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
if (index == null)
{
Assert.Equal(expected, propertyInfo.GetValue(obj));
}
Assert.Equal(expected, propertyInfo.GetValue(obj, index));
}
public static IEnumerable<object[]> GetValue_Invalid_TestData()
{
// Incorrect indexer parameters
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", new CustomIndexerNameClass(), new object[] { 1, "2", 3 }, typeof(TargetParameterCountException) };
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", new CustomIndexerNameClass(), null, typeof(TargetParameterCountException) };
// Incorrect type
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", new CustomIndexerNameClass(), new object[] { "1", "2" }, typeof(ArgumentException) };
// Readonly
yield return new object[] { typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), new BaseClass(), null, typeof(ArgumentException) };
// Null target
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", null, new object[] { "1", "2" }, typeof(TargetException) };
}
[Theory]
[ActiveIssue("https://github.com/mono/mono/issues/15027", TestRuntimes.Mono)]
[MemberData(nameof(GetValue_Invalid_TestData))]
public void GetValue_Invalid(Type type, string name, object obj, object[] index, Type exceptionType)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Throws(exceptionType, () => propertyInfo.GetValue(obj, index));
}
public static IEnumerable<object[]> SetValue_TestData()
{
yield return new object[] { typeof(BaseClass), nameof(BaseClass.StaticObjectArrayProperty), typeof(BaseClass), new string[] { "hello" }, null, new string[] { "hello" } };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ObjectArrayProperty), new BaseClass(), new string[] { "hello" }, null, new string[] { "hello" } };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.Name), new BaseClass(), "hello", null, "hello" };
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), "hello", new object[] { 99, 2, new string[] { "hello" }, "f" }, "992f1" };
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), "pw", new object[] { 99, 2, new string[] { "hello" }, "SOME string" }, "992SOME string1" };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ShortEnumProperty), new BaseClass(), (byte)1, null, (BaseClass.ShortEnum)1 };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.IntEnumProperty), new BaseClass(), (short)2, null, (BaseClass.IntEnum)2 };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.LongEnumProperty), new BaseClass(), (int)3, null, (BaseClass.LongEnum)3 };
}
[Theory]
[MemberData(nameof(SetValue_TestData))]
public void SetValue(Type type, string name, object obj, object value, object[] index, object expected)
{
PropertyInfo PropertyInfo = GetProperty(type, name);
object originalValue;
if (index == null)
{
// Use SetValue(object, object)
originalValue = PropertyInfo.GetValue(obj);
try
{
PropertyInfo.SetValue(obj, value);
Assert.Equal(expected, PropertyInfo.GetValue(obj));
}
finally
{
PropertyInfo.SetValue(obj, originalValue);
}
}
// Use SetValue(object, object, object[])
originalValue = PropertyInfo.GetValue(obj, index);
try
{
PropertyInfo.SetValue(obj, value, index);
Assert.Equal(expected, PropertyInfo.GetValue(obj, index));
}
finally
{
PropertyInfo.SetValue(obj, originalValue, index);
}
}
public static IEnumerable<object[]> SetValue_Invalid_TestData()
{
// Incorrect number of parameters
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), "value", new object[] { 99, 2, new string[] { "a" } }, typeof(TargetParameterCountException) };
// Obj is null
yield return new object[] { typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), null, null, null, typeof(TargetException) };
yield return new object[] { typeof(AdvancedIndexerClass), "Item", null, "value", new object[] { 99, 2, new string[] { "a" }, "b" }, typeof(TargetException) };
// Readonly
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), new BaseClass(), 100, null, typeof(ArgumentException) };
// Wrong value type
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), "value", new object[] { 99, 2, "invalid", "string" }, typeof(ArgumentException) };
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), 100, new object[] { 99, 2, new string[] { "a" }, "b" }, typeof(ArgumentException) };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), new BaseClass(), "string", null, typeof(ArgumentException) };
}
[Theory]
[MemberData(nameof(SetValue_Invalid_TestData))]
public void SetValue_Invalid(Type type, string name, object obj, object value, object[] index, Type exceptionType)
{
PropertyInfo PropertyInfo = GetProperty(type, name);
Assert.Throws(exceptionType, () => PropertyInfo.SetValue(obj, value, index));
}
[Theory]
[InlineData(nameof(PropertyInfoMembers.PublicGetIntProperty))]
[InlineData(nameof(PropertyInfoMembers.PublicGetPublicSetStringProperty))]
[InlineData(nameof(PropertyInfoMembers.PublicGetDoubleProperty))]
[InlineData(nameof(PropertyInfoMembers.PublicGetFloatProperty))]
[InlineData(nameof(PropertyInfoMembers.PublicGetEnumProperty))]
[InlineData("PrivateGetPrivateSetIntProperty")]
[InlineData(nameof(PropertyInfoMembers.PublicGetPrivateSetProperty))]
public static void GetRequiredCustomModifiers_GetOptionalCustomModifiers(string name)
{
PropertyInfo property = typeof(PropertyInfoMembers).GetTypeInfo().GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
Assert.Empty(property.GetRequiredCustomModifiers());
Assert.Empty(property.GetOptionalCustomModifiers());
}
[Theory]
[InlineData(nameof(PropertyInfoMembers.PublicGetIntProperty), 1, 1)]
[InlineData(nameof(PropertyInfoMembers.PublicGetPublicSetStringProperty), 2, 2)]
[InlineData(nameof(PropertyInfoMembers.PublicGetDoubleProperty), 1, 1)]
[InlineData(nameof(PropertyInfoMembers.PublicGetFloatProperty), 1, 1)]
[InlineData(nameof(PropertyInfoMembers.PublicGetEnumProperty), 2, 2)]
[InlineData("PrivateGetPrivateSetIntProperty", 0, 2)]
[InlineData(nameof(PropertyInfoMembers.PublicGetPrivateSetProperty), 1, 2)]
public static void GetAccessors(string name, int accessorPublicCount, int accessorPublicAndNonPublicCount)
{
PropertyInfo pi = typeof(PropertyInfoMembers).GetTypeInfo().GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
Assert.Equal(accessorPublicCount, pi.GetAccessors().Length);
Assert.Equal(accessorPublicCount, pi.GetAccessors(false).Length);
Assert.Equal(accessorPublicAndNonPublicCount, pi.GetAccessors(true).Length);
}
[Theory]
[InlineData(nameof(PropertyInfoMembers.PublicGetIntProperty), true, true, false, false)]
[InlineData(nameof(PropertyInfoMembers.PublicGetPublicSetStringProperty), true, true, true, true)]
[InlineData(nameof(PropertyInfoMembers.PublicGetDoubleProperty), true, true, false, false)]
[InlineData(nameof(PropertyInfoMembers.PublicGetFloatProperty), true, true, false, false)]
[InlineData(nameof(PropertyInfoMembers.PublicGetEnumProperty), true, true, true, true)]
[InlineData("PrivateGetPrivateSetIntProperty", false, true, false, true)]
[InlineData(nameof(PropertyInfoMembers.PublicGetPrivateSetProperty), true, true, false, true)]
public static void GetGetMethod_GetSetMethod(string name, bool publicGet, bool nonPublicGet, bool publicSet, bool nonPublicSet)
{
PropertyInfo pi = typeof(PropertyInfoMembers).GetTypeInfo().GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (publicGet)
{
Assert.Equal("get_" + name, pi.GetGetMethod().Name);
Assert.Equal("get_" + name, pi.GetGetMethod(true).Name);
Assert.Equal("get_" + name, pi.GetGetMethod(false).Name);
}
else
{
Assert.Null(pi.GetGetMethod());
}
if (nonPublicGet)
{
Assert.Equal("get_" + name, pi.GetGetMethod(true).Name);
}
else
{
Assert.Null(pi.GetGetMethod());
Assert.Null(pi.GetGetMethod(false));
}
if (publicSet)
{
Assert.Equal("set_" + name, pi.GetSetMethod().Name);
Assert.Equal("set_" + name, pi.GetSetMethod(true).Name);
Assert.Equal("set_" + name, pi.GetSetMethod(false).Name);
}
else
{
Assert.Null(pi.GetSetMethod());
}
if (nonPublicSet)
{
Assert.Equal("set_" + name, pi.GetSetMethod(true).Name);
}
else
{
Assert.Null(pi.GetSetMethod());
Assert.Null(pi.GetSetMethod(false));
}
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), true)]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), typeof(BaseClass), nameof(BaseClass.ReadWriteProperty2), false)]
public void EqualsTest(Type type1, string name1, Type type2, string name2, bool expected)
{
PropertyInfo propertyInfo1 = GetProperty(type1, name1);
PropertyInfo propertyInfo2 = GetProperty(type2, name2);
Assert.Equal(expected, propertyInfo1.Equals(propertyInfo2));
Assert.Equal(expected, propertyInfo1 == propertyInfo2);
Assert.Equal(!expected, propertyInfo1 != propertyInfo2);
}
[Fact]
public void GetHashCodeTest()
{
PropertyInfo propertyInfo = GetProperty(typeof(BaseClass), "ReadWriteProperty1");
Assert.NotEqual(0, propertyInfo.GetHashCode());
}
[Theory]
[InlineData(typeof(BaseClass), "Item", new string[] { "Index" })]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), new string[0])]
public void GetIndexParameters(Type type, string name, string[] expectedNames)
{
PropertyInfo propertyInfo = GetProperty(type, name);
ParameterInfo[] indexParameters = propertyInfo.GetIndexParameters();
Assert.Equal(expectedNames, indexParameters.Select(p => p.Name));
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), true)]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), true)]
[InlineData(typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), false)]
public void CanRead(Type type, string name, bool expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.CanRead);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), true)]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), false)]
[InlineData(typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), true)]
public void CanWrite(Type type, string name, bool expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.CanWrite);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1))]
[InlineData(typeof(SubClass), nameof(SubClass.NewProperty))]
public void DeclaringType(Type type, string name)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(type, propertyInfo.DeclaringType);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), typeof(short))]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty2), typeof(double))]
[InlineData(typeof(SubClass), nameof(SubClass.NewProperty), typeof(int))]
public void PropertyType(Type type, string name, Type expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.PropertyType);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1))]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty))]
public void Name(Type type, string name)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(name, propertyInfo.Name);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), false)]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), false)]
[InlineData(typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), false)]
public void IsSpecialName(Type type, string name, bool expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.IsSpecialName);
}
[Theory]
[InlineData(typeof(SubClass), nameof(SubClass.Description), PropertyAttributes.None)]
[InlineData(typeof(SubClass), nameof(SubClass.NewProperty), PropertyAttributes.None)]
public void Attributes(Type type, string name, PropertyAttributes expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.Attributes);
}
public static PropertyInfo GetProperty(Type type, string name)
{
return type.GetTypeInfo().DeclaredProperties.First(propertyInfo => propertyInfo.Name.Equals(name));
}
public interface InterfaceWithPropertyDeclaration
{
string Name { get; set; }
}
public class BaseClass : InterfaceWithPropertyDeclaration
{
public static object[] _staticObjectArrayProperty = new object[1];
public static object[] StaticObjectArrayProperty
{
get { return _staticObjectArrayProperty; }
set { _staticObjectArrayProperty = value; }
}
public enum ShortEnum : short {}
public enum IntEnum {}
public enum LongEnum : long {}
public ShortEnum ShortEnumProperty { get; set; }
public IntEnum IntEnumProperty { get; set; }
public LongEnum LongEnumProperty { get; set; }
public object[] _objectArray;
public object[] ObjectArrayProperty
{
get { return _objectArray; }
set { _objectArray = value; }
}
public short _readWriteProperty1 = -2;
public short ReadWriteProperty1
{
get { return _readWriteProperty1; }
set { _readWriteProperty1 = value; }
}
public double _readWriteProperty2 = -1;
public double ReadWriteProperty2
{
get { return _readWriteProperty2; }
set { _readWriteProperty2 = value; }
}
public static int _readWriteProperty3 = -2;
public static int ReadWriteProperty3
{
get { return _readWriteProperty3; }
set { _readWriteProperty3 = value; }
}
public int _readOnlyProperty = 100;
public int ReadOnlyProperty
{
get { return _readOnlyProperty; }
}
public long _writeOnlyProperty = 1;
public int WriteOnlyProperty
{
set { _writeOnlyProperty = value; }
}
// Indexer properties
public string[] _stringArray = { "abc", "def", "ghi", "jkl" };
public string this[int Index]
{
get { return _stringArray[Index]; }
set { _stringArray[Index] = value; }
}
// Interface property
private string _name = "hello";
public string Name
{
get { return _name; }
set { _name = value; }
}
// Const fields
private const int IntField = 100;
private const string StringField = "hello";
private const double DoubleField = 22.314;
private const float FloatField = 99.99F;
private const PublicEnum EnumField = PublicEnum.Case1;
public int IntProperty { get { return IntField; } }
public string StringProperty { get { return StringField; } }
public double DoubleProperty { get { return DoubleField; } }
public float FloatProperty { get { return FloatField; } }
public PublicEnum EnumProperty { get { return EnumField; } }
}
public class SubClass : BaseClass
{
private int _newProperty = 100;
private string _description;
public int NewProperty
{
get { return _newProperty; }
set { _newProperty = value; }
}
public string Description
{
get { return _description; }
set { _description = value; }
}
}
public class CustomIndexerNameClass
{
private object[] _objectArray;
[IndexerName("BasicIndexer")] // Property name will be BasicIndexer instead of Item
public object[] this[int index, string s]
{
get { return _objectArray; }
set { _objectArray = value; }
}
}
public class AdvancedIndexerClass
{
public string _setValue = null;
public string this[int index, int index2, string[] h, string myStr]
{
get
{
string strHashLength = "null";
if (h != null)
{
strHashLength = h.Length.ToString();
}
return index.ToString() + index2.ToString() + myStr + strHashLength;
}
set
{
string strHashLength = "null";
if (h != null)
{
strHashLength = h.Length.ToString();
}
_setValue = _setValue = index.ToString() + index2.ToString() + myStr + strHashLength + value;
}
}
}
public class GetSetClass
{
public int ReadWriteProperty { get { return 1; } set { } }
public string ReadOnlyProperty { get { return "Test"; } }
public char WriteOnlyProperty { set { } }
public int this[int index] { get { return 2; } set { } }
}
public struct GetSetStruct
{
public int ReadWriteProperty { get { return 1; } set { } }
public string ReadOnlyProperty { get { return "Test"; } }
public char WriteOnlyProperty { set { } }
public string this[int index] { get { return "name"; } }
}
public interface GetSetInterface
{
int ReadWriteProperty { get; set; }
string ReadOnlyProperty { get; }
char WriteOnlyProperty { set; }
char this[int index] { set; }
}
public class PropertyInfoMembers
{
public int PublicGetIntProperty { get; }
public string PublicGetPublicSetStringProperty { get; set; }
public double PublicGetDoubleProperty { get; }
public float PublicGetFloatProperty { get; }
public PublicEnum PublicGetEnumProperty { get; set; }
private int PrivateGetPrivateSetIntProperty { get; set; }
public int PublicGetPrivateSetProperty { get; private 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.Linq;
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Reflection.Tests
{
public class PropertyInfoTests
{
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.IntProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.StringProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.DoubleProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.FloatProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.EnumProperty))]
public void GetConstantValue_NotConstant_ThrowsInvalidOperationException(Type type, string name)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Throws<InvalidOperationException>(() => propertyInfo.GetConstantValue());
Assert.Throws<InvalidOperationException>(() => propertyInfo.GetRawConstantValue());
}
[Theory]
[InlineData(typeof(GetSetClass), nameof(GetSetClass.ReadWriteProperty), true, true)]
[InlineData(typeof(GetSetClass), nameof(GetSetClass.ReadOnlyProperty), true, false)]
[InlineData(typeof(GetSetClass), nameof(GetSetClass.WriteOnlyProperty), false, true)]
[InlineData(typeof(GetSetClass), "Item", true, true)]
[InlineData(typeof(GetSetStruct), nameof(GetSetStruct.ReadWriteProperty), true, true)]
[InlineData(typeof(GetSetStruct), nameof(GetSetStruct.ReadOnlyProperty), true, false)]
[InlineData(typeof(GetSetStruct), nameof(GetSetStruct.WriteOnlyProperty), false, true)]
[InlineData(typeof(GetSetStruct), "Item", true, false)]
[InlineData(typeof(GetSetInterface), nameof(GetSetInterface.ReadWriteProperty), true, true)]
[InlineData(typeof(GetSetInterface), nameof(GetSetInterface.ReadOnlyProperty), true, false)]
[InlineData(typeof(GetSetInterface), nameof(GetSetInterface.WriteOnlyProperty), false, true)]
[InlineData(typeof(GetSetInterface), "Item", false, true)]
public void GetMethod_SetMethod(Type type, string name, bool hasGetter, bool hasSetter)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(hasGetter, propertyInfo.GetMethod != null);
Assert.Equal(hasSetter, propertyInfo.SetMethod != null);
}
public static IEnumerable<object[]> GetValue_TestData()
{
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ReadWriteProperty2), new BaseClass(), null, -1.0 };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ReadWriteProperty3), typeof(BaseClass), null, -2 };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.Name), new BaseClass(), null, "hello" };
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", new CustomIndexerNameClass(), new object[] { 1, "2" }, null };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), new BaseClass(), null, 100 };
}
[Theory]
[MemberData(nameof(GetValue_TestData))]
public void GetValue(Type type, string name, object obj, object[] index, object expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
if (index == null)
{
Assert.Equal(expected, propertyInfo.GetValue(obj));
}
Assert.Equal(expected, propertyInfo.GetValue(obj, index));
}
public static IEnumerable<object[]> GetValue_Invalid_TestData()
{
// Incorrect indexer parameters
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", new CustomIndexerNameClass(), new object[] { 1, "2", 3 }, typeof(TargetParameterCountException) };
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", new CustomIndexerNameClass(), null, typeof(TargetParameterCountException) };
// Incorrect type
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", new CustomIndexerNameClass(), new object[] { "1", "2" }, typeof(ArgumentException) };
// Readonly
yield return new object[] { typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), new BaseClass(), null, typeof(ArgumentException) };
// Null target
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", null, new object[] { "1", "2" }, typeof(TargetException) };
}
[Theory]
[ActiveIssue("https://github.com/mono/mono/issues/15027", TestRuntimes.Mono)]
[MemberData(nameof(GetValue_Invalid_TestData))]
public void GetValue_Invalid(Type type, string name, object obj, object[] index, Type exceptionType)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Throws(exceptionType, () => propertyInfo.GetValue(obj, index));
}
public static IEnumerable<object[]> SetValue_TestData()
{
yield return new object[] { typeof(BaseClass), nameof(BaseClass.StaticObjectArrayProperty), typeof(BaseClass), new string[] { "hello" }, null, new string[] { "hello" } };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ObjectArrayProperty), new BaseClass(), new string[] { "hello" }, null, new string[] { "hello" } };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.Name), new BaseClass(), "hello", null, "hello" };
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), "hello", new object[] { 99, 2, new string[] { "hello" }, "f" }, "992f1" };
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), "pw", new object[] { 99, 2, new string[] { "hello" }, "SOME string" }, "992SOME string1" };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ShortEnumProperty), new BaseClass(), (byte)1, null, (BaseClass.ShortEnum)1 };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.IntEnumProperty), new BaseClass(), (short)2, null, (BaseClass.IntEnum)2 };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.LongEnumProperty), new BaseClass(), (int)3, null, (BaseClass.LongEnum)3 };
}
[Theory]
[MemberData(nameof(SetValue_TestData))]
public void SetValue(Type type, string name, object obj, object value, object[] index, object expected)
{
PropertyInfo PropertyInfo = GetProperty(type, name);
object originalValue;
if (index == null)
{
// Use SetValue(object, object)
originalValue = PropertyInfo.GetValue(obj);
try
{
PropertyInfo.SetValue(obj, value);
Assert.Equal(expected, PropertyInfo.GetValue(obj));
}
finally
{
PropertyInfo.SetValue(obj, originalValue);
}
}
// Use SetValue(object, object, object[])
originalValue = PropertyInfo.GetValue(obj, index);
try
{
PropertyInfo.SetValue(obj, value, index);
Assert.Equal(expected, PropertyInfo.GetValue(obj, index));
}
finally
{
PropertyInfo.SetValue(obj, originalValue, index);
}
}
public static IEnumerable<object[]> SetValue_Invalid_TestData()
{
// Incorrect number of parameters
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), "value", new object[] { 99, 2, new string[] { "a" } }, typeof(TargetParameterCountException) };
// Obj is null
yield return new object[] { typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), null, null, null, typeof(TargetException) };
yield return new object[] { typeof(AdvancedIndexerClass), "Item", null, "value", new object[] { 99, 2, new string[] { "a" }, "b" }, typeof(TargetException) };
// Readonly
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), new BaseClass(), 100, null, typeof(ArgumentException) };
// Wrong value type
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), "value", new object[] { 99, 2, "invalid", "string" }, typeof(ArgumentException) };
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), 100, new object[] { 99, 2, new string[] { "a" }, "b" }, typeof(ArgumentException) };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), new BaseClass(), "string", null, typeof(ArgumentException) };
}
[Theory]
[MemberData(nameof(SetValue_Invalid_TestData))]
public void SetValue_Invalid(Type type, string name, object obj, object value, object[] index, Type exceptionType)
{
PropertyInfo PropertyInfo = GetProperty(type, name);
Assert.Throws(exceptionType, () => PropertyInfo.SetValue(obj, value, index));
}
[Theory]
[InlineData(nameof(PropertyInfoMembers.PublicGetIntProperty))]
[InlineData(nameof(PropertyInfoMembers.PublicGetPublicSetStringProperty))]
[InlineData(nameof(PropertyInfoMembers.PublicGetDoubleProperty))]
[InlineData(nameof(PropertyInfoMembers.PublicGetFloatProperty))]
[InlineData(nameof(PropertyInfoMembers.PublicGetEnumProperty))]
[InlineData("PrivateGetPrivateSetIntProperty")]
[InlineData(nameof(PropertyInfoMembers.PublicGetPrivateSetProperty))]
public static void GetRequiredCustomModifiers_GetOptionalCustomModifiers(string name)
{
PropertyInfo property = typeof(PropertyInfoMembers).GetTypeInfo().GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
Assert.Empty(property.GetRequiredCustomModifiers());
Assert.Empty(property.GetOptionalCustomModifiers());
}
[Theory]
[InlineData(nameof(PropertyInfoMembers.PublicGetIntProperty), 1, 1)]
[InlineData(nameof(PropertyInfoMembers.PublicGetPublicSetStringProperty), 2, 2)]
[InlineData(nameof(PropertyInfoMembers.PublicGetDoubleProperty), 1, 1)]
[InlineData(nameof(PropertyInfoMembers.PublicGetFloatProperty), 1, 1)]
[InlineData(nameof(PropertyInfoMembers.PublicGetEnumProperty), 2, 2)]
[InlineData("PrivateGetPrivateSetIntProperty", 0, 2)]
[InlineData(nameof(PropertyInfoMembers.PublicGetPrivateSetProperty), 1, 2)]
public static void GetAccessors(string name, int accessorPublicCount, int accessorPublicAndNonPublicCount)
{
PropertyInfo pi = typeof(PropertyInfoMembers).GetTypeInfo().GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
Assert.Equal(accessorPublicCount, pi.GetAccessors().Length);
Assert.Equal(accessorPublicCount, pi.GetAccessors(false).Length);
Assert.Equal(accessorPublicAndNonPublicCount, pi.GetAccessors(true).Length);
}
[Theory]
[InlineData(nameof(PropertyInfoMembers.PublicGetIntProperty), true, true, false, false)]
[InlineData(nameof(PropertyInfoMembers.PublicGetPublicSetStringProperty), true, true, true, true)]
[InlineData(nameof(PropertyInfoMembers.PublicGetDoubleProperty), true, true, false, false)]
[InlineData(nameof(PropertyInfoMembers.PublicGetFloatProperty), true, true, false, false)]
[InlineData(nameof(PropertyInfoMembers.PublicGetEnumProperty), true, true, true, true)]
[InlineData("PrivateGetPrivateSetIntProperty", false, true, false, true)]
[InlineData(nameof(PropertyInfoMembers.PublicGetPrivateSetProperty), true, true, false, true)]
public static void GetGetMethod_GetSetMethod(string name, bool publicGet, bool nonPublicGet, bool publicSet, bool nonPublicSet)
{
PropertyInfo pi = typeof(PropertyInfoMembers).GetTypeInfo().GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (publicGet)
{
Assert.Equal("get_" + name, pi.GetGetMethod().Name);
Assert.Equal("get_" + name, pi.GetGetMethod(true).Name);
Assert.Equal("get_" + name, pi.GetGetMethod(false).Name);
}
else
{
Assert.Null(pi.GetGetMethod());
}
if (nonPublicGet)
{
Assert.Equal("get_" + name, pi.GetGetMethod(true).Name);
}
else
{
Assert.Null(pi.GetGetMethod());
Assert.Null(pi.GetGetMethod(false));
}
if (publicSet)
{
Assert.Equal("set_" + name, pi.GetSetMethod().Name);
Assert.Equal("set_" + name, pi.GetSetMethod(true).Name);
Assert.Equal("set_" + name, pi.GetSetMethod(false).Name);
}
else
{
Assert.Null(pi.GetSetMethod());
}
if (nonPublicSet)
{
Assert.Equal("set_" + name, pi.GetSetMethod(true).Name);
}
else
{
Assert.Null(pi.GetSetMethod());
Assert.Null(pi.GetSetMethod(false));
}
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), true)]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), typeof(BaseClass), nameof(BaseClass.ReadWriteProperty2), false)]
public void EqualsTest(Type type1, string name1, Type type2, string name2, bool expected)
{
PropertyInfo propertyInfo1 = GetProperty(type1, name1);
PropertyInfo propertyInfo2 = GetProperty(type2, name2);
Assert.Equal(expected, propertyInfo1.Equals(propertyInfo2));
Assert.Equal(expected, propertyInfo1 == propertyInfo2);
Assert.Equal(!expected, propertyInfo1 != propertyInfo2);
}
[Fact]
public void GetHashCodeTest()
{
PropertyInfo propertyInfo = GetProperty(typeof(BaseClass), "ReadWriteProperty1");
Assert.NotEqual(0, propertyInfo.GetHashCode());
}
[Theory]
[InlineData(typeof(BaseClass), "Item", new string[] { "Index" })]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), new string[0])]
public void GetIndexParameters(Type type, string name, string[] expectedNames)
{
PropertyInfo propertyInfo = GetProperty(type, name);
ParameterInfo[] indexParameters = propertyInfo.GetIndexParameters();
Assert.Equal(expectedNames, indexParameters.Select(p => p.Name));
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), true)]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), true)]
[InlineData(typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), false)]
public void CanRead(Type type, string name, bool expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.CanRead);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), true)]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), false)]
[InlineData(typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), true)]
public void CanWrite(Type type, string name, bool expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.CanWrite);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1))]
[InlineData(typeof(SubClass), nameof(SubClass.NewProperty))]
public void DeclaringType(Type type, string name)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(type, propertyInfo.DeclaringType);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), typeof(short))]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty2), typeof(double))]
[InlineData(typeof(SubClass), nameof(SubClass.NewProperty), typeof(int))]
public void PropertyType(Type type, string name, Type expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.PropertyType);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1))]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty))]
public void Name(Type type, string name)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(name, propertyInfo.Name);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), false)]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), false)]
[InlineData(typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), false)]
public void IsSpecialName(Type type, string name, bool expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.IsSpecialName);
}
[Theory]
[InlineData(typeof(SubClass), nameof(SubClass.Description), PropertyAttributes.None)]
[InlineData(typeof(SubClass), nameof(SubClass.NewProperty), PropertyAttributes.None)]
public void Attributes(Type type, string name, PropertyAttributes expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.Attributes);
}
public static PropertyInfo GetProperty(Type type, string name)
{
return type.GetTypeInfo().DeclaredProperties.First(propertyInfo => propertyInfo.Name.Equals(name));
}
public interface InterfaceWithPropertyDeclaration
{
string Name { get; set; }
}
public class BaseClass : InterfaceWithPropertyDeclaration
{
public static object[] _staticObjectArrayProperty = new object[1];
public static object[] StaticObjectArrayProperty
{
get { return _staticObjectArrayProperty; }
set { _staticObjectArrayProperty = value; }
}
public enum ShortEnum : short {}
public enum IntEnum {}
public enum LongEnum : long {}
public ShortEnum ShortEnumProperty { get; set; }
public IntEnum IntEnumProperty { get; set; }
public LongEnum LongEnumProperty { get; set; }
public object[] _objectArray;
public object[] ObjectArrayProperty
{
get { return _objectArray; }
set { _objectArray = value; }
}
public short _readWriteProperty1 = -2;
public short ReadWriteProperty1
{
get { return _readWriteProperty1; }
set { _readWriteProperty1 = value; }
}
public double _readWriteProperty2 = -1;
public double ReadWriteProperty2
{
get { return _readWriteProperty2; }
set { _readWriteProperty2 = value; }
}
public static int _readWriteProperty3 = -2;
public static int ReadWriteProperty3
{
get { return _readWriteProperty3; }
set { _readWriteProperty3 = value; }
}
public int _readOnlyProperty = 100;
public int ReadOnlyProperty
{
get { return _readOnlyProperty; }
}
public long _writeOnlyProperty = 1;
public int WriteOnlyProperty
{
set { _writeOnlyProperty = value; }
}
// Indexer properties
public string[] _stringArray = { "abc", "def", "ghi", "jkl" };
public string this[int Index]
{
get { return _stringArray[Index]; }
set { _stringArray[Index] = value; }
}
// Interface property
private string _name = "hello";
public string Name
{
get { return _name; }
set { _name = value; }
}
// Const fields
private const int IntField = 100;
private const string StringField = "hello";
private const double DoubleField = 22.314;
private const float FloatField = 99.99F;
private const PublicEnum EnumField = PublicEnum.Case1;
public int IntProperty { get { return IntField; } }
public string StringProperty { get { return StringField; } }
public double DoubleProperty { get { return DoubleField; } }
public float FloatProperty { get { return FloatField; } }
public PublicEnum EnumProperty { get { return EnumField; } }
}
public class SubClass : BaseClass
{
private int _newProperty = 100;
private string _description;
public int NewProperty
{
get { return _newProperty; }
set { _newProperty = value; }
}
public string Description
{
get { return _description; }
set { _description = value; }
}
}
public class CustomIndexerNameClass
{
private object[] _objectArray;
[IndexerName("BasicIndexer")] // Property name will be BasicIndexer instead of Item
public object[] this[int index, string s]
{
get { return _objectArray; }
set { _objectArray = value; }
}
}
public class AdvancedIndexerClass
{
public string _setValue = null;
public string this[int index, int index2, string[] h, string myStr]
{
get
{
string strHashLength = "null";
if (h != null)
{
strHashLength = h.Length.ToString();
}
return index.ToString() + index2.ToString() + myStr + strHashLength;
}
set
{
string strHashLength = "null";
if (h != null)
{
strHashLength = h.Length.ToString();
}
_setValue = _setValue = index.ToString() + index2.ToString() + myStr + strHashLength + value;
}
}
}
public class GetSetClass
{
public int ReadWriteProperty { get { return 1; } set { } }
public string ReadOnlyProperty { get { return "Test"; } }
public char WriteOnlyProperty { set { } }
public int this[int index] { get { return 2; } set { } }
}
public struct GetSetStruct
{
public int ReadWriteProperty { get { return 1; } set { } }
public string ReadOnlyProperty { get { return "Test"; } }
public char WriteOnlyProperty { set { } }
public string this[int index] { get { return "name"; } }
}
public interface GetSetInterface
{
int ReadWriteProperty { get; set; }
string ReadOnlyProperty { get; }
char WriteOnlyProperty { set; }
char this[int index] { set; }
}
public class PropertyInfoMembers
{
public int PublicGetIntProperty { get; }
public string PublicGetPublicSetStringProperty { get; set; }
public double PublicGetDoubleProperty { get; }
public float PublicGetFloatProperty { get; }
public PublicEnum PublicGetEnumProperty { get; set; }
private int PrivateGetPrivateSetIntProperty { get; set; }
public int PublicGetPrivateSetProperty { get; private set; }
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/jit64/gc/misc/struct6.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;
struct S
{
public String str;
}
class Test_struct6
{
public static void c(S s1, S s2, S s3, S s4, S s5)
{
Console.WriteLine(s1.str + s2.str + s3.str + s4.str + s5.str);
}
public static int Main()
{
S sM1, sM2, sM3, sM4, sM5;
sM1.str = "test";
sM2.str = "test2";
sM3.str = "test3";
sM4.str = "test4";
sM5.str = "test5";
c(sM1, sM2, sM3, sM4, sM5);
return 100;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
struct S
{
public String str;
}
class Test_struct6
{
public static void c(S s1, S s2, S s3, S s4, S s5)
{
Console.WriteLine(s1.str + s2.str + s3.str + s4.str + s5.str);
}
public static int Main()
{
S sM1, sM2, sM3, sM4, sM5;
sM1.str = "test";
sM2.str = "test2";
sM3.str = "test3";
sM4.str = "test4";
sM5.str = "test5";
c(sM1, sM2, sM3, sM4, sM5);
return 100;
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/AbsoluteDifferenceAdd.Vector64.SByte.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void AbsoluteDifferenceAdd_Vector64_SByte()
{
var test = new SimpleTernaryOpTest__AbsoluteDifferenceAdd_Vector64_SByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__AbsoluteDifferenceAdd_Vector64_SByte
{
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(SByte[] inArray1, SByte[] inArray2, SByte[] inArray3, SByte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>();
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<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<SByte, 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 Vector64<SByte> _fld1;
public Vector64<SByte> _fld2;
public Vector64<SByte> _fld3;
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>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld3), ref Unsafe.As<SByte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__AbsoluteDifferenceAdd_Vector64_SByte testClass)
{
var result = AdvSimd.AbsoluteDifferenceAdd(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__AbsoluteDifferenceAdd_Vector64_SByte testClass)
{
fixed (Vector64<SByte>* pFld1 = &_fld1)
fixed (Vector64<SByte>* pFld2 = &_fld2)
fixed (Vector64<SByte>* pFld3 = &_fld3)
{
var result = AdvSimd.AbsoluteDifferenceAdd(
AdvSimd.LoadVector64((SByte*)(pFld1)),
AdvSimd.LoadVector64((SByte*)(pFld2)),
AdvSimd.LoadVector64((SByte*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, 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 Op3ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static SByte[] _data3 = new SByte[Op3ElementCount];
private static Vector64<SByte> _clsVar1;
private static Vector64<SByte> _clsVar2;
private static Vector64<SByte> _clsVar3;
private Vector64<SByte> _fld1;
private Vector64<SByte> _fld2;
private Vector64<SByte> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__AbsoluteDifferenceAdd_Vector64_SByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar3), ref Unsafe.As<SByte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
}
public SimpleTernaryOpTest__AbsoluteDifferenceAdd_Vector64_SByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld3), ref Unsafe.As<SByte, byte>(ref _data3[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(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, _data2, _data3, 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.AbsoluteDifferenceAdd(
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.AbsoluteDifferenceAdd(
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AbsoluteDifferenceAdd), new Type[] { typeof(Vector64<SByte>), typeof(Vector64<SByte>), typeof(Vector64<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(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.AbsoluteDifferenceAdd), new Type[] { typeof(Vector64<SByte>), typeof(Vector64<SByte>), typeof(Vector64<SByte>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.AbsoluteDifferenceAdd(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<SByte>* pClsVar1 = &_clsVar1)
fixed (Vector64<SByte>* pClsVar2 = &_clsVar2)
fixed (Vector64<SByte>* pClsVar3 = &_clsVar3)
{
var result = AdvSimd.AbsoluteDifferenceAdd(
AdvSimd.LoadVector64((SByte*)(pClsVar1)),
AdvSimd.LoadVector64((SByte*)(pClsVar2)),
AdvSimd.LoadVector64((SByte*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray3Ptr);
var result = AdvSimd.AbsoluteDifferenceAdd(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr));
var op3 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray3Ptr));
var result = AdvSimd.AbsoluteDifferenceAdd(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__AbsoluteDifferenceAdd_Vector64_SByte();
var result = AdvSimd.AbsoluteDifferenceAdd(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__AbsoluteDifferenceAdd_Vector64_SByte();
fixed (Vector64<SByte>* pFld1 = &test._fld1)
fixed (Vector64<SByte>* pFld2 = &test._fld2)
fixed (Vector64<SByte>* pFld3 = &test._fld3)
{
var result = AdvSimd.AbsoluteDifferenceAdd(
AdvSimd.LoadVector64((SByte*)(pFld1)),
AdvSimd.LoadVector64((SByte*)(pFld2)),
AdvSimd.LoadVector64((SByte*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.AbsoluteDifferenceAdd(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<SByte>* pFld1 = &_fld1)
fixed (Vector64<SByte>* pFld2 = &_fld2)
fixed (Vector64<SByte>* pFld3 = &_fld3)
{
var result = AdvSimd.AbsoluteDifferenceAdd(
AdvSimd.LoadVector64((SByte*)(pFld1)),
AdvSimd.LoadVector64((SByte*)(pFld2)),
AdvSimd.LoadVector64((SByte*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.AbsoluteDifferenceAdd(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.AbsoluteDifferenceAdd(
AdvSimd.LoadVector64((SByte*)(&test._fld1)),
AdvSimd.LoadVector64((SByte*)(&test._fld2)),
AdvSimd.LoadVector64((SByte*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<SByte> op1, Vector64<SByte> op2, Vector64<SByte> op3, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] inArray3 = new SByte[Op3ElementCount];
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.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] inArray3 = new SByte[Op3ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (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, inArray3, outArray, method);
}
private void ValidateResult(SByte[] firstOp, SByte[] secondOp, SByte[] thirdOp, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.AbsoluteDifferenceAdd(firstOp[i], secondOp[i], thirdOp[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AbsoluteDifferenceAdd)}<SByte>(Vector64<SByte>, Vector64<SByte>, Vector64<SByte>): {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 AbsoluteDifferenceAdd_Vector64_SByte()
{
var test = new SimpleTernaryOpTest__AbsoluteDifferenceAdd_Vector64_SByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__AbsoluteDifferenceAdd_Vector64_SByte
{
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(SByte[] inArray1, SByte[] inArray2, SByte[] inArray3, SByte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>();
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<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<SByte, 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 Vector64<SByte> _fld1;
public Vector64<SByte> _fld2;
public Vector64<SByte> _fld3;
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>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref testStruct._fld3), ref Unsafe.As<SByte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__AbsoluteDifferenceAdd_Vector64_SByte testClass)
{
var result = AdvSimd.AbsoluteDifferenceAdd(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__AbsoluteDifferenceAdd_Vector64_SByte testClass)
{
fixed (Vector64<SByte>* pFld1 = &_fld1)
fixed (Vector64<SByte>* pFld2 = &_fld2)
fixed (Vector64<SByte>* pFld3 = &_fld3)
{
var result = AdvSimd.AbsoluteDifferenceAdd(
AdvSimd.LoadVector64((SByte*)(pFld1)),
AdvSimd.LoadVector64((SByte*)(pFld2)),
AdvSimd.LoadVector64((SByte*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, 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 Op3ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static SByte[] _data3 = new SByte[Op3ElementCount];
private static Vector64<SByte> _clsVar1;
private static Vector64<SByte> _clsVar2;
private static Vector64<SByte> _clsVar3;
private Vector64<SByte> _fld1;
private Vector64<SByte> _fld2;
private Vector64<SByte> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__AbsoluteDifferenceAdd_Vector64_SByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _clsVar3), ref Unsafe.As<SByte, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
}
public SimpleTernaryOpTest__AbsoluteDifferenceAdd_Vector64_SByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<SByte>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<SByte>, byte>(ref _fld3), ref Unsafe.As<SByte, byte>(ref _data3[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(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, _data2, _data3, 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.AbsoluteDifferenceAdd(
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.AbsoluteDifferenceAdd(
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AbsoluteDifferenceAdd), new Type[] { typeof(Vector64<SByte>), typeof(Vector64<SByte>), typeof(Vector64<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector64<SByte>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(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.AbsoluteDifferenceAdd), new Type[] { typeof(Vector64<SByte>), typeof(Vector64<SByte>), typeof(Vector64<SByte>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector64((SByte*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.AbsoluteDifferenceAdd(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<SByte>* pClsVar1 = &_clsVar1)
fixed (Vector64<SByte>* pClsVar2 = &_clsVar2)
fixed (Vector64<SByte>* pClsVar3 = &_clsVar3)
{
var result = AdvSimd.AbsoluteDifferenceAdd(
AdvSimd.LoadVector64((SByte*)(pClsVar1)),
AdvSimd.LoadVector64((SByte*)(pClsVar2)),
AdvSimd.LoadVector64((SByte*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector64<SByte>>(_dataTable.inArray3Ptr);
var result = AdvSimd.AbsoluteDifferenceAdd(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray2Ptr));
var op3 = AdvSimd.LoadVector64((SByte*)(_dataTable.inArray3Ptr));
var result = AdvSimd.AbsoluteDifferenceAdd(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__AbsoluteDifferenceAdd_Vector64_SByte();
var result = AdvSimd.AbsoluteDifferenceAdd(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__AbsoluteDifferenceAdd_Vector64_SByte();
fixed (Vector64<SByte>* pFld1 = &test._fld1)
fixed (Vector64<SByte>* pFld2 = &test._fld2)
fixed (Vector64<SByte>* pFld3 = &test._fld3)
{
var result = AdvSimd.AbsoluteDifferenceAdd(
AdvSimd.LoadVector64((SByte*)(pFld1)),
AdvSimd.LoadVector64((SByte*)(pFld2)),
AdvSimd.LoadVector64((SByte*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.AbsoluteDifferenceAdd(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<SByte>* pFld1 = &_fld1)
fixed (Vector64<SByte>* pFld2 = &_fld2)
fixed (Vector64<SByte>* pFld3 = &_fld3)
{
var result = AdvSimd.AbsoluteDifferenceAdd(
AdvSimd.LoadVector64((SByte*)(pFld1)),
AdvSimd.LoadVector64((SByte*)(pFld2)),
AdvSimd.LoadVector64((SByte*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.AbsoluteDifferenceAdd(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.AbsoluteDifferenceAdd(
AdvSimd.LoadVector64((SByte*)(&test._fld1)),
AdvSimd.LoadVector64((SByte*)(&test._fld2)),
AdvSimd.LoadVector64((SByte*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<SByte> op1, Vector64<SByte> op2, Vector64<SByte> op3, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] inArray3 = new SByte[Op3ElementCount];
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.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<SByte>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] inArray3 = new SByte[Op3ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (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, inArray3, outArray, method);
}
private void ValidateResult(SByte[] firstOp, SByte[] secondOp, SByte[] thirdOp, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.AbsoluteDifferenceAdd(firstOp[i], secondOp[i], thirdOp[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AbsoluteDifferenceAdd)}<SByte>(Vector64<SByte>, Vector64<SByte>, Vector64<SByte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/jit64/hfa/main/testA/hfa_nd0A_d.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>full</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="hfa_testA.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\dll\common.csproj" />
<ProjectReference Include="..\dll\hfa_nested_f64_common.csproj" />
<ProjectReference Include="..\dll\hfa_nested_f64_managed.csproj" />
<CMakeProjectReference Include="..\dll\CMakelists.txt" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>full</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="hfa_testA.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\dll\common.csproj" />
<ProjectReference Include="..\dll\hfa_nested_f64_common.csproj" />
<ProjectReference Include="..\dll\hfa_nested_f64_managed.csproj" />
<CMakeProjectReference Include="..\dll\CMakelists.txt" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/Regression/CLR-x86-JIT/V1.2-Beta1/b103058/b103058.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
internal struct VT
{
public float m1;
public bool m2;
public double m3;
public double m3_1;
public double m3_2;
public double m3_3;
public char m4;
}
internal unsafe class test
{
private static unsafe bool CheckDoubleAlignment1(VT* p)
{
Console.WriteLine("Address {0}", (IntPtr)p);
if (OperatingSystem.IsWindows() || (RuntimeInformation.ProcessArchitecture != Architecture.X86))
{
if ((int)(long)p % sizeof(double) != 0)
{
Console.WriteLine("not double aligned");
return false;
}
else
{
return true;
}
}
else
{
// Current JIT implementation doesn't use double alignment stack optimization for Linux/x86
return true;
}
}
public static int Main()
{
VT vt1 = new VT();
VT vt2 = new VT();
bool retVal;
retVal = CheckDoubleAlignment1(&vt1);
VT vt3 = new VT();
retVal = CheckDoubleAlignment1(&vt2) && retVal;
retVal = CheckDoubleAlignment1(&vt3) && retVal;
if (retVal)
{
Console.WriteLine("PASS");
return 100;
}
else
{
Console.WriteLine("FAIL");
return 0;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
internal struct VT
{
public float m1;
public bool m2;
public double m3;
public double m3_1;
public double m3_2;
public double m3_3;
public char m4;
}
internal unsafe class test
{
private static unsafe bool CheckDoubleAlignment1(VT* p)
{
Console.WriteLine("Address {0}", (IntPtr)p);
if (OperatingSystem.IsWindows() || (RuntimeInformation.ProcessArchitecture != Architecture.X86))
{
if ((int)(long)p % sizeof(double) != 0)
{
Console.WriteLine("not double aligned");
return false;
}
else
{
return true;
}
}
else
{
// Current JIT implementation doesn't use double alignment stack optimization for Linux/x86
return true;
}
}
public static int Main()
{
VT vt1 = new VT();
VT vt2 = new VT();
bool retVal;
retVal = CheckDoubleAlignment1(&vt1);
VT vt3 = new VT();
retVal = CheckDoubleAlignment1(&vt2) && retVal;
retVal = CheckDoubleAlignment1(&vt3) && retVal;
if (retVal)
{
Console.WriteLine("PASS");
return 100;
}
else
{
Console.WriteLine("FAIL");
return 0;
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/General/Vector256/LessThanAny.Double.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void LessThanAnyDouble()
{
var test = new VectorBooleanBinaryOpTest__LessThanAnyDouble();
// 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__LessThanAnyDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
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<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Double> _fld1;
public Vector256<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
return testStruct;
}
public void RunStructFldScenario(VectorBooleanBinaryOpTest__LessThanAnyDouble testClass)
{
var result = Vector256.LessThanAny(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector256<Double> _clsVar1;
private static Vector256<Double> _clsVar2;
private Vector256<Double> _fld1;
private Vector256<Double> _fld2;
private DataTable _dataTable;
static VectorBooleanBinaryOpTest__LessThanAnyDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
}
public VectorBooleanBinaryOpTest__LessThanAnyDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector256.LessThanAny(
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector256).GetMethod(nameof(Vector256.LessThanAny), new Type[] {
typeof(Vector256<Double>),
typeof(Vector256<Double>)
});
if (method is null)
{
method = typeof(Vector256).GetMethod(nameof(Vector256.LessThanAny), 1, new Type[] {
typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Double));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector256.LessThanAny(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr);
var result = Vector256.LessThanAny(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBooleanBinaryOpTest__LessThanAnyDouble();
var result = Vector256.LessThanAny(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector256.LessThanAny(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector256.LessThanAny(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector256<Double> op1, Vector256<Double> op2, bool result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Double[] left, Double[] 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(Vector256)}.{nameof(Vector256.LessThanAny)}<Double>(Vector256<Double>, Vector256<Double>): {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 LessThanAnyDouble()
{
var test = new VectorBooleanBinaryOpTest__LessThanAnyDouble();
// 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__LessThanAnyDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
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<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Double> _fld1;
public Vector256<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
return testStruct;
}
public void RunStructFldScenario(VectorBooleanBinaryOpTest__LessThanAnyDouble testClass)
{
var result = Vector256.LessThanAny(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector256<Double> _clsVar1;
private static Vector256<Double> _clsVar2;
private Vector256<Double> _fld1;
private Vector256<Double> _fld2;
private DataTable _dataTable;
static VectorBooleanBinaryOpTest__LessThanAnyDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
}
public VectorBooleanBinaryOpTest__LessThanAnyDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector256.LessThanAny(
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector256).GetMethod(nameof(Vector256.LessThanAny), new Type[] {
typeof(Vector256<Double>),
typeof(Vector256<Double>)
});
if (method is null)
{
method = typeof(Vector256).GetMethod(nameof(Vector256.LessThanAny), 1, new Type[] {
typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Double));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector256.LessThanAny(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr);
var result = Vector256.LessThanAny(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBooleanBinaryOpTest__LessThanAnyDouble();
var result = Vector256.LessThanAny(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector256.LessThanAny(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector256.LessThanAny(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector256<Double> op1, Vector256<Double> op2, bool result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Double[] left, Double[] 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(Vector256)}.{nameof(Vector256.LessThanAny)}<Double>(Vector256<Double>, Vector256<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/AddSaturateScalar.Vector64.Byte.Vector64.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.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 AddSaturateScalar_Vector64_Byte_Vector64_Byte()
{
var test = new SimpleBinaryOpTest__AddSaturateScalar_Vector64_Byte_Vector64_Byte();
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__AddSaturateScalar_Vector64_Byte_Vector64_Byte
{
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(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
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<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, 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<Byte> _fld1;
public Vector64<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddSaturateScalar_Vector64_Byte_Vector64_Byte testClass)
{
var result = AdvSimd.Arm64.AddSaturateScalar(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddSaturateScalar_Vector64_Byte_Vector64_Byte testClass)
{
fixed (Vector64<Byte>* pFld1 = &_fld1)
fixed (Vector64<Byte>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.AddSaturateScalar(
AdvSimd.LoadVector64((Byte*)(pFld1)),
AdvSimd.LoadVector64((Byte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector64<Byte> _clsVar1;
private static Vector64<Byte> _clsVar2;
private Vector64<Byte> _fld1;
private Vector64<Byte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddSaturateScalar_Vector64_Byte_Vector64_Byte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>());
}
public SimpleBinaryOpTest__AddSaturateScalar_Vector64_Byte_Vector64_Byte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, new Byte[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.AddSaturateScalar(
Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Arm64.AddSaturateScalar(
AdvSimd.LoadVector64((Byte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.AddSaturateScalar), new Type[] { typeof(Vector64<Byte>), typeof(Vector64<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.AddSaturateScalar), new Type[] { typeof(Vector64<Byte>), typeof(Vector64<Byte>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Byte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.AddSaturateScalar(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector64<Byte>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.Arm64.AddSaturateScalar(
AdvSimd.LoadVector64((Byte*)(pClsVar1)),
AdvSimd.LoadVector64((Byte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr);
var result = AdvSimd.Arm64.AddSaturateScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Byte*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((Byte*)(_dataTable.inArray2Ptr));
var result = AdvSimd.Arm64.AddSaturateScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddSaturateScalar_Vector64_Byte_Vector64_Byte();
var result = AdvSimd.Arm64.AddSaturateScalar(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__AddSaturateScalar_Vector64_Byte_Vector64_Byte();
fixed (Vector64<Byte>* pFld1 = &test._fld1)
fixed (Vector64<Byte>* pFld2 = &test._fld2)
{
var result = AdvSimd.Arm64.AddSaturateScalar(
AdvSimd.LoadVector64((Byte*)(pFld1)),
AdvSimd.LoadVector64((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.AddSaturateScalar(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Byte>* pFld1 = &_fld1)
fixed (Vector64<Byte>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.AddSaturateScalar(
AdvSimd.LoadVector64((Byte*)(pFld1)),
AdvSimd.LoadVector64((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.AddSaturateScalar(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.AddSaturateScalar(
AdvSimd.LoadVector64((Byte*)(&test._fld1)),
AdvSimd.LoadVector64((Byte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<Byte> op1, Vector64<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Helpers.AddSaturate(left[0], right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != 0)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.AddSaturateScalar)}<Byte>(Vector64<Byte>, Vector64<Byte>): {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 AddSaturateScalar_Vector64_Byte_Vector64_Byte()
{
var test = new SimpleBinaryOpTest__AddSaturateScalar_Vector64_Byte_Vector64_Byte();
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__AddSaturateScalar_Vector64_Byte_Vector64_Byte
{
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(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
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<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, 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<Byte> _fld1;
public Vector64<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddSaturateScalar_Vector64_Byte_Vector64_Byte testClass)
{
var result = AdvSimd.Arm64.AddSaturateScalar(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddSaturateScalar_Vector64_Byte_Vector64_Byte testClass)
{
fixed (Vector64<Byte>* pFld1 = &_fld1)
fixed (Vector64<Byte>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.AddSaturateScalar(
AdvSimd.LoadVector64((Byte*)(pFld1)),
AdvSimd.LoadVector64((Byte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector64<Byte> _clsVar1;
private static Vector64<Byte> _clsVar2;
private Vector64<Byte> _fld1;
private Vector64<Byte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddSaturateScalar_Vector64_Byte_Vector64_Byte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>());
}
public SimpleBinaryOpTest__AddSaturateScalar_Vector64_Byte_Vector64_Byte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, new Byte[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.AddSaturateScalar(
Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Arm64.AddSaturateScalar(
AdvSimd.LoadVector64((Byte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.AddSaturateScalar), new Type[] { typeof(Vector64<Byte>), typeof(Vector64<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.AddSaturateScalar), new Type[] { typeof(Vector64<Byte>), typeof(Vector64<Byte>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Byte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.AddSaturateScalar(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector64<Byte>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.Arm64.AddSaturateScalar(
AdvSimd.LoadVector64((Byte*)(pClsVar1)),
AdvSimd.LoadVector64((Byte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Byte>>(_dataTable.inArray2Ptr);
var result = AdvSimd.Arm64.AddSaturateScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Byte*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((Byte*)(_dataTable.inArray2Ptr));
var result = AdvSimd.Arm64.AddSaturateScalar(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddSaturateScalar_Vector64_Byte_Vector64_Byte();
var result = AdvSimd.Arm64.AddSaturateScalar(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__AddSaturateScalar_Vector64_Byte_Vector64_Byte();
fixed (Vector64<Byte>* pFld1 = &test._fld1)
fixed (Vector64<Byte>* pFld2 = &test._fld2)
{
var result = AdvSimd.Arm64.AddSaturateScalar(
AdvSimd.LoadVector64((Byte*)(pFld1)),
AdvSimd.LoadVector64((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.AddSaturateScalar(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Byte>* pFld1 = &_fld1)
fixed (Vector64<Byte>* pFld2 = &_fld2)
{
var result = AdvSimd.Arm64.AddSaturateScalar(
AdvSimd.LoadVector64((Byte*)(pFld1)),
AdvSimd.LoadVector64((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.AddSaturateScalar(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Arm64.AddSaturateScalar(
AdvSimd.LoadVector64((Byte*)(&test._fld1)),
AdvSimd.LoadVector64((Byte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<Byte> op1, Vector64<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Helpers.AddSaturate(left[0], right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != 0)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.AddSaturateScalar)}<Byte>(Vector64<Byte>, Vector64<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/GC/Scenarios/GCSimulator/GCSimulator_19.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<GCStressIncompatible>true</GCStressIncompatible>
<CLRTestExecutionArguments>-t 1 -tp 0 -dz 17 -sdz 8500 -dc 10000 -sdc 5000 -lt 4 -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 1 -tp 0 -dz 17 -sdz 8500 -dc 10000 -sdc 5000 -lt 4 -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 | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/reflection/DefaultInterfaceMethods/Emit.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<Compile Include="Emit.cs" />
</ItemGroup>
<ItemGroup>
<NoWarn Include="42016,42020,42025,42024" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<Compile Include="Emit.cs" />
</ItemGroup>
<ItemGroup>
<NoWarn Include="42016,42020,42025,42024" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Runtime/tests/System/OverflowExceptionTests.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.Tests
{
public static class OverflowExceptionTests
{
private const int COR_E_OVERFLOW = unchecked((int)0x80131516);
[Fact]
public static void Ctor_Empty()
{
var exception = new OverflowException();
ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_OVERFLOW, validateMessage: false);
}
[Fact]
public static void Ctor_String()
{
string message = "overflow";
var exception = new OverflowException(message);
ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_OVERFLOW, message: message);
}
[Fact]
public static void Ctor_String_Exception()
{
string message = "overflow";
var innerException = new Exception("Inner exception");
var exception = new OverflowException(message, innerException);
ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_OVERFLOW, innerException: innerException, message: message);
}
}
}
| // 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.Tests
{
public static class OverflowExceptionTests
{
private const int COR_E_OVERFLOW = unchecked((int)0x80131516);
[Fact]
public static void Ctor_Empty()
{
var exception = new OverflowException();
ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_OVERFLOW, validateMessage: false);
}
[Fact]
public static void Ctor_String()
{
string message = "overflow";
var exception = new OverflowException(message);
ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_OVERFLOW, message: message);
}
[Fact]
public static void Ctor_String_Exception()
{
string message = "overflow";
var innerException = new Exception("Inner exception");
var exception = new OverflowException(message, innerException);
ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_OVERFLOW, innerException: innerException, message: message);
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/CodeGenBringUpTests/JTrueEqInt1_d.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>Full</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="JTrueEqInt1.cs" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>Full</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="JTrueEqInt1.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/jit64/valuetypes/nullable/castclass/castclass/castclass040.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 ImplementOneInterfaceGen<int> 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((ImplementOneInterfaceGen<int>)(ValueType)o, Helper.Create(default(ImplementOneInterfaceGen<int>)));
}
private static bool BoxUnboxToQ(object o)
{
return Helper.Compare((ImplementOneInterfaceGen<int>?)(ValueType)o, Helper.Create(default(ImplementOneInterfaceGen<int>)));
}
private static int Main()
{
ImplementOneInterfaceGen<int>? s = Helper.Create(default(ImplementOneInterfaceGen<int>));
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 ImplementOneInterfaceGen<int> 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((ImplementOneInterfaceGen<int>)(ValueType)o, Helper.Create(default(ImplementOneInterfaceGen<int>)));
}
private static bool BoxUnboxToQ(object o)
{
return Helper.Compare((ImplementOneInterfaceGen<int>?)(ValueType)o, Helper.Create(default(ImplementOneInterfaceGen<int>)));
}
private static int Main()
{
ImplementOneInterfaceGen<int>? s = Helper.Create(default(ImplementOneInterfaceGen<int>));
if (BoxUnboxToNQ(s) && BoxUnboxToQ(s))
return ExitCode.Passed;
else
return ExitCode.Failed;
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/X86/Avx1/CompareGreaterThan.Double.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareGreaterThanDouble()
{
var test = new SimpleBinaryOpTest__CompareGreaterThanDouble();
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();
if (Avx.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 (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();
if (Avx.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 (Avx.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 (Avx.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 (Avx.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__CompareGreaterThanDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Double> _fld1;
public Vector256<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__CompareGreaterThanDouble testClass)
{
var result = Avx.CompareGreaterThan(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareGreaterThanDouble testClass)
{
fixed (Vector256<Double>* pFld1 = &_fld1)
fixed (Vector256<Double>* pFld2 = &_fld2)
{
var result = Avx.CompareGreaterThan(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2))
);
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<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector256<Double> _clsVar1;
private static Vector256<Double> _clsVar2;
private Vector256<Double> _fld1;
private Vector256<Double> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__CompareGreaterThanDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
}
public SimpleBinaryOpTest__CompareGreaterThanDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.CompareGreaterThan(
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.CompareGreaterThan(
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.CompareGreaterThan(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.CompareGreaterThan), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.CompareGreaterThan), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.CompareGreaterThan), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.CompareGreaterThan(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Double>* pClsVar1 = &_clsVar1)
fixed (Vector256<Double>* pClsVar2 = &_clsVar2)
{
var result = Avx.CompareGreaterThan(
Avx.LoadVector256((Double*)(pClsVar1)),
Avx.LoadVector256((Double*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr);
var result = Avx.CompareGreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.CompareGreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.CompareGreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__CompareGreaterThanDouble();
var result = Avx.CompareGreaterThan(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__CompareGreaterThanDouble();
fixed (Vector256<Double>* pFld1 = &test._fld1)
fixed (Vector256<Double>* pFld2 = &test._fld2)
{
var result = Avx.CompareGreaterThan(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.CompareGreaterThan(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Double>* pFld1 = &_fld1)
fixed (Vector256<Double>* pFld2 = &_fld2)
{
var result = Avx.CompareGreaterThan(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.CompareGreaterThan(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 = Avx.CompareGreaterThan(
Avx.LoadVector256((Double*)(&test._fld1)),
Avx.LoadVector256((Double*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Double> op1, Vector256<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(result[0]) != ((left[0] > right[0]) ? -1 : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != ((left[i] > right[i]) ? -1 : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.CompareGreaterThan)}<Double>(Vector256<Double>, Vector256<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareGreaterThanDouble()
{
var test = new SimpleBinaryOpTest__CompareGreaterThanDouble();
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();
if (Avx.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 (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();
if (Avx.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 (Avx.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 (Avx.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 (Avx.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__CompareGreaterThanDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Double> _fld1;
public Vector256<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__CompareGreaterThanDouble testClass)
{
var result = Avx.CompareGreaterThan(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareGreaterThanDouble testClass)
{
fixed (Vector256<Double>* pFld1 = &_fld1)
fixed (Vector256<Double>* pFld2 = &_fld2)
{
var result = Avx.CompareGreaterThan(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2))
);
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<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector256<Double> _clsVar1;
private static Vector256<Double> _clsVar2;
private Vector256<Double> _fld1;
private Vector256<Double> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__CompareGreaterThanDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
}
public SimpleBinaryOpTest__CompareGreaterThanDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.CompareGreaterThan(
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.CompareGreaterThan(
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.CompareGreaterThan(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.CompareGreaterThan), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.CompareGreaterThan), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.CompareGreaterThan), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.CompareGreaterThan(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Double>* pClsVar1 = &_clsVar1)
fixed (Vector256<Double>* pClsVar2 = &_clsVar2)
{
var result = Avx.CompareGreaterThan(
Avx.LoadVector256((Double*)(pClsVar1)),
Avx.LoadVector256((Double*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr);
var result = Avx.CompareGreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.CompareGreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.CompareGreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__CompareGreaterThanDouble();
var result = Avx.CompareGreaterThan(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__CompareGreaterThanDouble();
fixed (Vector256<Double>* pFld1 = &test._fld1)
fixed (Vector256<Double>* pFld2 = &test._fld2)
{
var result = Avx.CompareGreaterThan(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.CompareGreaterThan(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Double>* pFld1 = &_fld1)
fixed (Vector256<Double>* pFld2 = &_fld2)
{
var result = Avx.CompareGreaterThan(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.CompareGreaterThan(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 = Avx.CompareGreaterThan(
Avx.LoadVector256((Double*)(&test._fld1)),
Avx.LoadVector256((Double*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Double> op1, Vector256<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(result[0]) != ((left[0] > right[0]) ? -1 : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != ((left[i] > right[i]) ? -1 : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.CompareGreaterThan)}<Double>(Vector256<Double>, Vector256<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/GC/API/GCHandle/Casting.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. -->
<DebugType>PdbOnly</DebugType>
</PropertyGroup>
<ItemGroup>
<Compile Include="Casting.cs" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. -->
<DebugType>PdbOnly</DebugType>
</PropertyGroup>
<ItemGroup>
<Compile Include="Casting.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSA.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Formats.Asn1;
using System.IO;
using System.Runtime.Versioning;
using Internal.Cryptography;
namespace System.Security.Cryptography
{
public abstract partial class DSA : AsymmetricAlgorithm
{
// As of FIPS 186-4 the maximum Q size is 256 bits (32 bytes).
// The DER signature format thus maxes out at 2 + 3 + 33 + 3 + 33 => 74 bytes.
// So 128 should always work.
private const int SignatureStackSize = 128;
// The biggest supported hash algorithm is SHA-2-512, which is only 64 bytes.
// One power of two bigger should cover most unknown algorithms, too.
private const int HashBufferStackSize = 128;
public abstract DSAParameters ExportParameters(bool includePrivateParameters);
public abstract void ImportParameters(DSAParameters parameters);
protected DSA() { }
[RequiresUnreferencedCode(CryptoConfig.CreateFromNameUnreferencedCodeMessage)]
public static new DSA? Create(string algName)
{
return (DSA?)CryptoConfig.CreateFromName(algName);
}
[UnsupportedOSPlatform("browser")]
[UnsupportedOSPlatform("ios")]
[UnsupportedOSPlatform("tvos")]
public static new DSA Create()
{
return CreateCore();
}
[UnsupportedOSPlatform("browser")]
[UnsupportedOSPlatform("ios")]
[UnsupportedOSPlatform("tvos")]
public static DSA Create(int keySizeInBits)
{
DSA dsa = CreateCore();
try
{
dsa.KeySize = keySizeInBits;
return dsa;
}
catch
{
dsa.Dispose();
throw;
}
}
[UnsupportedOSPlatform("browser")]
[UnsupportedOSPlatform("ios")]
[UnsupportedOSPlatform("tvos")]
public static DSA Create(DSAParameters parameters)
{
DSA dsa = CreateCore();
try
{
dsa.ImportParameters(parameters);
return dsa;
}
catch
{
dsa.Dispose();
throw;
}
}
// DSA does not encode the algorithm identifier into the signature blob, therefore CreateSignature and
// VerifySignature do not need the HashAlgorithmName value, only SignData and VerifyData do.
public abstract byte[] CreateSignature(byte[] rgbHash);
public abstract bool VerifySignature(byte[] rgbHash, byte[] rgbSignature);
protected virtual byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
throw DerivedClassMustOverride();
}
protected virtual byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
{
throw DerivedClassMustOverride();
}
public byte[] SignData(byte[] data!!, HashAlgorithmName hashAlgorithm)
{
// hashAlgorithm is verified in the overload
return SignData(data, 0, data.Length, hashAlgorithm);
}
/// <summary>
/// Computes the hash value of the specified data and signs it using the specified signature format.
/// </summary>
/// <param name="data">The data to sign.</param>
/// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <returns>
/// The DSA signature for the specified data.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="hashAlgorithm"/> has a <see langword="null"/> or empty <see cref="HashAlgorithmName.Name"/>.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or signing operation.
/// </exception>
public byte[] SignData(byte[] data!!, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return SignDataCore(data, hashAlgorithm, signatureFormat);
}
public virtual byte[] SignData(byte[] data!!, int offset, int count, HashAlgorithmName hashAlgorithm)
{
if (offset < 0 || offset > data.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > data.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
byte[] hash = HashData(data, offset, count, hashAlgorithm);
return CreateSignature(hash);
}
/// <summary>
/// Computes the hash value of the specified data and signs it using the specified signature format.
/// </summary>
/// <param name="data">The data to sign.</param>
/// <param name="offset">The offset into <paramref name="data"/> at which to begin hashing.</param>
/// <param name="count">The number of bytes to read from <paramref name="data"/>.</param>
/// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <returns>
/// The DSA signature for the specified data.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
///
/// -or-
///
/// <paramref name="offset" /> is less than zero.
///
/// -or-
///
/// <paramref name="count" /> is less than zero.
///
/// -or-
///
/// <paramref name="offset" /> + <paramref name="count"/> - 1 results in an index that is
/// beyond the upper bound of <paramref name="data"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="hashAlgorithm"/> has a <see langword="null"/> or empty <see cref="HashAlgorithmName.Name"/>.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or signing operation.
/// </exception>
public byte[] SignData(
byte[] data!!,
int offset,
int count,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat)
{
if (offset < 0 || offset > data.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > data.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return SignDataCore(new ReadOnlySpan<byte>(data, offset, count), hashAlgorithm, signatureFormat);
}
/// <summary>
/// Computes the hash value of the specified data and signs it using the specified signature format.
/// </summary>
/// <param name="data">The data to sign.</param>
/// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <returns>
/// The DSA signature for the specified data.
/// </returns>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or signing operation.
/// </exception>
protected virtual byte[] SignDataCore(
ReadOnlySpan<byte> data,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat)
{
Span<byte> signature = stackalloc byte[SignatureStackSize];
if (TrySignDataCore(data, signature, hashAlgorithm, signatureFormat, out int bytesWritten))
{
return signature.Slice(0, bytesWritten).ToArray();
}
// If that didn't work, fall back on older approaches.
byte[] hash = HashSpanToArray(data, hashAlgorithm);
byte[] sig = CreateSignature(hash);
return AsymmetricAlgorithmHelpers.ConvertFromIeeeP1363Signature(sig, signatureFormat);
}
public virtual byte[] SignData(Stream data!!, HashAlgorithmName hashAlgorithm)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
byte[] hash = HashData(data, hashAlgorithm);
return CreateSignature(hash);
}
/// <summary>
/// Computes the hash value of the specified data and signs it using the specified signature format.
/// </summary>
/// <param name="data">The data to sign.</param>
/// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <returns>
/// The DSA signature for the specified data.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="hashAlgorithm"/> has a <see langword="null"/> or empty <see cref="HashAlgorithmName.Name"/>.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or signing operation.
/// </exception>
public byte[] SignData(Stream data!!, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return SignDataCore(data, hashAlgorithm, signatureFormat);
}
/// <summary>
/// Computes the hash value of the specified data and signs it using the specified signature format.
/// </summary>
/// <param name="data">The data to sign.</param>
/// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <returns>
/// The DSA signature for the specified data.
/// </returns>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or signing operation.
/// </exception>
protected virtual byte[] SignDataCore(Stream data, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat)
{
byte[] hash = HashData(data, hashAlgorithm);
return CreateSignatureCore(hash, signatureFormat);
}
public bool VerifyData(byte[] data!!, byte[] signature, HashAlgorithmName hashAlgorithm)
{
return VerifyData(data, 0, data.Length, signature, hashAlgorithm);
}
public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm)
{
ArgumentNullException.ThrowIfNull(data);
if (offset < 0 || offset > data.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > data.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
ArgumentNullException.ThrowIfNull(signature);
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
byte[] hash = HashData(data, offset, count, hashAlgorithm);
return VerifySignature(hash, signature);
}
/// <summary>
/// Verifies that a digital signature is valid for the provided data.
/// </summary>
/// <param name="data">An array that contains the signed data.</param>
/// <param name="offset">The starting index of the signed portion of <paramref name="data"/>.</param>
/// <param name="count">The number of bytes in <paramref name="data"/> that were signed.</param>
/// <param name="signature">The signature to verify.</param>
/// <param name="hashAlgorithm">The hash algorithm used to hash the data for the verification process.</param>
/// <param name="signatureFormat">The encoding format for <paramref name="signature"/>.</param>
/// <returns>
/// <see langword="true"/> if the digital signature is valid for the provided data; otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> or <paramref name="signature"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
///
/// -or-
///
/// <paramref name="offset" /> is less than zero.
///
/// -or-
///
/// <paramref name="count" /> is less than zero.
///
/// -or-
///
/// <paramref name="offset" /> + <paramref name="count"/> - 1 results in an index that is
/// beyond the upper bound of <paramref name="data"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="hashAlgorithm"/> has a <see langword="null"/> or empty <see cref="HashAlgorithmName.Name"/>.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or verification operation.
/// </exception>
public bool VerifyData(
byte[] data,
int offset,
int count,
byte[] signature,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat)
{
ArgumentNullException.ThrowIfNull(data);
if (offset < 0 || offset > data.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > data.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
ArgumentNullException.ThrowIfNull(signature);
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return VerifyDataCore(new ReadOnlySpan<byte>(data, offset, count), signature, hashAlgorithm, signatureFormat);
}
public virtual bool VerifyData(Stream data!!, byte[] signature!!, HashAlgorithmName hashAlgorithm)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
byte[] hash = HashData(data, hashAlgorithm);
return VerifySignature(hash, signature);
}
/// <summary>
/// Creates the DSA signature for the specified hash value in the indicated format.
/// </summary>
/// <param name="rgbHash">The hash value to sign.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <returns>
/// The DSA signature for the specified data.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="rgbHash"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the signing operation.
/// </exception>
public byte[] CreateSignature(byte[] rgbHash!!, DSASignatureFormat signatureFormat)
{
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return CreateSignatureCore(rgbHash, signatureFormat);
}
/// <summary>
/// Creates the DSA signature for the specified hash value in the indicated format.
/// </summary>
/// <param name="hash">The hash value to sign.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <returns>
/// The DSA signature for the specified data.
/// </returns>
/// <exception cref="CryptographicException">
/// An error occurred in the signing operation.
/// </exception>
protected virtual byte[] CreateSignatureCore(ReadOnlySpan<byte> hash, DSASignatureFormat signatureFormat)
{
Span<byte> signature = stackalloc byte[SignatureStackSize];
if (TryCreateSignatureCore(hash, signature, signatureFormat, out int bytesWritten))
{
return signature.Slice(0, bytesWritten).ToArray();
}
// If that didn't work, fall back to the older overload and convert formats.
byte[] sig = CreateSignature(hash.ToArray());
return AsymmetricAlgorithmHelpers.ConvertFromIeeeP1363Signature(sig, signatureFormat);
}
public virtual bool TryCreateSignature(ReadOnlySpan<byte> hash, Span<byte> destination, out int bytesWritten)
=> TryCreateSignatureCore(hash, destination, DSASignatureFormat.IeeeP1363FixedFieldConcatenation, out bytesWritten);
/// <summary>
/// Attempts to create the DSA signature for the specified hash value in the indicated format
/// into the provided buffer.
/// </summary>
/// <param name="hash">The hash value to sign.</param>
/// <param name="destination">The buffer to receive the signature.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <param name="bytesWritten">
/// When this method returns, contains a value that indicates the number of bytes written to
/// <paramref name="destination"/>. This parameter is treated as uninitialized.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="destination"/> is big enough to receive the signature;
/// otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the signing operation.
/// </exception>
public bool TryCreateSignature(
ReadOnlySpan<byte> hash,
Span<byte> destination,
DSASignatureFormat signatureFormat,
out int bytesWritten)
{
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return TryCreateSignatureCore(hash, destination, signatureFormat, out bytesWritten);
}
/// <summary>
/// Attempts to create the DSA signature for the specified hash value in the indicated format
/// into the provided buffer.
/// </summary>
/// <param name="hash">The hash value to sign.</param>
/// <param name="destination">The buffer to receive the signature.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <param name="bytesWritten">
/// When this method returns, contains a value that indicates the number of bytes written to
/// <paramref name="destination"/>. This parameter is treated as uninitialized.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="destination"/> is big enough to receive the signature;
/// otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="CryptographicException">
/// An error occurred in the signing operation.
/// </exception>
protected virtual bool TryCreateSignatureCore(
ReadOnlySpan<byte> hash,
Span<byte> destination,
DSASignatureFormat signatureFormat,
out int bytesWritten)
{
// This method is expected to be overriden with better implementation
// The only available implementation here is abstract method, use it
byte[] sig = CreateSignature(hash.ToArray());
if (signatureFormat != DSASignatureFormat.IeeeP1363FixedFieldConcatenation)
{
sig = AsymmetricAlgorithmHelpers.ConvertFromIeeeP1363Signature(sig, signatureFormat);
}
return Helpers.TryCopyToDestination(sig, destination, out bytesWritten);
}
protected virtual bool TryHashData(
ReadOnlySpan<byte> data,
Span<byte> destination,
HashAlgorithmName hashAlgorithm,
out int bytesWritten)
{
byte[] hash = HashSpanToArray(data, hashAlgorithm);
return Helpers.TryCopyToDestination(hash, destination, out bytesWritten);
}
public virtual bool TrySignData(
ReadOnlySpan<byte> data,
Span<byte> destination,
HashAlgorithmName hashAlgorithm,
out int bytesWritten)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
if (TryHashData(data, destination, hashAlgorithm, out int hashLength) &&
TryCreateSignature(destination.Slice(0, hashLength), destination, out bytesWritten))
{
return true;
}
bytesWritten = 0;
return false;
}
/// <summary>
/// Attempts to create the DSA signature for the specified data in the indicated format
/// into the provided buffer.
/// </summary>
/// <param name="data">The data to hash and sign.</param>
/// <param name="destination">The buffer to receive the signature.</param>
/// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <param name="bytesWritten">
/// When this method returns, contains a value that indicates the number of bytes written to
/// <paramref name="destination"/>. This parameter is treated as uninitialized.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="destination"/> is big enough to receive the signature;
/// otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="hashAlgorithm"/> has a <see langword="null"/> or empty <see cref="HashAlgorithmName.Name"/>.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the signing operation.
/// </exception>
public bool TrySignData(
ReadOnlySpan<byte> data,
Span<byte> destination,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat,
out int bytesWritten)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return TrySignDataCore(data, destination, hashAlgorithm, signatureFormat, out bytesWritten);
}
/// <summary>
/// Attempts to create the DSA signature for the specified data in the indicated format
/// into the provided buffer.
/// </summary>
/// <param name="data">The data to hash and sign.</param>
/// <param name="destination">The buffer to receive the signature.</param>
/// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <param name="bytesWritten">
/// When this method returns, contains a value that indicates the number of bytes written to
/// <paramref name="destination"/>. This parameter is treated as uninitialized.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="destination"/> is big enough to receive the signature;
/// otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="CryptographicException">
/// An error occurred in the signing operation.
/// </exception>
protected virtual bool TrySignDataCore(
ReadOnlySpan<byte> data,
Span<byte> destination,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat,
out int bytesWritten)
{
Span<byte> tmp = stackalloc byte[HashBufferStackSize];
ReadOnlySpan<byte> hash = HashSpanToTmp(data, hashAlgorithm, tmp);
return TryCreateSignatureCore(hash, destination, signatureFormat, out bytesWritten);
}
public virtual bool VerifyData(
ReadOnlySpan<byte> data,
ReadOnlySpan<byte> signature,
HashAlgorithmName hashAlgorithm)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
return VerifyDataCore(data, signature, hashAlgorithm, DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
}
/// <summary>
/// Verifies that a digital signature is valid for the provided data.
/// </summary>
/// <param name="data">The signed data.</param>
/// <param name="signature">The signature to verify.</param>
/// <param name="hashAlgorithm">The hash algorithm used to hash the data for the verification process.</param>
/// <param name="signatureFormat">The encoding format for <paramref name="signature"/>.</param>
/// <returns>
/// <see langword="true"/> if the digital signature is valid for the provided data; otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> or <paramref name="signature"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="hashAlgorithm"/> has a <see langword="null"/> or empty <see cref="HashAlgorithmName.Name"/>.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or verification operation.
/// </exception>
public bool VerifyData(
byte[] data!!,
byte[] signature!!,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return VerifyDataCore(data, signature, hashAlgorithm, signatureFormat);
}
/// <summary>
/// Verifies that a digital signature is valid for the provided data.
/// </summary>
/// <param name="data">The signed data.</param>
/// <param name="signature">The signature to verify.</param>
/// <param name="hashAlgorithm">The hash algorithm used to hash the data for the verification process.</param>
/// <param name="signatureFormat">The encoding format for <paramref name="signature"/>.</param>
/// <returns>
/// <see langword="true"/> if the digital signature is valid for the provided data; otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> or <paramref name="signature"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="hashAlgorithm"/> has a <see langword="null"/> or empty <see cref="HashAlgorithmName.Name"/>.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or verification operation.
/// </exception>
public bool VerifyData(
Stream data!!,
byte[] signature!!,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return VerifyDataCore(data, signature, hashAlgorithm, signatureFormat);
}
/// <summary>
/// Verifies that a digital signature is valid for the provided data.
/// </summary>
/// <param name="data">The signed data.</param>
/// <param name="signature">The signature to verify.</param>
/// <param name="hashAlgorithm">The hash algorithm used to hash the data for the verification process.</param>
/// <param name="signatureFormat">The encoding format for <paramref name="signature"/>.</param>
/// <returns>
/// <see langword="true"/> if the digital signature is valid for the provided data; otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or verification operation.
/// </exception>
protected virtual bool VerifyDataCore(
Stream data,
ReadOnlySpan<byte> signature,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat)
{
byte[] hash = HashData(data, hashAlgorithm);
return VerifySignatureCore(hash, signature, signatureFormat);
}
/// <summary>
/// Verifies that a digital signature is valid for the provided data.
/// </summary>
/// <param name="data">The signed data.</param>
/// <param name="signature">The signature to verify.</param>
/// <param name="hashAlgorithm">The hash algorithm used to hash the data for the verification process.</param>
/// <param name="signatureFormat">The encoding format for <paramref name="signature"/>.</param>
/// <returns>
/// <see langword="true"/> if the digital signature is valid for the provided data; otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or verification operation.
/// </exception>
public bool VerifyData(
ReadOnlySpan<byte> data,
ReadOnlySpan<byte> signature,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return VerifyDataCore(data, signature, hashAlgorithm, signatureFormat);
}
/// <summary>
/// Verifies that a digital signature is valid for the provided data.
/// </summary>
/// <param name="data">The signed data.</param>
/// <param name="signature">The signature to verify.</param>
/// <param name="hashAlgorithm">The hash algorithm used to hash the data for the verification process.</param>
/// <param name="signatureFormat">The encoding format for <paramref name="signature"/>.</param>
/// <returns>
/// <see langword="true"/> if the digital signature is valid for the provided data; otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or verification operation.
/// </exception>
protected virtual bool VerifyDataCore(
ReadOnlySpan<byte> data,
ReadOnlySpan<byte> signature,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat)
{
Span<byte> tmp = stackalloc byte[HashBufferStackSize];
ReadOnlySpan<byte> hash = HashSpanToTmp(data, hashAlgorithm, tmp);
return VerifySignatureCore(hash, signature, signatureFormat);
}
/// <summary>
/// Verifies that a digital signature is valid for the provided hash.
/// </summary>
/// <param name="rgbHash">The signed hash.</param>
/// <param name="rgbSignature">The signature to verify.</param>
/// <param name="signatureFormat">The encoding format for <paramref name="rgbSignature"/>.</param>
/// <returns>
/// <see langword="true"/> if the digital signature is valid for the provided data; otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="rgbHash"/> or <paramref name="rgbSignature"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the verification operation.
/// </exception>
public bool VerifySignature(byte[] rgbHash!!, byte[] rgbSignature!!, DSASignatureFormat signatureFormat)
{
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return VerifySignatureCore(rgbHash, rgbSignature, signatureFormat);
}
public virtual bool VerifySignature(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature) =>
VerifySignature(hash.ToArray(), signature.ToArray());
/// <summary>
/// Verifies that a digital signature is valid for the provided hash.
/// </summary>
/// <param name="hash">The signed hash.</param>
/// <param name="signature">The signature to verify.</param>
/// <param name="signatureFormat">The encoding format for <paramref name="signature"/>.</param>
/// <returns>
/// <see langword="true"/> if the digital signature is valid for the provided data; otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the verification operation.
/// </exception>
public bool VerifySignature(
ReadOnlySpan<byte> hash,
ReadOnlySpan<byte> signature,
DSASignatureFormat signatureFormat)
{
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return VerifySignatureCore(hash, signature, signatureFormat);
}
/// <summary>
/// Verifies that a digital signature is valid for the provided hash.
/// </summary>
/// <param name="hash">The signed hash.</param>
/// <param name="signature">The signature to verify.</param>
/// <param name="signatureFormat">The encoding format for <paramref name="signature"/>.</param>
/// <returns>
/// <see langword="true"/> if the digital signature is valid for the provided data; otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="CryptographicException">
/// An error occurred in the verification operation.
/// </exception>
protected virtual bool VerifySignatureCore(
ReadOnlySpan<byte> hash,
ReadOnlySpan<byte> signature,
DSASignatureFormat signatureFormat)
{
// This method is expected to be overriden with better implementation
byte[]? sig = this.ConvertSignatureToIeeeP1363(signatureFormat, signature);
// If the signature failed normalization to IEEE P1363 then it
// obviously doesn't verify.
if (sig == null)
{
return false;
}
// The only available implementation here is abstract method, use it.
// Since it requires an exactly-sized array, skip pooled arrays.
return VerifySignature(hash, sig);
}
private ReadOnlySpan<byte> HashSpanToTmp(
ReadOnlySpan<byte> data,
HashAlgorithmName hashAlgorithm,
Span<byte> tmp)
{
Debug.Assert(tmp.Length == HashBufferStackSize);
if (TryHashData(data, tmp, hashAlgorithm, out int hashSize))
{
return tmp.Slice(0, hashSize);
}
// This is not expected, but a poor virtual implementation of TryHashData,
// or an exotic new algorithm, will hit this fallback.
return HashSpanToArray(data, hashAlgorithm);
}
private byte[] HashSpanToArray(ReadOnlySpan<byte> data, HashAlgorithmName hashAlgorithm)
{
// Use ArrayPool.Shared instead of CryptoPool because the array is passed out.
byte[] array = ArrayPool<byte>.Shared.Rent(data.Length);
bool returnArray = false;
try
{
data.CopyTo(array);
byte[] ret = HashData(array, 0, data.Length, hashAlgorithm);
returnArray = true;
return ret;
}
finally
{
Array.Clear(array, 0, data.Length);
if (returnArray)
{
ArrayPool<byte>.Shared.Return(array);
}
}
}
private static Exception DerivedClassMustOverride() =>
new NotImplementedException(SR.NotSupported_SubclassOverride);
public override bool TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
PbeParameters pbeParameters!!,
Span<byte> destination,
out int bytesWritten)
{
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
ReadOnlySpan<char>.Empty,
passwordBytes);
AsnWriter pkcs8PrivateKey = WritePkcs8();
AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8(
passwordBytes,
pkcs8PrivateKey,
pbeParameters);
return writer.TryEncode(destination, out bytesWritten);
}
public override bool TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
PbeParameters pbeParameters!!,
Span<byte> destination,
out int bytesWritten)
{
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
password,
ReadOnlySpan<byte>.Empty);
AsnWriter pkcs8PrivateKey = WritePkcs8();
AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8(
password,
pkcs8PrivateKey,
pbeParameters);
return writer.TryEncode(destination, out bytesWritten);
}
public override bool TryExportPkcs8PrivateKey(
Span<byte> destination,
out int bytesWritten)
{
AsnWriter writer = WritePkcs8();
return writer.TryEncode(destination, out bytesWritten);
}
public override bool TryExportSubjectPublicKeyInfo(
Span<byte> destination,
out int bytesWritten)
{
AsnWriter writer = WriteSubjectPublicKeyInfo();
return writer.TryEncode(destination, out bytesWritten);
}
private unsafe AsnWriter WritePkcs8()
{
DSAParameters dsaParameters = ExportParameters(true);
fixed (byte* privPin = dsaParameters.X)
{
try
{
return DSAKeyFormatHelper.WritePkcs8(dsaParameters);
}
finally
{
CryptographicOperations.ZeroMemory(dsaParameters.X);
}
}
}
private AsnWriter WriteSubjectPublicKeyInfo()
{
DSAParameters dsaParameters = ExportParameters(false);
return DSAKeyFormatHelper.WriteSubjectPublicKeyInfo(dsaParameters);
}
public override unsafe void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
ReadOnlySpan<byte> source,
out int bytesRead)
{
DSAKeyFormatHelper.ReadEncryptedPkcs8(
source,
passwordBytes,
out int localRead,
out DSAParameters ret);
fixed (byte* privPin = ret.X)
{
try
{
ImportParameters(ret);
}
finally
{
CryptographicOperations.ZeroMemory(ret.X);
}
}
bytesRead = localRead;
}
public override unsafe void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
ReadOnlySpan<byte> source,
out int bytesRead)
{
DSAKeyFormatHelper.ReadEncryptedPkcs8(
source,
password,
out int localRead,
out DSAParameters ret);
fixed (byte* privPin = ret.X)
{
try
{
ImportParameters(ret);
}
finally
{
CryptographicOperations.ZeroMemory(ret.X);
}
}
bytesRead = localRead;
}
public override unsafe void ImportPkcs8PrivateKey(
ReadOnlySpan<byte> source,
out int bytesRead)
{
DSAKeyFormatHelper.ReadPkcs8(
source,
out int localRead,
out DSAParameters key);
fixed (byte* privPin = key.X)
{
try
{
ImportParameters(key);
}
finally
{
CryptographicOperations.ZeroMemory(key.X);
}
}
bytesRead = localRead;
}
public override void ImportSubjectPublicKeyInfo(
ReadOnlySpan<byte> source,
out int bytesRead)
{
DSAKeyFormatHelper.ReadSubjectPublicKeyInfo(
source,
out int localRead,
out DSAParameters key);
ImportParameters(key);
bytesRead = localRead;
}
/// <summary>
/// Gets the largest size, in bytes, for a signature produced by this key in the indicated format.
/// </summary>
/// <param name="signatureFormat">The encoding format for a signature.</param>
/// <returns>
/// The largest size, in bytes, for a signature produced by this key in the indicated format.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
public int GetMaxSignatureSize(DSASignatureFormat signatureFormat)
{
DSAParameters dsaParameters = ExportParameters(false);
int qLength = dsaParameters.Q!.Length;
switch (signatureFormat)
{
case DSASignatureFormat.IeeeP1363FixedFieldConcatenation:
return qLength * 2;
case DSASignatureFormat.Rfc3279DerSequence:
return AsymmetricAlgorithmHelpers.GetMaxDerSignatureSize(fieldSizeBits: qLength * 8);
default:
throw new ArgumentOutOfRangeException(nameof(signatureFormat));
}
}
/// <summary>
/// Imports an RFC 7468 PEM-encoded key, replacing the keys for this object.
/// </summary>
/// <param name="input">The PEM text of the key to import.</param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="input"/> does not contain a PEM-encoded key with a recognized label.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="input"/> contains multiple PEM-encoded keys with a recognized label.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="input"/> contains an encrypted PEM-encoded key.
/// </para>
/// </exception>
/// <remarks>
/// <para>
/// Unsupported or malformed PEM-encoded objects will be ignored. If multiple supported PEM labels
/// are found, an exception is raised to prevent importing a key when
/// the key is ambiguous.
/// </para>
/// <para>
/// This method supports the following PEM labels:
/// <list type="bullet">
/// <item><description>PUBLIC KEY</description></item>
/// <item><description>PRIVATE KEY</description></item>
/// </list>
/// </para>
/// </remarks>
public override void ImportFromPem(ReadOnlySpan<char> input)
{
// Implementation has been pushed down to AsymmetricAlgorithm. The
// override remains for compatibility.
base.ImportFromPem(input);
}
/// <summary>
/// Imports an encrypted RFC 7468 PEM-encoded private key, replacing the keys for this object.
/// </summary>
/// <param name="input">The PEM text of the encrypted key to import.</param>
/// <param name="password">
/// The password to use for decrypting the key material.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="input"/> does not contain a PEM-encoded key with a recognized label.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="input"/> contains multiple PEM-encoded keys with a recognized label.
/// </para>
/// </exception>
/// <exception cref="CryptographicException">
/// <para>
/// The password is incorrect.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The base-64 decoded contents of the PEM text from <paramref name="input" />
/// do not represent an ASN.1-BER-encoded PKCS#8 EncryptedPrivateKeyInfo structure.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The base-64 decoded contents of the PEM text from <paramref name="input" />
/// indicate the key is for an algorithm other than the algorithm
/// represented by this instance.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The base-64 decoded contents of the PEM text from <paramref name="input" />
/// represent the key in a format that is not supported.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The algorithm-specific key import failed.
/// </para>
/// </exception>
/// <remarks>
/// <para>
/// When the base-64 decoded contents of <paramref name="input" /> indicate an algorithm that uses PBKDF1
/// (Password-Based Key Derivation Function 1) or PBKDF2 (Password-Based Key Derivation Function 2),
/// the password is converted to bytes via the UTF-8 encoding.
/// </para>
/// <para>
/// Unsupported or malformed PEM-encoded objects will be ignored. If multiple supported PEM labels
/// are found, an exception is thrown to prevent importing a key when
/// the key is ambiguous.
/// </para>
/// <para>This method supports the <c>ENCRYPTED PRIVATE KEY</c> PEM label.</para>
/// </remarks>
public override void ImportFromEncryptedPem(ReadOnlySpan<char> input, ReadOnlySpan<char> password)
{
// Implementation has been pushed down to AsymmetricAlgorithm. The
// override remains for compatibility.
base.ImportFromEncryptedPem(input, password);
}
/// <summary>
/// Imports an encrypted RFC 7468 PEM-encoded private key, replacing the keys for this object.
/// </summary>
/// <param name="input">The PEM text of the encrypted key to import.</param>
/// <param name="passwordBytes">
/// The bytes to use as a password when decrypting the key material.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="input"/> does not contain a PEM-encoded key with a recognized label.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="input"/> contains multiple PEM-encoded keys with a recognized label.
/// </para>
/// </exception>
/// <exception cref="CryptographicException">
/// <para>
/// The password is incorrect.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The base-64 decoded contents of the PEM text from <paramref name="input" />
/// do not represent an ASN.1-BER-encoded PKCS#8 EncryptedPrivateKeyInfo structure.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The base-64 decoded contents of the PEM text from <paramref name="input" />
/// indicate the key is for an algorithm other than the algorithm
/// represented by this instance.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The base-64 decoded contents of the PEM text from <paramref name="input" />
/// represent the key in a format that is not supported.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The algorithm-specific key import failed.
/// </para>
/// </exception>
/// <remarks>
/// <para>
/// The password bytes are passed directly into the Key Derivation Function (KDF)
/// used by the algorithm indicated by <c>pbeParameters</c>. This enables compatibility
/// with other systems which use a text encoding other than UTF-8 when processing
/// passwords with PBKDF2 (Password-Based Key Derivation Function 2).
/// </para>
/// <para>
/// Unsupported or malformed PEM-encoded objects will be ignored. If multiple supported PEM labels
/// are found, an exception is thrown to prevent importing a key when
/// the key is ambiguous.
/// </para>
/// <para>This method supports the <c>ENCRYPTED PRIVATE KEY</c> PEM label.</para>
/// </remarks>
public override void ImportFromEncryptedPem(ReadOnlySpan<char> input, ReadOnlySpan<byte> passwordBytes)
{
// Implementation has been pushed down to AsymmetricAlgorithm. The
// override remains for compatibility.
base.ImportFromEncryptedPem(input, passwordBytes);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Formats.Asn1;
using System.IO;
using System.Runtime.Versioning;
using Internal.Cryptography;
namespace System.Security.Cryptography
{
public abstract partial class DSA : AsymmetricAlgorithm
{
// As of FIPS 186-4 the maximum Q size is 256 bits (32 bytes).
// The DER signature format thus maxes out at 2 + 3 + 33 + 3 + 33 => 74 bytes.
// So 128 should always work.
private const int SignatureStackSize = 128;
// The biggest supported hash algorithm is SHA-2-512, which is only 64 bytes.
// One power of two bigger should cover most unknown algorithms, too.
private const int HashBufferStackSize = 128;
public abstract DSAParameters ExportParameters(bool includePrivateParameters);
public abstract void ImportParameters(DSAParameters parameters);
protected DSA() { }
[RequiresUnreferencedCode(CryptoConfig.CreateFromNameUnreferencedCodeMessage)]
public static new DSA? Create(string algName)
{
return (DSA?)CryptoConfig.CreateFromName(algName);
}
[UnsupportedOSPlatform("browser")]
[UnsupportedOSPlatform("ios")]
[UnsupportedOSPlatform("tvos")]
public static new DSA Create()
{
return CreateCore();
}
[UnsupportedOSPlatform("browser")]
[UnsupportedOSPlatform("ios")]
[UnsupportedOSPlatform("tvos")]
public static DSA Create(int keySizeInBits)
{
DSA dsa = CreateCore();
try
{
dsa.KeySize = keySizeInBits;
return dsa;
}
catch
{
dsa.Dispose();
throw;
}
}
[UnsupportedOSPlatform("browser")]
[UnsupportedOSPlatform("ios")]
[UnsupportedOSPlatform("tvos")]
public static DSA Create(DSAParameters parameters)
{
DSA dsa = CreateCore();
try
{
dsa.ImportParameters(parameters);
return dsa;
}
catch
{
dsa.Dispose();
throw;
}
}
// DSA does not encode the algorithm identifier into the signature blob, therefore CreateSignature and
// VerifySignature do not need the HashAlgorithmName value, only SignData and VerifyData do.
public abstract byte[] CreateSignature(byte[] rgbHash);
public abstract bool VerifySignature(byte[] rgbHash, byte[] rgbSignature);
protected virtual byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
throw DerivedClassMustOverride();
}
protected virtual byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
{
throw DerivedClassMustOverride();
}
public byte[] SignData(byte[] data!!, HashAlgorithmName hashAlgorithm)
{
// hashAlgorithm is verified in the overload
return SignData(data, 0, data.Length, hashAlgorithm);
}
/// <summary>
/// Computes the hash value of the specified data and signs it using the specified signature format.
/// </summary>
/// <param name="data">The data to sign.</param>
/// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <returns>
/// The DSA signature for the specified data.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="hashAlgorithm"/> has a <see langword="null"/> or empty <see cref="HashAlgorithmName.Name"/>.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or signing operation.
/// </exception>
public byte[] SignData(byte[] data!!, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return SignDataCore(data, hashAlgorithm, signatureFormat);
}
public virtual byte[] SignData(byte[] data!!, int offset, int count, HashAlgorithmName hashAlgorithm)
{
if (offset < 0 || offset > data.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > data.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
byte[] hash = HashData(data, offset, count, hashAlgorithm);
return CreateSignature(hash);
}
/// <summary>
/// Computes the hash value of the specified data and signs it using the specified signature format.
/// </summary>
/// <param name="data">The data to sign.</param>
/// <param name="offset">The offset into <paramref name="data"/> at which to begin hashing.</param>
/// <param name="count">The number of bytes to read from <paramref name="data"/>.</param>
/// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <returns>
/// The DSA signature for the specified data.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
///
/// -or-
///
/// <paramref name="offset" /> is less than zero.
///
/// -or-
///
/// <paramref name="count" /> is less than zero.
///
/// -or-
///
/// <paramref name="offset" /> + <paramref name="count"/> - 1 results in an index that is
/// beyond the upper bound of <paramref name="data"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="hashAlgorithm"/> has a <see langword="null"/> or empty <see cref="HashAlgorithmName.Name"/>.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or signing operation.
/// </exception>
public byte[] SignData(
byte[] data!!,
int offset,
int count,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat)
{
if (offset < 0 || offset > data.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > data.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return SignDataCore(new ReadOnlySpan<byte>(data, offset, count), hashAlgorithm, signatureFormat);
}
/// <summary>
/// Computes the hash value of the specified data and signs it using the specified signature format.
/// </summary>
/// <param name="data">The data to sign.</param>
/// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <returns>
/// The DSA signature for the specified data.
/// </returns>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or signing operation.
/// </exception>
protected virtual byte[] SignDataCore(
ReadOnlySpan<byte> data,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat)
{
Span<byte> signature = stackalloc byte[SignatureStackSize];
if (TrySignDataCore(data, signature, hashAlgorithm, signatureFormat, out int bytesWritten))
{
return signature.Slice(0, bytesWritten).ToArray();
}
// If that didn't work, fall back on older approaches.
byte[] hash = HashSpanToArray(data, hashAlgorithm);
byte[] sig = CreateSignature(hash);
return AsymmetricAlgorithmHelpers.ConvertFromIeeeP1363Signature(sig, signatureFormat);
}
public virtual byte[] SignData(Stream data!!, HashAlgorithmName hashAlgorithm)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
byte[] hash = HashData(data, hashAlgorithm);
return CreateSignature(hash);
}
/// <summary>
/// Computes the hash value of the specified data and signs it using the specified signature format.
/// </summary>
/// <param name="data">The data to sign.</param>
/// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <returns>
/// The DSA signature for the specified data.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="hashAlgorithm"/> has a <see langword="null"/> or empty <see cref="HashAlgorithmName.Name"/>.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or signing operation.
/// </exception>
public byte[] SignData(Stream data!!, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return SignDataCore(data, hashAlgorithm, signatureFormat);
}
/// <summary>
/// Computes the hash value of the specified data and signs it using the specified signature format.
/// </summary>
/// <param name="data">The data to sign.</param>
/// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <returns>
/// The DSA signature for the specified data.
/// </returns>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or signing operation.
/// </exception>
protected virtual byte[] SignDataCore(Stream data, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat)
{
byte[] hash = HashData(data, hashAlgorithm);
return CreateSignatureCore(hash, signatureFormat);
}
public bool VerifyData(byte[] data!!, byte[] signature, HashAlgorithmName hashAlgorithm)
{
return VerifyData(data, 0, data.Length, signature, hashAlgorithm);
}
public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm)
{
ArgumentNullException.ThrowIfNull(data);
if (offset < 0 || offset > data.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > data.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
ArgumentNullException.ThrowIfNull(signature);
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
byte[] hash = HashData(data, offset, count, hashAlgorithm);
return VerifySignature(hash, signature);
}
/// <summary>
/// Verifies that a digital signature is valid for the provided data.
/// </summary>
/// <param name="data">An array that contains the signed data.</param>
/// <param name="offset">The starting index of the signed portion of <paramref name="data"/>.</param>
/// <param name="count">The number of bytes in <paramref name="data"/> that were signed.</param>
/// <param name="signature">The signature to verify.</param>
/// <param name="hashAlgorithm">The hash algorithm used to hash the data for the verification process.</param>
/// <param name="signatureFormat">The encoding format for <paramref name="signature"/>.</param>
/// <returns>
/// <see langword="true"/> if the digital signature is valid for the provided data; otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> or <paramref name="signature"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
///
/// -or-
///
/// <paramref name="offset" /> is less than zero.
///
/// -or-
///
/// <paramref name="count" /> is less than zero.
///
/// -or-
///
/// <paramref name="offset" /> + <paramref name="count"/> - 1 results in an index that is
/// beyond the upper bound of <paramref name="data"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="hashAlgorithm"/> has a <see langword="null"/> or empty <see cref="HashAlgorithmName.Name"/>.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or verification operation.
/// </exception>
public bool VerifyData(
byte[] data,
int offset,
int count,
byte[] signature,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat)
{
ArgumentNullException.ThrowIfNull(data);
if (offset < 0 || offset > data.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > data.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
ArgumentNullException.ThrowIfNull(signature);
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return VerifyDataCore(new ReadOnlySpan<byte>(data, offset, count), signature, hashAlgorithm, signatureFormat);
}
public virtual bool VerifyData(Stream data!!, byte[] signature!!, HashAlgorithmName hashAlgorithm)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
byte[] hash = HashData(data, hashAlgorithm);
return VerifySignature(hash, signature);
}
/// <summary>
/// Creates the DSA signature for the specified hash value in the indicated format.
/// </summary>
/// <param name="rgbHash">The hash value to sign.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <returns>
/// The DSA signature for the specified data.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="rgbHash"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the signing operation.
/// </exception>
public byte[] CreateSignature(byte[] rgbHash!!, DSASignatureFormat signatureFormat)
{
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return CreateSignatureCore(rgbHash, signatureFormat);
}
/// <summary>
/// Creates the DSA signature for the specified hash value in the indicated format.
/// </summary>
/// <param name="hash">The hash value to sign.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <returns>
/// The DSA signature for the specified data.
/// </returns>
/// <exception cref="CryptographicException">
/// An error occurred in the signing operation.
/// </exception>
protected virtual byte[] CreateSignatureCore(ReadOnlySpan<byte> hash, DSASignatureFormat signatureFormat)
{
Span<byte> signature = stackalloc byte[SignatureStackSize];
if (TryCreateSignatureCore(hash, signature, signatureFormat, out int bytesWritten))
{
return signature.Slice(0, bytesWritten).ToArray();
}
// If that didn't work, fall back to the older overload and convert formats.
byte[] sig = CreateSignature(hash.ToArray());
return AsymmetricAlgorithmHelpers.ConvertFromIeeeP1363Signature(sig, signatureFormat);
}
public virtual bool TryCreateSignature(ReadOnlySpan<byte> hash, Span<byte> destination, out int bytesWritten)
=> TryCreateSignatureCore(hash, destination, DSASignatureFormat.IeeeP1363FixedFieldConcatenation, out bytesWritten);
/// <summary>
/// Attempts to create the DSA signature for the specified hash value in the indicated format
/// into the provided buffer.
/// </summary>
/// <param name="hash">The hash value to sign.</param>
/// <param name="destination">The buffer to receive the signature.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <param name="bytesWritten">
/// When this method returns, contains a value that indicates the number of bytes written to
/// <paramref name="destination"/>. This parameter is treated as uninitialized.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="destination"/> is big enough to receive the signature;
/// otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the signing operation.
/// </exception>
public bool TryCreateSignature(
ReadOnlySpan<byte> hash,
Span<byte> destination,
DSASignatureFormat signatureFormat,
out int bytesWritten)
{
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return TryCreateSignatureCore(hash, destination, signatureFormat, out bytesWritten);
}
/// <summary>
/// Attempts to create the DSA signature for the specified hash value in the indicated format
/// into the provided buffer.
/// </summary>
/// <param name="hash">The hash value to sign.</param>
/// <param name="destination">The buffer to receive the signature.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <param name="bytesWritten">
/// When this method returns, contains a value that indicates the number of bytes written to
/// <paramref name="destination"/>. This parameter is treated as uninitialized.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="destination"/> is big enough to receive the signature;
/// otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="CryptographicException">
/// An error occurred in the signing operation.
/// </exception>
protected virtual bool TryCreateSignatureCore(
ReadOnlySpan<byte> hash,
Span<byte> destination,
DSASignatureFormat signatureFormat,
out int bytesWritten)
{
// This method is expected to be overriden with better implementation
// The only available implementation here is abstract method, use it
byte[] sig = CreateSignature(hash.ToArray());
if (signatureFormat != DSASignatureFormat.IeeeP1363FixedFieldConcatenation)
{
sig = AsymmetricAlgorithmHelpers.ConvertFromIeeeP1363Signature(sig, signatureFormat);
}
return Helpers.TryCopyToDestination(sig, destination, out bytesWritten);
}
protected virtual bool TryHashData(
ReadOnlySpan<byte> data,
Span<byte> destination,
HashAlgorithmName hashAlgorithm,
out int bytesWritten)
{
byte[] hash = HashSpanToArray(data, hashAlgorithm);
return Helpers.TryCopyToDestination(hash, destination, out bytesWritten);
}
public virtual bool TrySignData(
ReadOnlySpan<byte> data,
Span<byte> destination,
HashAlgorithmName hashAlgorithm,
out int bytesWritten)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
if (TryHashData(data, destination, hashAlgorithm, out int hashLength) &&
TryCreateSignature(destination.Slice(0, hashLength), destination, out bytesWritten))
{
return true;
}
bytesWritten = 0;
return false;
}
/// <summary>
/// Attempts to create the DSA signature for the specified data in the indicated format
/// into the provided buffer.
/// </summary>
/// <param name="data">The data to hash and sign.</param>
/// <param name="destination">The buffer to receive the signature.</param>
/// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <param name="bytesWritten">
/// When this method returns, contains a value that indicates the number of bytes written to
/// <paramref name="destination"/>. This parameter is treated as uninitialized.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="destination"/> is big enough to receive the signature;
/// otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="hashAlgorithm"/> has a <see langword="null"/> or empty <see cref="HashAlgorithmName.Name"/>.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the signing operation.
/// </exception>
public bool TrySignData(
ReadOnlySpan<byte> data,
Span<byte> destination,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat,
out int bytesWritten)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return TrySignDataCore(data, destination, hashAlgorithm, signatureFormat, out bytesWritten);
}
/// <summary>
/// Attempts to create the DSA signature for the specified data in the indicated format
/// into the provided buffer.
/// </summary>
/// <param name="data">The data to hash and sign.</param>
/// <param name="destination">The buffer to receive the signature.</param>
/// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param>
/// <param name="signatureFormat">The encoding format to use for the signature.</param>
/// <param name="bytesWritten">
/// When this method returns, contains a value that indicates the number of bytes written to
/// <paramref name="destination"/>. This parameter is treated as uninitialized.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="destination"/> is big enough to receive the signature;
/// otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="CryptographicException">
/// An error occurred in the signing operation.
/// </exception>
protected virtual bool TrySignDataCore(
ReadOnlySpan<byte> data,
Span<byte> destination,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat,
out int bytesWritten)
{
Span<byte> tmp = stackalloc byte[HashBufferStackSize];
ReadOnlySpan<byte> hash = HashSpanToTmp(data, hashAlgorithm, tmp);
return TryCreateSignatureCore(hash, destination, signatureFormat, out bytesWritten);
}
public virtual bool VerifyData(
ReadOnlySpan<byte> data,
ReadOnlySpan<byte> signature,
HashAlgorithmName hashAlgorithm)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
return VerifyDataCore(data, signature, hashAlgorithm, DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
}
/// <summary>
/// Verifies that a digital signature is valid for the provided data.
/// </summary>
/// <param name="data">The signed data.</param>
/// <param name="signature">The signature to verify.</param>
/// <param name="hashAlgorithm">The hash algorithm used to hash the data for the verification process.</param>
/// <param name="signatureFormat">The encoding format for <paramref name="signature"/>.</param>
/// <returns>
/// <see langword="true"/> if the digital signature is valid for the provided data; otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> or <paramref name="signature"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="hashAlgorithm"/> has a <see langword="null"/> or empty <see cref="HashAlgorithmName.Name"/>.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or verification operation.
/// </exception>
public bool VerifyData(
byte[] data!!,
byte[] signature!!,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return VerifyDataCore(data, signature, hashAlgorithm, signatureFormat);
}
/// <summary>
/// Verifies that a digital signature is valid for the provided data.
/// </summary>
/// <param name="data">The signed data.</param>
/// <param name="signature">The signature to verify.</param>
/// <param name="hashAlgorithm">The hash algorithm used to hash the data for the verification process.</param>
/// <param name="signatureFormat">The encoding format for <paramref name="signature"/>.</param>
/// <returns>
/// <see langword="true"/> if the digital signature is valid for the provided data; otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="data"/> or <paramref name="signature"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="hashAlgorithm"/> has a <see langword="null"/> or empty <see cref="HashAlgorithmName.Name"/>.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or verification operation.
/// </exception>
public bool VerifyData(
Stream data!!,
byte[] signature!!,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return VerifyDataCore(data, signature, hashAlgorithm, signatureFormat);
}
/// <summary>
/// Verifies that a digital signature is valid for the provided data.
/// </summary>
/// <param name="data">The signed data.</param>
/// <param name="signature">The signature to verify.</param>
/// <param name="hashAlgorithm">The hash algorithm used to hash the data for the verification process.</param>
/// <param name="signatureFormat">The encoding format for <paramref name="signature"/>.</param>
/// <returns>
/// <see langword="true"/> if the digital signature is valid for the provided data; otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or verification operation.
/// </exception>
protected virtual bool VerifyDataCore(
Stream data,
ReadOnlySpan<byte> signature,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat)
{
byte[] hash = HashData(data, hashAlgorithm);
return VerifySignatureCore(hash, signature, signatureFormat);
}
/// <summary>
/// Verifies that a digital signature is valid for the provided data.
/// </summary>
/// <param name="data">The signed data.</param>
/// <param name="signature">The signature to verify.</param>
/// <param name="hashAlgorithm">The hash algorithm used to hash the data for the verification process.</param>
/// <param name="signatureFormat">The encoding format for <paramref name="signature"/>.</param>
/// <returns>
/// <see langword="true"/> if the digital signature is valid for the provided data; otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or verification operation.
/// </exception>
public bool VerifyData(
ReadOnlySpan<byte> data,
ReadOnlySpan<byte> signature,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat)
{
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return VerifyDataCore(data, signature, hashAlgorithm, signatureFormat);
}
/// <summary>
/// Verifies that a digital signature is valid for the provided data.
/// </summary>
/// <param name="data">The signed data.</param>
/// <param name="signature">The signature to verify.</param>
/// <param name="hashAlgorithm">The hash algorithm used to hash the data for the verification process.</param>
/// <param name="signatureFormat">The encoding format for <paramref name="signature"/>.</param>
/// <returns>
/// <see langword="true"/> if the digital signature is valid for the provided data; otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="CryptographicException">
/// An error occurred in the hashing or verification operation.
/// </exception>
protected virtual bool VerifyDataCore(
ReadOnlySpan<byte> data,
ReadOnlySpan<byte> signature,
HashAlgorithmName hashAlgorithm,
DSASignatureFormat signatureFormat)
{
Span<byte> tmp = stackalloc byte[HashBufferStackSize];
ReadOnlySpan<byte> hash = HashSpanToTmp(data, hashAlgorithm, tmp);
return VerifySignatureCore(hash, signature, signatureFormat);
}
/// <summary>
/// Verifies that a digital signature is valid for the provided hash.
/// </summary>
/// <param name="rgbHash">The signed hash.</param>
/// <param name="rgbSignature">The signature to verify.</param>
/// <param name="signatureFormat">The encoding format for <paramref name="rgbSignature"/>.</param>
/// <returns>
/// <see langword="true"/> if the digital signature is valid for the provided data; otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="rgbHash"/> or <paramref name="rgbSignature"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the verification operation.
/// </exception>
public bool VerifySignature(byte[] rgbHash!!, byte[] rgbSignature!!, DSASignatureFormat signatureFormat)
{
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return VerifySignatureCore(rgbHash, rgbSignature, signatureFormat);
}
public virtual bool VerifySignature(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature) =>
VerifySignature(hash.ToArray(), signature.ToArray());
/// <summary>
/// Verifies that a digital signature is valid for the provided hash.
/// </summary>
/// <param name="hash">The signed hash.</param>
/// <param name="signature">The signature to verify.</param>
/// <param name="signatureFormat">The encoding format for <paramref name="signature"/>.</param>
/// <returns>
/// <see langword="true"/> if the digital signature is valid for the provided data; otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
/// <exception cref="CryptographicException">
/// An error occurred in the verification operation.
/// </exception>
public bool VerifySignature(
ReadOnlySpan<byte> hash,
ReadOnlySpan<byte> signature,
DSASignatureFormat signatureFormat)
{
if (!signatureFormat.IsKnownValue())
throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
return VerifySignatureCore(hash, signature, signatureFormat);
}
/// <summary>
/// Verifies that a digital signature is valid for the provided hash.
/// </summary>
/// <param name="hash">The signed hash.</param>
/// <param name="signature">The signature to verify.</param>
/// <param name="signatureFormat">The encoding format for <paramref name="signature"/>.</param>
/// <returns>
/// <see langword="true"/> if the digital signature is valid for the provided data; otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="CryptographicException">
/// An error occurred in the verification operation.
/// </exception>
protected virtual bool VerifySignatureCore(
ReadOnlySpan<byte> hash,
ReadOnlySpan<byte> signature,
DSASignatureFormat signatureFormat)
{
// This method is expected to be overriden with better implementation
byte[]? sig = this.ConvertSignatureToIeeeP1363(signatureFormat, signature);
// If the signature failed normalization to IEEE P1363 then it
// obviously doesn't verify.
if (sig == null)
{
return false;
}
// The only available implementation here is abstract method, use it.
// Since it requires an exactly-sized array, skip pooled arrays.
return VerifySignature(hash, sig);
}
private ReadOnlySpan<byte> HashSpanToTmp(
ReadOnlySpan<byte> data,
HashAlgorithmName hashAlgorithm,
Span<byte> tmp)
{
Debug.Assert(tmp.Length == HashBufferStackSize);
if (TryHashData(data, tmp, hashAlgorithm, out int hashSize))
{
return tmp.Slice(0, hashSize);
}
// This is not expected, but a poor virtual implementation of TryHashData,
// or an exotic new algorithm, will hit this fallback.
return HashSpanToArray(data, hashAlgorithm);
}
private byte[] HashSpanToArray(ReadOnlySpan<byte> data, HashAlgorithmName hashAlgorithm)
{
// Use ArrayPool.Shared instead of CryptoPool because the array is passed out.
byte[] array = ArrayPool<byte>.Shared.Rent(data.Length);
bool returnArray = false;
try
{
data.CopyTo(array);
byte[] ret = HashData(array, 0, data.Length, hashAlgorithm);
returnArray = true;
return ret;
}
finally
{
Array.Clear(array, 0, data.Length);
if (returnArray)
{
ArrayPool<byte>.Shared.Return(array);
}
}
}
private static Exception DerivedClassMustOverride() =>
new NotImplementedException(SR.NotSupported_SubclassOverride);
public override bool TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
PbeParameters pbeParameters!!,
Span<byte> destination,
out int bytesWritten)
{
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
ReadOnlySpan<char>.Empty,
passwordBytes);
AsnWriter pkcs8PrivateKey = WritePkcs8();
AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8(
passwordBytes,
pkcs8PrivateKey,
pbeParameters);
return writer.TryEncode(destination, out bytesWritten);
}
public override bool TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
PbeParameters pbeParameters!!,
Span<byte> destination,
out int bytesWritten)
{
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
password,
ReadOnlySpan<byte>.Empty);
AsnWriter pkcs8PrivateKey = WritePkcs8();
AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8(
password,
pkcs8PrivateKey,
pbeParameters);
return writer.TryEncode(destination, out bytesWritten);
}
public override bool TryExportPkcs8PrivateKey(
Span<byte> destination,
out int bytesWritten)
{
AsnWriter writer = WritePkcs8();
return writer.TryEncode(destination, out bytesWritten);
}
public override bool TryExportSubjectPublicKeyInfo(
Span<byte> destination,
out int bytesWritten)
{
AsnWriter writer = WriteSubjectPublicKeyInfo();
return writer.TryEncode(destination, out bytesWritten);
}
private unsafe AsnWriter WritePkcs8()
{
DSAParameters dsaParameters = ExportParameters(true);
fixed (byte* privPin = dsaParameters.X)
{
try
{
return DSAKeyFormatHelper.WritePkcs8(dsaParameters);
}
finally
{
CryptographicOperations.ZeroMemory(dsaParameters.X);
}
}
}
private AsnWriter WriteSubjectPublicKeyInfo()
{
DSAParameters dsaParameters = ExportParameters(false);
return DSAKeyFormatHelper.WriteSubjectPublicKeyInfo(dsaParameters);
}
public override unsafe void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
ReadOnlySpan<byte> source,
out int bytesRead)
{
DSAKeyFormatHelper.ReadEncryptedPkcs8(
source,
passwordBytes,
out int localRead,
out DSAParameters ret);
fixed (byte* privPin = ret.X)
{
try
{
ImportParameters(ret);
}
finally
{
CryptographicOperations.ZeroMemory(ret.X);
}
}
bytesRead = localRead;
}
public override unsafe void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
ReadOnlySpan<byte> source,
out int bytesRead)
{
DSAKeyFormatHelper.ReadEncryptedPkcs8(
source,
password,
out int localRead,
out DSAParameters ret);
fixed (byte* privPin = ret.X)
{
try
{
ImportParameters(ret);
}
finally
{
CryptographicOperations.ZeroMemory(ret.X);
}
}
bytesRead = localRead;
}
public override unsafe void ImportPkcs8PrivateKey(
ReadOnlySpan<byte> source,
out int bytesRead)
{
DSAKeyFormatHelper.ReadPkcs8(
source,
out int localRead,
out DSAParameters key);
fixed (byte* privPin = key.X)
{
try
{
ImportParameters(key);
}
finally
{
CryptographicOperations.ZeroMemory(key.X);
}
}
bytesRead = localRead;
}
public override void ImportSubjectPublicKeyInfo(
ReadOnlySpan<byte> source,
out int bytesRead)
{
DSAKeyFormatHelper.ReadSubjectPublicKeyInfo(
source,
out int localRead,
out DSAParameters key);
ImportParameters(key);
bytesRead = localRead;
}
/// <summary>
/// Gets the largest size, in bytes, for a signature produced by this key in the indicated format.
/// </summary>
/// <param name="signatureFormat">The encoding format for a signature.</param>
/// <returns>
/// The largest size, in bytes, for a signature produced by this key in the indicated format.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="signatureFormat"/> is not a known format.
/// </exception>
public int GetMaxSignatureSize(DSASignatureFormat signatureFormat)
{
DSAParameters dsaParameters = ExportParameters(false);
int qLength = dsaParameters.Q!.Length;
switch (signatureFormat)
{
case DSASignatureFormat.IeeeP1363FixedFieldConcatenation:
return qLength * 2;
case DSASignatureFormat.Rfc3279DerSequence:
return AsymmetricAlgorithmHelpers.GetMaxDerSignatureSize(fieldSizeBits: qLength * 8);
default:
throw new ArgumentOutOfRangeException(nameof(signatureFormat));
}
}
/// <summary>
/// Imports an RFC 7468 PEM-encoded key, replacing the keys for this object.
/// </summary>
/// <param name="input">The PEM text of the key to import.</param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="input"/> does not contain a PEM-encoded key with a recognized label.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="input"/> contains multiple PEM-encoded keys with a recognized label.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="input"/> contains an encrypted PEM-encoded key.
/// </para>
/// </exception>
/// <remarks>
/// <para>
/// Unsupported or malformed PEM-encoded objects will be ignored. If multiple supported PEM labels
/// are found, an exception is raised to prevent importing a key when
/// the key is ambiguous.
/// </para>
/// <para>
/// This method supports the following PEM labels:
/// <list type="bullet">
/// <item><description>PUBLIC KEY</description></item>
/// <item><description>PRIVATE KEY</description></item>
/// </list>
/// </para>
/// </remarks>
public override void ImportFromPem(ReadOnlySpan<char> input)
{
// Implementation has been pushed down to AsymmetricAlgorithm. The
// override remains for compatibility.
base.ImportFromPem(input);
}
/// <summary>
/// Imports an encrypted RFC 7468 PEM-encoded private key, replacing the keys for this object.
/// </summary>
/// <param name="input">The PEM text of the encrypted key to import.</param>
/// <param name="password">
/// The password to use for decrypting the key material.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="input"/> does not contain a PEM-encoded key with a recognized label.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="input"/> contains multiple PEM-encoded keys with a recognized label.
/// </para>
/// </exception>
/// <exception cref="CryptographicException">
/// <para>
/// The password is incorrect.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The base-64 decoded contents of the PEM text from <paramref name="input" />
/// do not represent an ASN.1-BER-encoded PKCS#8 EncryptedPrivateKeyInfo structure.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The base-64 decoded contents of the PEM text from <paramref name="input" />
/// indicate the key is for an algorithm other than the algorithm
/// represented by this instance.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The base-64 decoded contents of the PEM text from <paramref name="input" />
/// represent the key in a format that is not supported.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The algorithm-specific key import failed.
/// </para>
/// </exception>
/// <remarks>
/// <para>
/// When the base-64 decoded contents of <paramref name="input" /> indicate an algorithm that uses PBKDF1
/// (Password-Based Key Derivation Function 1) or PBKDF2 (Password-Based Key Derivation Function 2),
/// the password is converted to bytes via the UTF-8 encoding.
/// </para>
/// <para>
/// Unsupported or malformed PEM-encoded objects will be ignored. If multiple supported PEM labels
/// are found, an exception is thrown to prevent importing a key when
/// the key is ambiguous.
/// </para>
/// <para>This method supports the <c>ENCRYPTED PRIVATE KEY</c> PEM label.</para>
/// </remarks>
public override void ImportFromEncryptedPem(ReadOnlySpan<char> input, ReadOnlySpan<char> password)
{
// Implementation has been pushed down to AsymmetricAlgorithm. The
// override remains for compatibility.
base.ImportFromEncryptedPem(input, password);
}
/// <summary>
/// Imports an encrypted RFC 7468 PEM-encoded private key, replacing the keys for this object.
/// </summary>
/// <param name="input">The PEM text of the encrypted key to import.</param>
/// <param name="passwordBytes">
/// The bytes to use as a password when decrypting the key material.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="input"/> does not contain a PEM-encoded key with a recognized label.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="input"/> contains multiple PEM-encoded keys with a recognized label.
/// </para>
/// </exception>
/// <exception cref="CryptographicException">
/// <para>
/// The password is incorrect.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The base-64 decoded contents of the PEM text from <paramref name="input" />
/// do not represent an ASN.1-BER-encoded PKCS#8 EncryptedPrivateKeyInfo structure.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The base-64 decoded contents of the PEM text from <paramref name="input" />
/// indicate the key is for an algorithm other than the algorithm
/// represented by this instance.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The base-64 decoded contents of the PEM text from <paramref name="input" />
/// represent the key in a format that is not supported.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The algorithm-specific key import failed.
/// </para>
/// </exception>
/// <remarks>
/// <para>
/// The password bytes are passed directly into the Key Derivation Function (KDF)
/// used by the algorithm indicated by <c>pbeParameters</c>. This enables compatibility
/// with other systems which use a text encoding other than UTF-8 when processing
/// passwords with PBKDF2 (Password-Based Key Derivation Function 2).
/// </para>
/// <para>
/// Unsupported or malformed PEM-encoded objects will be ignored. If multiple supported PEM labels
/// are found, an exception is thrown to prevent importing a key when
/// the key is ambiguous.
/// </para>
/// <para>This method supports the <c>ENCRYPTED PRIVATE KEY</c> PEM label.</para>
/// </remarks>
public override void ImportFromEncryptedPem(ReadOnlySpan<char> input, ReadOnlySpan<byte> passwordBytes)
{
// Implementation has been pushed down to AsymmetricAlgorithm. The
// override remains for compatibility.
base.ImportFromEncryptedPem(input, passwordBytes);
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Net.Mail/tests/Functional/MailMessageTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// MailMessageTest.cs - Unit Test Cases for System.Net.MailAddress.MailMessage
//
// Authors:
// John Luke ([email protected])
//
// (C) 2005, 2006 John Luke
//
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using Xunit;
namespace System.Net.Mail.Tests
{
public class MailMessageTest
{
MailMessage messageWithSubjectAndBody;
MailMessage emptyMessage;
public MailMessageTest()
{
messageWithSubjectAndBody = new MailMessage("[email protected]", "[email protected]");
messageWithSubjectAndBody.Subject = "the subject";
messageWithSubjectAndBody.Body = "hello";
messageWithSubjectAndBody.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("<html><body>hello</body></html>", null, "text/html"));
Attachment a = Attachment.CreateAttachmentFromString("blah blah", "AttachmentName");
messageWithSubjectAndBody.Attachments.Add(a);
emptyMessage = new MailMessage("[email protected]", "[email protected], [email protected]");
}
[Fact]
public void TestRecipients()
{
Assert.Equal(2, emptyMessage.To.Count);
Assert.Equal("[email protected]", emptyMessage.To[0].Address);
Assert.Equal("[email protected]", emptyMessage.To[1].Address);
}
[Fact]
public void TestForNullException()
{
Assert.Throws<ArgumentNullException>(() => new MailMessage("[email protected]", null));
Assert.Throws<ArgumentNullException>(() => new MailMessage(null, new MailAddress("[email protected]")));
Assert.Throws<ArgumentNullException>(() => new MailMessage(new MailAddress("[email protected]"), null));
Assert.Throws<ArgumentNullException>(() => new MailMessage(null, "[email protected]"));
}
[Fact]
public void AlternateViewTest()
{
Assert.Equal(1, messageWithSubjectAndBody.AlternateViews.Count);
AlternateView av = messageWithSubjectAndBody.AlternateViews[0];
Assert.Equal(0, av.LinkedResources.Count);
Assert.Equal("text/html; charset=us-ascii", av.ContentType.ToString());
}
[Fact]
public void AttachmentTest()
{
Assert.Equal(1, messageWithSubjectAndBody.Attachments.Count);
Attachment at = messageWithSubjectAndBody.Attachments[0];
Assert.Equal("text/plain", at.ContentType.MediaType);
Assert.Equal("AttachmentName", at.ContentType.Name);
Assert.Equal("AttachmentName", at.Name);
}
[Fact]
public void BodyTest()
{
Assert.Equal("hello", messageWithSubjectAndBody.Body);
}
[Fact]
public void BodyEncodingTest()
{
Assert.Equal(messageWithSubjectAndBody.BodyEncoding, Encoding.ASCII);
}
[Fact]
public void FromTest()
{
Assert.Equal("[email protected]", messageWithSubjectAndBody.From.Address);
}
[Fact]
public void IsBodyHtmlTest()
{
Assert.False(messageWithSubjectAndBody.IsBodyHtml);
}
[Fact]
public void PriorityTest()
{
Assert.Equal(MailPriority.Normal, messageWithSubjectAndBody.Priority);
}
[Fact]
public void SubjectTest()
{
Assert.Equal("the subject", messageWithSubjectAndBody.Subject);
}
[Fact]
public void ToTest()
{
Assert.Equal(1, messageWithSubjectAndBody.To.Count);
Assert.Equal("[email protected]", messageWithSubjectAndBody.To[0].Address);
messageWithSubjectAndBody = new MailMessage();
messageWithSubjectAndBody.To.Add("[email protected]");
messageWithSubjectAndBody.To.Add("[email protected]");
Assert.Equal(2, messageWithSubjectAndBody.To.Count);
Assert.Equal("[email protected]", messageWithSubjectAndBody.To[0].Address);
Assert.Equal("[email protected]", messageWithSubjectAndBody.To[1].Address);
}
[Fact]
public void BodyAndEncodingTest()
{
MailMessage msg = new MailMessage("[email protected]", "[email protected]");
Assert.Null(msg.BodyEncoding);
msg.Body = "test";
Assert.Equal(Encoding.ASCII, msg.BodyEncoding);
msg.Body = "test\u3067\u3059";
Assert.Equal(Encoding.ASCII, msg.BodyEncoding);
msg.BodyEncoding = null;
msg.Body = "test\u3067\u3059";
Assert.Equal(Encoding.UTF8.CodePage, msg.BodyEncoding.CodePage);
}
[Fact]
public void SubjectAndEncodingTest()
{
MailMessage msg = new MailMessage("[email protected]", "[email protected]");
Assert.Null(msg.SubjectEncoding);
msg.Subject = "test";
Assert.Null(msg.SubjectEncoding);
msg.Subject = "test\u3067\u3059";
Assert.Equal(Encoding.UTF8.CodePage, msg.SubjectEncoding.CodePage);
msg.SubjectEncoding = null;
msg.Subject = "test\u3067\u3059";
Assert.Equal(Encoding.UTF8.CodePage, msg.SubjectEncoding.CodePage);
}
[Fact]
[SkipOnPlatform(TestPlatforms.Browser, "Not passing as internal System.Net.Mail.MailWriter stripped from build")]
public void SendMailMessageTest()
{
string expected = @"X-Sender: [email protected]
X-Receiver: [email protected]
MIME-Version: 1.0
From: [email protected]
To: [email protected]
Date: DATE
Subject: the subject
Content-Type: multipart/mixed;
boundary=--boundary_1_GUID
----boundary_1_GUID
Content-Type: multipart/alternative;
boundary=--boundary_0_GUID
----boundary_0_GUID
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable
hello
----boundary_0_GUID
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: quoted-printable
<html><body>hello</body></html>
----boundary_0_GUID--
----boundary_1_GUID
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment
Content-Transfer-Encoding: quoted-printable
blah blah
----boundary_1_GUID--
";
expected = expected.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n");
string sent = DecodeSentMailMessage(messageWithSubjectAndBody).Raw;
sent = Regex.Replace(sent, "Date:.*?\r\n", "Date: DATE\r\n");
sent = Regex.Replace(sent, @"_.{8}-.{4}-.{4}-.{4}-.{12}", "_GUID");
// name and charset can appear in different order
Assert.Contains("; name=AttachmentName", sent);
sent = sent.Replace("; name=AttachmentName", string.Empty);
Assert.Equal(expected, sent);
}
[Fact]
[SkipOnPlatform(TestPlatforms.Browser, "Not passing as internal System.Net.Mail.MailWriter stripped from build")]
public void SentSpecialLengthMailAttachment_Base64Decode_Success()
{
// The special length follows pattern: (3N - 1) * 0x4400 + 1
// This length will trigger WriteState.Padding = 2 & count = 1 (byte to write)
// The smallest number to match the pattern is 34817.
int specialLength = 34817;
string stringLength34817 = new string('A', specialLength - 1) + 'Z';
byte[] toBytes = Encoding.ASCII.GetBytes(stringLength34817);
using (var tempFile = TempFile.Create(toBytes))
{
var message = new MailMessage("[email protected]", "[email protected]", "testSubject", "testBody");
message.Attachments.Add(new Attachment(tempFile.Path));
string attachment = DecodeSentMailMessage(message).Attachment;
string decodedAttachment = Encoding.UTF8.GetString(Convert.FromBase64String(attachment));
// Make sure last byte is not encoded twice.
Assert.Equal(specialLength, decodedAttachment.Length);
Assert.Equal("AAAAAAAAAAAAAAAAZ", decodedAttachment.Substring(34800));
}
}
private static (string Raw, string Attachment) DecodeSentMailMessage(MailMessage mail)
{
// Create a MIME message that would be sent using System.Net.Mail.
var stream = new MemoryStream();
var mailWriterType = mail.GetType().Assembly.GetType("System.Net.Mail.MailWriter");
var mailWriter = Activator.CreateInstance(
type: mailWriterType,
bindingAttr: BindingFlags.Instance | BindingFlags.NonPublic,
binder: null,
args: new object[] { stream, true }, // true to encode message for transport
culture: null,
activationAttributes: null);
// Send the message.
mail.GetType().InvokeMember(
name: "Send",
invokeAttr: BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod,
binder: null,
target: mail,
args: new object[] { mailWriter, true, true });
// Decode contents.
string result = Encoding.UTF8.GetString(stream.ToArray());
string attachment = result.Split(new[] { "attachment" }, StringSplitOptions.None)[1].Trim().Split('-')[0].Trim();
return (result, attachment);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// MailMessageTest.cs - Unit Test Cases for System.Net.MailAddress.MailMessage
//
// Authors:
// John Luke ([email protected])
//
// (C) 2005, 2006 John Luke
//
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using Xunit;
namespace System.Net.Mail.Tests
{
public class MailMessageTest
{
MailMessage messageWithSubjectAndBody;
MailMessage emptyMessage;
public MailMessageTest()
{
messageWithSubjectAndBody = new MailMessage("[email protected]", "[email protected]");
messageWithSubjectAndBody.Subject = "the subject";
messageWithSubjectAndBody.Body = "hello";
messageWithSubjectAndBody.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("<html><body>hello</body></html>", null, "text/html"));
Attachment a = Attachment.CreateAttachmentFromString("blah blah", "AttachmentName");
messageWithSubjectAndBody.Attachments.Add(a);
emptyMessage = new MailMessage("[email protected]", "[email protected], [email protected]");
}
[Fact]
public void TestRecipients()
{
Assert.Equal(2, emptyMessage.To.Count);
Assert.Equal("[email protected]", emptyMessage.To[0].Address);
Assert.Equal("[email protected]", emptyMessage.To[1].Address);
}
[Fact]
public void TestForNullException()
{
Assert.Throws<ArgumentNullException>(() => new MailMessage("[email protected]", null));
Assert.Throws<ArgumentNullException>(() => new MailMessage(null, new MailAddress("[email protected]")));
Assert.Throws<ArgumentNullException>(() => new MailMessage(new MailAddress("[email protected]"), null));
Assert.Throws<ArgumentNullException>(() => new MailMessage(null, "[email protected]"));
}
[Fact]
public void AlternateViewTest()
{
Assert.Equal(1, messageWithSubjectAndBody.AlternateViews.Count);
AlternateView av = messageWithSubjectAndBody.AlternateViews[0];
Assert.Equal(0, av.LinkedResources.Count);
Assert.Equal("text/html; charset=us-ascii", av.ContentType.ToString());
}
[Fact]
public void AttachmentTest()
{
Assert.Equal(1, messageWithSubjectAndBody.Attachments.Count);
Attachment at = messageWithSubjectAndBody.Attachments[0];
Assert.Equal("text/plain", at.ContentType.MediaType);
Assert.Equal("AttachmentName", at.ContentType.Name);
Assert.Equal("AttachmentName", at.Name);
}
[Fact]
public void BodyTest()
{
Assert.Equal("hello", messageWithSubjectAndBody.Body);
}
[Fact]
public void BodyEncodingTest()
{
Assert.Equal(messageWithSubjectAndBody.BodyEncoding, Encoding.ASCII);
}
[Fact]
public void FromTest()
{
Assert.Equal("[email protected]", messageWithSubjectAndBody.From.Address);
}
[Fact]
public void IsBodyHtmlTest()
{
Assert.False(messageWithSubjectAndBody.IsBodyHtml);
}
[Fact]
public void PriorityTest()
{
Assert.Equal(MailPriority.Normal, messageWithSubjectAndBody.Priority);
}
[Fact]
public void SubjectTest()
{
Assert.Equal("the subject", messageWithSubjectAndBody.Subject);
}
[Fact]
public void ToTest()
{
Assert.Equal(1, messageWithSubjectAndBody.To.Count);
Assert.Equal("[email protected]", messageWithSubjectAndBody.To[0].Address);
messageWithSubjectAndBody = new MailMessage();
messageWithSubjectAndBody.To.Add("[email protected]");
messageWithSubjectAndBody.To.Add("[email protected]");
Assert.Equal(2, messageWithSubjectAndBody.To.Count);
Assert.Equal("[email protected]", messageWithSubjectAndBody.To[0].Address);
Assert.Equal("[email protected]", messageWithSubjectAndBody.To[1].Address);
}
[Fact]
public void BodyAndEncodingTest()
{
MailMessage msg = new MailMessage("[email protected]", "[email protected]");
Assert.Null(msg.BodyEncoding);
msg.Body = "test";
Assert.Equal(Encoding.ASCII, msg.BodyEncoding);
msg.Body = "test\u3067\u3059";
Assert.Equal(Encoding.ASCII, msg.BodyEncoding);
msg.BodyEncoding = null;
msg.Body = "test\u3067\u3059";
Assert.Equal(Encoding.UTF8.CodePage, msg.BodyEncoding.CodePage);
}
[Fact]
public void SubjectAndEncodingTest()
{
MailMessage msg = new MailMessage("[email protected]", "[email protected]");
Assert.Null(msg.SubjectEncoding);
msg.Subject = "test";
Assert.Null(msg.SubjectEncoding);
msg.Subject = "test\u3067\u3059";
Assert.Equal(Encoding.UTF8.CodePage, msg.SubjectEncoding.CodePage);
msg.SubjectEncoding = null;
msg.Subject = "test\u3067\u3059";
Assert.Equal(Encoding.UTF8.CodePage, msg.SubjectEncoding.CodePage);
}
[Fact]
[SkipOnPlatform(TestPlatforms.Browser, "Not passing as internal System.Net.Mail.MailWriter stripped from build")]
public void SendMailMessageTest()
{
string expected = @"X-Sender: [email protected]
X-Receiver: [email protected]
MIME-Version: 1.0
From: [email protected]
To: [email protected]
Date: DATE
Subject: the subject
Content-Type: multipart/mixed;
boundary=--boundary_1_GUID
----boundary_1_GUID
Content-Type: multipart/alternative;
boundary=--boundary_0_GUID
----boundary_0_GUID
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable
hello
----boundary_0_GUID
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: quoted-printable
<html><body>hello</body></html>
----boundary_0_GUID--
----boundary_1_GUID
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment
Content-Transfer-Encoding: quoted-printable
blah blah
----boundary_1_GUID--
";
expected = expected.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n");
string sent = DecodeSentMailMessage(messageWithSubjectAndBody).Raw;
sent = Regex.Replace(sent, "Date:.*?\r\n", "Date: DATE\r\n");
sent = Regex.Replace(sent, @"_.{8}-.{4}-.{4}-.{4}-.{12}", "_GUID");
// name and charset can appear in different order
Assert.Contains("; name=AttachmentName", sent);
sent = sent.Replace("; name=AttachmentName", string.Empty);
Assert.Equal(expected, sent);
}
[Fact]
[SkipOnPlatform(TestPlatforms.Browser, "Not passing as internal System.Net.Mail.MailWriter stripped from build")]
public void SentSpecialLengthMailAttachment_Base64Decode_Success()
{
// The special length follows pattern: (3N - 1) * 0x4400 + 1
// This length will trigger WriteState.Padding = 2 & count = 1 (byte to write)
// The smallest number to match the pattern is 34817.
int specialLength = 34817;
string stringLength34817 = new string('A', specialLength - 1) + 'Z';
byte[] toBytes = Encoding.ASCII.GetBytes(stringLength34817);
using (var tempFile = TempFile.Create(toBytes))
{
var message = new MailMessage("[email protected]", "[email protected]", "testSubject", "testBody");
message.Attachments.Add(new Attachment(tempFile.Path));
string attachment = DecodeSentMailMessage(message).Attachment;
string decodedAttachment = Encoding.UTF8.GetString(Convert.FromBase64String(attachment));
// Make sure last byte is not encoded twice.
Assert.Equal(specialLength, decodedAttachment.Length);
Assert.Equal("AAAAAAAAAAAAAAAAZ", decodedAttachment.Substring(34800));
}
}
private static (string Raw, string Attachment) DecodeSentMailMessage(MailMessage mail)
{
// Create a MIME message that would be sent using System.Net.Mail.
var stream = new MemoryStream();
var mailWriterType = mail.GetType().Assembly.GetType("System.Net.Mail.MailWriter");
var mailWriter = Activator.CreateInstance(
type: mailWriterType,
bindingAttr: BindingFlags.Instance | BindingFlags.NonPublic,
binder: null,
args: new object[] { stream, true }, // true to encode message for transport
culture: null,
activationAttributes: null);
// Send the message.
mail.GetType().InvokeMember(
name: "Send",
invokeAttr: BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod,
binder: null,
target: mail,
args: new object[] { mailWriter, true, true });
// Decode contents.
string result = Encoding.UTF8.GetString(stream.ToArray());
string attachment = result.Split(new[] { "attachment" }, StringSplitOptions.None)[1].Trim().Split('-')[0].Trim();
return (result, attachment);
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/Directed/BitTest/BitTest.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>None</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).cs" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>None</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/mono/mono/tests/bug-666008.cs | using System;
abstract class Foo<T>
{
public virtual int OnReloaded () {
Console.WriteLine ("HIT!");
return 0;
}
}
class Bar<T> : Foo<T>
{
public int DoIt (Func<int> a) {
return a ();
}
public override int OnReloaded () {
return DoIt (base.OnReloaded);
}
}
public class Tests
{
public static int Main (String[] args) {
var b = new Bar<string> ();
return b.OnReloaded ();
}
}
| using System;
abstract class Foo<T>
{
public virtual int OnReloaded () {
Console.WriteLine ("HIT!");
return 0;
}
}
class Bar<T> : Foo<T>
{
public int DoIt (Func<int> a) {
return a ();
}
public override int OnReloaded () {
return DoIt (base.OnReloaded);
}
}
public class Tests
{
public static int Main (String[] args) {
var b = new Bar<string> ();
return b.OnReloaded ();
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/ConvertToUInt64RoundToEven.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 ConvertToUInt64RoundToEven_Vector128_Double()
{
var test = new SimpleUnaryOpTest__ConvertToUInt64RoundToEven_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__ConvertToUInt64RoundToEven_Vector128_Double
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, UInt64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>();
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__ConvertToUInt64RoundToEven_Vector128_Double testClass)
{
var result = AdvSimd.Arm64.ConvertToUInt64RoundToEven(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__ConvertToUInt64RoundToEven_Vector128_Double testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
{
var result = AdvSimd.Arm64.ConvertToUInt64RoundToEven(
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<UInt64>>() / sizeof(UInt64);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Vector128<Double> _clsVar1;
private Vector128<Double> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__ConvertToUInt64RoundToEven_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__ConvertToUInt64RoundToEven_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 UInt64[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.ConvertToUInt64RoundToEven(
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.ConvertToUInt64RoundToEven(
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.ConvertToUInt64RoundToEven), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(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.ConvertToUInt64RoundToEven), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.ConvertToUInt64RoundToEven(
_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.ConvertToUInt64RoundToEven(
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.ConvertToUInt64RoundToEven(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.ConvertToUInt64RoundToEven(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__ConvertToUInt64RoundToEven_Vector128_Double();
var result = AdvSimd.Arm64.ConvertToUInt64RoundToEven(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__ConvertToUInt64RoundToEven_Vector128_Double();
fixed (Vector128<Double>* pFld1 = &test._fld1)
{
var result = AdvSimd.Arm64.ConvertToUInt64RoundToEven(
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.ConvertToUInt64RoundToEven(_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.ConvertToUInt64RoundToEven(
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.ConvertToUInt64RoundToEven(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.ConvertToUInt64RoundToEven(
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];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
UInt64[] outArray = new UInt64[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<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Double[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ConvertToUInt64RoundToEven(firstOp[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ConvertToUInt64RoundToEven)}<UInt64>(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 ConvertToUInt64RoundToEven_Vector128_Double()
{
var test = new SimpleUnaryOpTest__ConvertToUInt64RoundToEven_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__ConvertToUInt64RoundToEven_Vector128_Double
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, UInt64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>();
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__ConvertToUInt64RoundToEven_Vector128_Double testClass)
{
var result = AdvSimd.Arm64.ConvertToUInt64RoundToEven(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__ConvertToUInt64RoundToEven_Vector128_Double testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
{
var result = AdvSimd.Arm64.ConvertToUInt64RoundToEven(
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<UInt64>>() / sizeof(UInt64);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Vector128<Double> _clsVar1;
private Vector128<Double> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__ConvertToUInt64RoundToEven_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__ConvertToUInt64RoundToEven_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 UInt64[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.ConvertToUInt64RoundToEven(
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.ConvertToUInt64RoundToEven(
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.ConvertToUInt64RoundToEven), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(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.ConvertToUInt64RoundToEven), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.ConvertToUInt64RoundToEven(
_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.ConvertToUInt64RoundToEven(
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.ConvertToUInt64RoundToEven(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.ConvertToUInt64RoundToEven(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__ConvertToUInt64RoundToEven_Vector128_Double();
var result = AdvSimd.Arm64.ConvertToUInt64RoundToEven(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__ConvertToUInt64RoundToEven_Vector128_Double();
fixed (Vector128<Double>* pFld1 = &test._fld1)
{
var result = AdvSimd.Arm64.ConvertToUInt64RoundToEven(
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.ConvertToUInt64RoundToEven(_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.ConvertToUInt64RoundToEven(
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.ConvertToUInt64RoundToEven(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.ConvertToUInt64RoundToEven(
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];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
UInt64[] outArray = new UInt64[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<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Double[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ConvertToUInt64RoundToEven(firstOp[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ConvertToUInt64RoundToEven)}<UInt64>(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 | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutFieldDesc.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using Internal.TypeSystem;
using Internal.NativeFormat;
namespace Internal.Runtime.TypeLoader
{
/// <summary>
/// Represents a field defined in native layout data, but without metadata
/// </summary>
internal class NativeLayoutFieldDesc : FieldDesc
{
private DefType _owningType;
private TypeDesc _fieldType;
private FieldStorage _fieldStorage;
public NativeLayoutFieldDesc(DefType owningType, TypeDesc fieldType, FieldStorage fieldStorage)
{
_owningType = owningType;
_fieldType = fieldType;
_fieldStorage = fieldStorage;
}
public override TypeSystemContext Context
{
get
{
return _owningType.Context;
}
}
public override TypeDesc FieldType
{
get
{
return _fieldType;
}
}
public override bool HasRva
{
get
{
throw NotImplemented.ByDesign;
}
}
public override bool IsInitOnly
{
get
{
throw NotImplemented.ByDesign;
}
}
public override bool IsLiteral
{
get
{
return false;
}
}
public override bool IsStatic
{
get
{
return _fieldStorage != FieldStorage.Instance;
}
}
public override bool IsThreadStatic
{
get
{
return _fieldStorage == FieldStorage.TLSStatic;
}
}
internal FieldStorage FieldStorage
{
get
{
return _fieldStorage;
}
}
public override DefType OwningType
{
get
{
return _owningType;
}
}
public override bool HasCustomAttribute(string attributeNamespace, string attributeName)
{
throw NotImplemented.ByDesign;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using Internal.TypeSystem;
using Internal.NativeFormat;
namespace Internal.Runtime.TypeLoader
{
/// <summary>
/// Represents a field defined in native layout data, but without metadata
/// </summary>
internal class NativeLayoutFieldDesc : FieldDesc
{
private DefType _owningType;
private TypeDesc _fieldType;
private FieldStorage _fieldStorage;
public NativeLayoutFieldDesc(DefType owningType, TypeDesc fieldType, FieldStorage fieldStorage)
{
_owningType = owningType;
_fieldType = fieldType;
_fieldStorage = fieldStorage;
}
public override TypeSystemContext Context
{
get
{
return _owningType.Context;
}
}
public override TypeDesc FieldType
{
get
{
return _fieldType;
}
}
public override bool HasRva
{
get
{
throw NotImplemented.ByDesign;
}
}
public override bool IsInitOnly
{
get
{
throw NotImplemented.ByDesign;
}
}
public override bool IsLiteral
{
get
{
return false;
}
}
public override bool IsStatic
{
get
{
return _fieldStorage != FieldStorage.Instance;
}
}
public override bool IsThreadStatic
{
get
{
return _fieldStorage == FieldStorage.TLSStatic;
}
}
internal FieldStorage FieldStorage
{
get
{
return _fieldStorage;
}
}
public override DefType OwningType
{
get
{
return _owningType;
}
}
public override bool HasCustomAttribute(string attributeNamespace, string attributeName)
{
throw NotImplemented.ByDesign;
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/baseservices/threading/generics/WaitCallback/thread23.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;
interface IGen<T>
{
void Target<U>(object p);
T Dummy(T t);
}
struct GenInt : IGen<int>
{
public int Dummy(int t) { return t; }
public void Target<U>(object p)
{
//dummy line to avoid warnings
Test_thread23.Eval(typeof(U)!=p.GetType());
ManualResetEvent evt = (ManualResetEvent) p;
Interlocked.Increment(ref Test_thread23.Xcounter);
evt.Set();
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent[] evts = new ManualResetEvent[Test_thread23.nThreads];
WaitHandle[] hdls = new WaitHandle[Test_thread23.nThreads];
for (int i=0; i<Test_thread23.nThreads; i++)
{
evts[i] = new ManualResetEvent(false);
hdls[i] = (WaitHandle) evts[i];
}
IGen<int> obj = new GenInt();
for (int i = 0; i <Test_thread23.nThreads; i++)
{
WaitCallback cb = new WaitCallback(obj.Target<U>);
ThreadPool.QueueUserWorkItem(cb,evts[i]);
}
WaitHandle.WaitAll(hdls);
Test_thread23.Eval(Test_thread23.Xcounter==Test_thread23.nThreads);
Test_thread23.Xcounter = 0;
}
}
struct GenDouble : IGen<double>
{
public double Dummy(double t) { return t; }
public void Target<U>(object p)
{
//dummy line to avoid warnings
Test_thread23.Eval(typeof(U)!=p.GetType());
ManualResetEvent evt = (ManualResetEvent) p;
Interlocked.Increment(ref Test_thread23.Xcounter);
evt.Set();
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent[] evts = new ManualResetEvent[Test_thread23.nThreads];
WaitHandle[] hdls = new WaitHandle[Test_thread23.nThreads];
for (int i=0; i<Test_thread23.nThreads; i++)
{
evts[i] = new ManualResetEvent(false);
hdls[i] = (WaitHandle) evts[i];
}
IGen<double> obj = new GenDouble();
for (int i = 0; i <Test_thread23.nThreads; i++)
{
WaitCallback cb = new WaitCallback(obj.Target<U>);
ThreadPool.QueueUserWorkItem(cb,evts[i]);
}
WaitHandle.WaitAll(hdls);
Test_thread23.Eval(Test_thread23.Xcounter==Test_thread23.nThreads);
Test_thread23.Xcounter = 0;
}
}
struct GenString : IGen<string>
{
public string Dummy(string t) { return t; }
public void Target<U>(object p)
{
//dummy line to avoid warnings
Test_thread23.Eval(typeof(U)!=p.GetType());
ManualResetEvent evt = (ManualResetEvent) p;
Interlocked.Increment(ref Test_thread23.Xcounter);
evt.Set();
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent[] evts = new ManualResetEvent[Test_thread23.nThreads];
WaitHandle[] hdls = new WaitHandle[Test_thread23.nThreads];
for (int i=0; i<Test_thread23.nThreads; i++)
{
evts[i] = new ManualResetEvent(false);
hdls[i] = (WaitHandle) evts[i];
}
IGen<string> obj = new GenString();
for (int i = 0; i <Test_thread23.nThreads; i++)
{
WaitCallback cb = new WaitCallback(obj.Target<U>);
ThreadPool.QueueUserWorkItem(cb,evts[i]);
}
WaitHandle.WaitAll(hdls);
Test_thread23.Eval(Test_thread23.Xcounter==Test_thread23.nThreads);
Test_thread23.Xcounter = 0;
}
}
struct GenObject : IGen<object>
{
public object Dummy(object t) { return t; }
public void Target<U>(object p)
{
//dummy line to avoid warnings
Test_thread23.Eval(typeof(U)!=p.GetType());
ManualResetEvent evt = (ManualResetEvent) p;
Interlocked.Increment(ref Test_thread23.Xcounter);
evt.Set();
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent[] evts = new ManualResetEvent[Test_thread23.nThreads];
WaitHandle[] hdls = new WaitHandle[Test_thread23.nThreads];
for (int i=0; i<Test_thread23.nThreads; i++)
{
evts[i] = new ManualResetEvent(false);
hdls[i] = (WaitHandle) evts[i];
}
IGen<object> obj = new GenObject();
for (int i = 0; i <Test_thread23.nThreads; i++)
{
WaitCallback cb = new WaitCallback(obj.Target<U>);
ThreadPool.QueueUserWorkItem(cb,evts[i]);
}
WaitHandle.WaitAll(hdls);
Test_thread23.Eval(Test_thread23.Xcounter==Test_thread23.nThreads);
Test_thread23.Xcounter = 0;
}
}
struct GenGuid : IGen<Guid>
{
public Guid Dummy(Guid t) { return t; }
public void Target<U>(object p)
{
//dummy line to avoid warnings
Test_thread23.Eval(typeof(U)!=p.GetType());
ManualResetEvent evt = (ManualResetEvent) p;
Interlocked.Increment(ref Test_thread23.Xcounter);
evt.Set();
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent[] evts = new ManualResetEvent[Test_thread23.nThreads];
WaitHandle[] hdls = new WaitHandle[Test_thread23.nThreads];
for (int i=0; i<Test_thread23.nThreads; i++)
{
evts[i] = new ManualResetEvent(false);
hdls[i] = (WaitHandle) evts[i];
}
IGen<Guid> obj = new GenGuid();
for (int i = 0; i <Test_thread23.nThreads; i++)
{
WaitCallback cb = new WaitCallback(obj.Target<U>);
ThreadPool.QueueUserWorkItem(cb,evts[i]);
}
WaitHandle.WaitAll(hdls);
Test_thread23.Eval(Test_thread23.Xcounter==Test_thread23.nThreads);
Test_thread23.Xcounter = 0;
}
}
public class Test_thread23
{
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()
{
GenInt.ThreadPoolTest<int>();
GenDouble.ThreadPoolTest<int>();
GenString.ThreadPoolTest<int>();
GenObject.ThreadPoolTest<int>();
GenGuid.ThreadPoolTest<int>();
GenInt.ThreadPoolTest<double>();
GenDouble.ThreadPoolTest<double>();
GenString.ThreadPoolTest<double>();
GenObject.ThreadPoolTest<double>();
GenGuid.ThreadPoolTest<double>();
GenInt.ThreadPoolTest<string>();
GenDouble.ThreadPoolTest<string>();
GenString.ThreadPoolTest<string>();
GenObject.ThreadPoolTest<string>();
GenGuid.ThreadPoolTest<string>();
GenInt.ThreadPoolTest<object>();
GenDouble.ThreadPoolTest<object>();
GenString.ThreadPoolTest<object>();
GenObject.ThreadPoolTest<object>();
GenGuid.ThreadPoolTest<object>();
GenInt.ThreadPoolTest<Guid>();
GenDouble.ThreadPoolTest<Guid>();
GenString.ThreadPoolTest<Guid>();
GenObject.ThreadPoolTest<Guid>();
GenGuid.ThreadPoolTest<Guid>();
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;
interface IGen<T>
{
void Target<U>(object p);
T Dummy(T t);
}
struct GenInt : IGen<int>
{
public int Dummy(int t) { return t; }
public void Target<U>(object p)
{
//dummy line to avoid warnings
Test_thread23.Eval(typeof(U)!=p.GetType());
ManualResetEvent evt = (ManualResetEvent) p;
Interlocked.Increment(ref Test_thread23.Xcounter);
evt.Set();
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent[] evts = new ManualResetEvent[Test_thread23.nThreads];
WaitHandle[] hdls = new WaitHandle[Test_thread23.nThreads];
for (int i=0; i<Test_thread23.nThreads; i++)
{
evts[i] = new ManualResetEvent(false);
hdls[i] = (WaitHandle) evts[i];
}
IGen<int> obj = new GenInt();
for (int i = 0; i <Test_thread23.nThreads; i++)
{
WaitCallback cb = new WaitCallback(obj.Target<U>);
ThreadPool.QueueUserWorkItem(cb,evts[i]);
}
WaitHandle.WaitAll(hdls);
Test_thread23.Eval(Test_thread23.Xcounter==Test_thread23.nThreads);
Test_thread23.Xcounter = 0;
}
}
struct GenDouble : IGen<double>
{
public double Dummy(double t) { return t; }
public void Target<U>(object p)
{
//dummy line to avoid warnings
Test_thread23.Eval(typeof(U)!=p.GetType());
ManualResetEvent evt = (ManualResetEvent) p;
Interlocked.Increment(ref Test_thread23.Xcounter);
evt.Set();
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent[] evts = new ManualResetEvent[Test_thread23.nThreads];
WaitHandle[] hdls = new WaitHandle[Test_thread23.nThreads];
for (int i=0; i<Test_thread23.nThreads; i++)
{
evts[i] = new ManualResetEvent(false);
hdls[i] = (WaitHandle) evts[i];
}
IGen<double> obj = new GenDouble();
for (int i = 0; i <Test_thread23.nThreads; i++)
{
WaitCallback cb = new WaitCallback(obj.Target<U>);
ThreadPool.QueueUserWorkItem(cb,evts[i]);
}
WaitHandle.WaitAll(hdls);
Test_thread23.Eval(Test_thread23.Xcounter==Test_thread23.nThreads);
Test_thread23.Xcounter = 0;
}
}
struct GenString : IGen<string>
{
public string Dummy(string t) { return t; }
public void Target<U>(object p)
{
//dummy line to avoid warnings
Test_thread23.Eval(typeof(U)!=p.GetType());
ManualResetEvent evt = (ManualResetEvent) p;
Interlocked.Increment(ref Test_thread23.Xcounter);
evt.Set();
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent[] evts = new ManualResetEvent[Test_thread23.nThreads];
WaitHandle[] hdls = new WaitHandle[Test_thread23.nThreads];
for (int i=0; i<Test_thread23.nThreads; i++)
{
evts[i] = new ManualResetEvent(false);
hdls[i] = (WaitHandle) evts[i];
}
IGen<string> obj = new GenString();
for (int i = 0; i <Test_thread23.nThreads; i++)
{
WaitCallback cb = new WaitCallback(obj.Target<U>);
ThreadPool.QueueUserWorkItem(cb,evts[i]);
}
WaitHandle.WaitAll(hdls);
Test_thread23.Eval(Test_thread23.Xcounter==Test_thread23.nThreads);
Test_thread23.Xcounter = 0;
}
}
struct GenObject : IGen<object>
{
public object Dummy(object t) { return t; }
public void Target<U>(object p)
{
//dummy line to avoid warnings
Test_thread23.Eval(typeof(U)!=p.GetType());
ManualResetEvent evt = (ManualResetEvent) p;
Interlocked.Increment(ref Test_thread23.Xcounter);
evt.Set();
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent[] evts = new ManualResetEvent[Test_thread23.nThreads];
WaitHandle[] hdls = new WaitHandle[Test_thread23.nThreads];
for (int i=0; i<Test_thread23.nThreads; i++)
{
evts[i] = new ManualResetEvent(false);
hdls[i] = (WaitHandle) evts[i];
}
IGen<object> obj = new GenObject();
for (int i = 0; i <Test_thread23.nThreads; i++)
{
WaitCallback cb = new WaitCallback(obj.Target<U>);
ThreadPool.QueueUserWorkItem(cb,evts[i]);
}
WaitHandle.WaitAll(hdls);
Test_thread23.Eval(Test_thread23.Xcounter==Test_thread23.nThreads);
Test_thread23.Xcounter = 0;
}
}
struct GenGuid : IGen<Guid>
{
public Guid Dummy(Guid t) { return t; }
public void Target<U>(object p)
{
//dummy line to avoid warnings
Test_thread23.Eval(typeof(U)!=p.GetType());
ManualResetEvent evt = (ManualResetEvent) p;
Interlocked.Increment(ref Test_thread23.Xcounter);
evt.Set();
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent[] evts = new ManualResetEvent[Test_thread23.nThreads];
WaitHandle[] hdls = new WaitHandle[Test_thread23.nThreads];
for (int i=0; i<Test_thread23.nThreads; i++)
{
evts[i] = new ManualResetEvent(false);
hdls[i] = (WaitHandle) evts[i];
}
IGen<Guid> obj = new GenGuid();
for (int i = 0; i <Test_thread23.nThreads; i++)
{
WaitCallback cb = new WaitCallback(obj.Target<U>);
ThreadPool.QueueUserWorkItem(cb,evts[i]);
}
WaitHandle.WaitAll(hdls);
Test_thread23.Eval(Test_thread23.Xcounter==Test_thread23.nThreads);
Test_thread23.Xcounter = 0;
}
}
public class Test_thread23
{
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()
{
GenInt.ThreadPoolTest<int>();
GenDouble.ThreadPoolTest<int>();
GenString.ThreadPoolTest<int>();
GenObject.ThreadPoolTest<int>();
GenGuid.ThreadPoolTest<int>();
GenInt.ThreadPoolTest<double>();
GenDouble.ThreadPoolTest<double>();
GenString.ThreadPoolTest<double>();
GenObject.ThreadPoolTest<double>();
GenGuid.ThreadPoolTest<double>();
GenInt.ThreadPoolTest<string>();
GenDouble.ThreadPoolTest<string>();
GenString.ThreadPoolTest<string>();
GenObject.ThreadPoolTest<string>();
GenGuid.ThreadPoolTest<string>();
GenInt.ThreadPoolTest<object>();
GenDouble.ThreadPoolTest<object>();
GenString.ThreadPoolTest<object>();
GenObject.ThreadPoolTest<object>();
GenGuid.ThreadPoolTest<object>();
GenInt.ThreadPoolTest<Guid>();
GenDouble.ThreadPoolTest<Guid>();
GenString.ThreadPoolTest<Guid>();
GenObject.ThreadPoolTest<Guid>();
GenGuid.ThreadPoolTest<Guid>();
if (result)
{
Console.WriteLine("Test Passed");
return 100;
}
else
{
Console.WriteLine("Test Failed");
return 1;
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/Performance/CodeQuality/Benchstones/MDBenchI/MDMidpoint/MDMidpoint.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 Benchstone.MDBenchI
{
public static class MDMidpoint
{
#if DEBUG
public const int Iterations = 1;
#else
public const int Iterations = 70000;
#endif
static int Inner(ref int x, ref int y, ref int z) {
int mid;
if (x < y) {
if (y < z) {
mid = y;
}
else {
if (x < z) {
mid = z;
}
else {
mid = x;
}
}
}
else {
if (x < z) {
mid = x;
}
else {
if (y < z) {
mid = z;
}
else {
mid = y;
}
}
}
return (mid);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool Bench() {
int[,] a = new int[2001, 4];
int[] mid = new int[2001];
int j = 99999;
for (int i = 1; i <= 2000; i++) {
a[i,1] = j & 32767;
a[i,2] = (j + 11111) & 32767;
a[i,3] = (j + 22222) & 32767;
j = j + 33333;
}
for (int k = 1; k <= Iterations; k++) {
for (int l = 1; l <= 2000; l++) {
mid[l] = Inner(ref a[l,1], ref a[l,2], ref a[l,3]);
}
}
return (mid[2000] == 17018);
}
static bool TestBase() {
bool result = Bench();
return result;
}
public static int Main() {
bool result = TestBase();
return (result ? 100 : -1);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
using System.Runtime.CompilerServices;
namespace Benchstone.MDBenchI
{
public static class MDMidpoint
{
#if DEBUG
public const int Iterations = 1;
#else
public const int Iterations = 70000;
#endif
static int Inner(ref int x, ref int y, ref int z) {
int mid;
if (x < y) {
if (y < z) {
mid = y;
}
else {
if (x < z) {
mid = z;
}
else {
mid = x;
}
}
}
else {
if (x < z) {
mid = x;
}
else {
if (y < z) {
mid = z;
}
else {
mid = y;
}
}
}
return (mid);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool Bench() {
int[,] a = new int[2001, 4];
int[] mid = new int[2001];
int j = 99999;
for (int i = 1; i <= 2000; i++) {
a[i,1] = j & 32767;
a[i,2] = (j + 11111) & 32767;
a[i,3] = (j + 22222) & 32767;
j = j + 33333;
}
for (int k = 1; k <= Iterations; k++) {
for (int l = 1; l <= 2000; l++) {
mid[l] = Inner(ref a[l,1], ref a[l,2], ref a[l,3]);
}
}
return (mid[2000] == 17018);
}
static bool TestBase() {
bool result = Bench();
return result;
}
public static int Main() {
bool result = TestBase();
return (result ? 100 : -1);
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/Fakes/StructServiceWithNoDependencies.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.Extensions.DependencyInjection.Specification.Fakes;
namespace Microsoft.Extensions.DependencyInjection.Fakes
{
public struct StructServiceWithNoDependencies: IFakeService
{
public StructServiceWithNoDependencies()
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Extensions.DependencyInjection.Specification.Fakes;
namespace Microsoft.Extensions.DependencyInjection.Fakes
{
public struct StructServiceWithNoDependencies: IFakeService
{
public StructServiceWithNoDependencies()
{
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ExtractNarrowingUpper.Vector128.Int16.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void ExtractNarrowingUpper_Vector128_Int16()
{
var test = new SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, Int32[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int16> _fld1;
public Vector128<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int16 testClass)
{
var result = AdvSimd.ExtractNarrowingUpper(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int16 testClass)
{
fixed (Vector64<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.ExtractNarrowingUpper(
AdvSimd.LoadVector64((Int16*)(pFld1)),
AdvSimd.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector64<Int16> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector64<Int16> _fld1;
private Vector128<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.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.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.ExtractNarrowingUpper(
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.ExtractNarrowingUpper(
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ExtractNarrowingUpper), new Type[] { typeof(Vector64<Int16>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ExtractNarrowingUpper), new Type[] { typeof(Vector64<Int16>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.ExtractNarrowingUpper(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int32>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.ExtractNarrowingUpper(
AdvSimd.LoadVector64((Int16*)(pClsVar1)),
AdvSimd.LoadVector128((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = AdvSimd.ExtractNarrowingUpper(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var result = AdvSimd.ExtractNarrowingUpper(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int16();
var result = AdvSimd.ExtractNarrowingUpper(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__ExtractNarrowingUpper_Vector128_Int16();
fixed (Vector64<Int16>* pFld1 = &test._fld1)
fixed (Vector128<Int32>* pFld2 = &test._fld2)
{
var result = AdvSimd.ExtractNarrowingUpper(
AdvSimd.LoadVector64((Int16*)(pFld1)),
AdvSimd.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.ExtractNarrowingUpper(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.ExtractNarrowingUpper(
AdvSimd.LoadVector64((Int16*)(pFld1)),
AdvSimd.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.ExtractNarrowingUpper(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.ExtractNarrowingUpper(
AdvSimd.LoadVector64((Int16*)(&test._fld1)),
AdvSimd.LoadVector128((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<Int16> op1, Vector128<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int32[] right, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ExtractNarrowingUpper(left, right, i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ExtractNarrowingUpper)}<Int16>(Vector64<Int16>, Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void ExtractNarrowingUpper_Vector128_Int16()
{
var test = new SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, Int32[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int16> _fld1;
public Vector128<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int16 testClass)
{
var result = AdvSimd.ExtractNarrowingUpper(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int16 testClass)
{
fixed (Vector64<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.ExtractNarrowingUpper(
AdvSimd.LoadVector64((Int16*)(pFld1)),
AdvSimd.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector64<Int16> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector64<Int16> _fld1;
private Vector128<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.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.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.ExtractNarrowingUpper(
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.ExtractNarrowingUpper(
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ExtractNarrowingUpper), new Type[] { typeof(Vector64<Int16>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ExtractNarrowingUpper), new Type[] { typeof(Vector64<Int16>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.ExtractNarrowingUpper(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int32>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.ExtractNarrowingUpper(
AdvSimd.LoadVector64((Int16*)(pClsVar1)),
AdvSimd.LoadVector128((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = AdvSimd.ExtractNarrowingUpper(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var result = AdvSimd.ExtractNarrowingUpper(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__ExtractNarrowingUpper_Vector128_Int16();
var result = AdvSimd.ExtractNarrowingUpper(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__ExtractNarrowingUpper_Vector128_Int16();
fixed (Vector64<Int16>* pFld1 = &test._fld1)
fixed (Vector128<Int32>* pFld2 = &test._fld2)
{
var result = AdvSimd.ExtractNarrowingUpper(
AdvSimd.LoadVector64((Int16*)(pFld1)),
AdvSimd.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.ExtractNarrowingUpper(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = AdvSimd.ExtractNarrowingUpper(
AdvSimd.LoadVector64((Int16*)(pFld1)),
AdvSimd.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.ExtractNarrowingUpper(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.ExtractNarrowingUpper(
AdvSimd.LoadVector64((Int16*)(&test._fld1)),
AdvSimd.LoadVector128((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<Int16> op1, Vector128<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int32[] right, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ExtractNarrowingUpper(left, right, i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ExtractNarrowingUpper)}<Int16>(Vector64<Int16>, Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.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.Formats.Asn1;
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using Internal.Cryptography;
namespace Internal.Cryptography.Pal.AnyOS
{
internal sealed partial class ManagedPkcsPal : PkcsPal
{
public override void AddCertsFromStoreForDecryption(X509Certificate2Collection certs)
{
certs.AddRange(PkcsHelpers.GetStoreCertificates(StoreName.My, StoreLocation.CurrentUser, openExistingOnly: false));
try
{
// This store exists on macOS, but not Linux
certs.AddRange(
PkcsHelpers.GetStoreCertificates(StoreName.My, StoreLocation.LocalMachine, openExistingOnly: false));
}
catch (CryptographicException)
{
}
}
public override byte[] GetSubjectKeyIdentifier(X509Certificate2 certificate)
{
Debug.Assert(certificate != null);
X509Extension? extension = certificate.Extensions[Oids.SubjectKeyIdentifier];
if (extension == null)
{
// Construct the value from the public key info.
extension = new X509SubjectKeyIdentifierExtension(
certificate.PublicKey,
X509SubjectKeyIdentifierHashAlgorithm.CapiSha1,
false);
}
try
{
// Certificates are DER encoded.
AsnValueReader reader = new AsnValueReader(extension.RawData, AsnEncodingRules.DER);
if (reader.TryReadPrimitiveOctetString(out ReadOnlySpan<byte> contents))
{
reader.ThrowIfNotEmpty();
return contents.ToArray();
}
// TryGetPrimitiveOctetStringBytes will have thrown if the next tag wasn't
// Universal (primitive) OCTET STRING, since we're in DER mode.
// So there's really no way we can get here.
Debug.Fail($"TryGetPrimitiveOctetStringBytes returned false in DER mode");
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
catch (AsnContentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}
public override T? GetPrivateKeyForSigning<T>(X509Certificate2 certificate, bool silent) where T : class
{
return GetPrivateKey<T>(certificate);
}
public override T? GetPrivateKeyForDecryption<T>(X509Certificate2 certificate, bool silent) where T : class
{
return GetPrivateKey<T>(certificate);
}
private T? GetPrivateKey<T>(X509Certificate2 certificate) where T : AsymmetricAlgorithm
{
if (typeof(T) == typeof(RSA))
return (T?)(object?)certificate.GetRSAPrivateKey();
if (typeof(T) == typeof(ECDsa))
return (T?)(object?)certificate.GetECDsaPrivateKey();
#if NETCOREAPP || NETSTANDARD2_1
if (typeof(T) == typeof(DSA) && Internal.Cryptography.Helpers.IsDSASupported)
return (T?)(object?)certificate.GetDSAPrivateKey();
#endif
Debug.Fail($"Unknown key type requested: {typeof(T).FullName}");
return null;
}
private static SymmetricAlgorithm OpenAlgorithm(AlgorithmIdentifierAsn contentEncryptionAlgorithm)
{
SymmetricAlgorithm alg = OpenAlgorithm(contentEncryptionAlgorithm.Algorithm);
if (alg is RC2)
{
if (contentEncryptionAlgorithm.Parameters == null)
{
// Windows issues CRYPT_E_BAD_DECODE
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
Rc2CbcParameters rc2Params = Rc2CbcParameters.Decode(
contentEncryptionAlgorithm.Parameters.Value,
AsnEncodingRules.BER);
alg.KeySize = rc2Params.GetEffectiveKeyBits();
alg.IV = rc2Params.Iv.ToArray();
}
else
{
if (contentEncryptionAlgorithm.Parameters == null)
{
// Windows issues CRYPT_E_BAD_DECODE
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
try
{
AsnReader reader = new AsnReader(contentEncryptionAlgorithm.Parameters.Value, AsnEncodingRules.BER);
alg.IV = reader.ReadOctetString();
if (alg.IV.Length != alg.BlockSize / 8)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
}
catch (AsnContentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}
return alg;
}
private static SymmetricAlgorithm OpenAlgorithm(AlgorithmIdentifier algorithmIdentifier)
{
SymmetricAlgorithm alg = OpenAlgorithm(algorithmIdentifier.Oid.Value!);
if (alg is RC2)
{
if (algorithmIdentifier.KeyLength != 0)
{
alg.KeySize = algorithmIdentifier.KeyLength;
}
else
{
alg.KeySize = KeyLengths.Rc2_128Bit;
}
}
return alg;
}
private static SymmetricAlgorithm OpenAlgorithm(string algorithmIdentifier)
{
Debug.Assert(algorithmIdentifier != null);
SymmetricAlgorithm alg;
switch (algorithmIdentifier)
{
case Oids.Rc2Cbc:
if (!Helpers.IsRC2Supported)
{
throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_AlgorithmNotSupported, nameof(RC2)));
}
#pragma warning disable CA5351
alg = RC2.Create();
#pragma warning restore CA5351
break;
case Oids.DesCbc:
#pragma warning disable CA5351
alg = DES.Create();
#pragma warning restore CA5351
break;
case Oids.TripleDesCbc:
#pragma warning disable CA5350
alg = TripleDES.Create();
#pragma warning restore CA5350
break;
case Oids.Aes128Cbc:
alg = Aes.Create();
alg.KeySize = 128;
break;
case Oids.Aes192Cbc:
alg = Aes.Create();
alg.KeySize = 192;
break;
case Oids.Aes256Cbc:
alg = Aes.Create();
alg.KeySize = 256;
break;
default:
throw new CryptographicException(SR.Cryptography_Cms_UnknownAlgorithm, algorithmIdentifier);
}
// These are the defaults, but they're restated here for clarity.
alg.Padding = PaddingMode.PKCS7;
alg.Mode = CipherMode.CBC;
return alg;
}
}
}
| // 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.Formats.Asn1;
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using Internal.Cryptography;
namespace Internal.Cryptography.Pal.AnyOS
{
internal sealed partial class ManagedPkcsPal : PkcsPal
{
public override void AddCertsFromStoreForDecryption(X509Certificate2Collection certs)
{
certs.AddRange(PkcsHelpers.GetStoreCertificates(StoreName.My, StoreLocation.CurrentUser, openExistingOnly: false));
try
{
// This store exists on macOS, but not Linux
certs.AddRange(
PkcsHelpers.GetStoreCertificates(StoreName.My, StoreLocation.LocalMachine, openExistingOnly: false));
}
catch (CryptographicException)
{
}
}
public override byte[] GetSubjectKeyIdentifier(X509Certificate2 certificate)
{
Debug.Assert(certificate != null);
X509Extension? extension = certificate.Extensions[Oids.SubjectKeyIdentifier];
if (extension == null)
{
// Construct the value from the public key info.
extension = new X509SubjectKeyIdentifierExtension(
certificate.PublicKey,
X509SubjectKeyIdentifierHashAlgorithm.CapiSha1,
false);
}
try
{
// Certificates are DER encoded.
AsnValueReader reader = new AsnValueReader(extension.RawData, AsnEncodingRules.DER);
if (reader.TryReadPrimitiveOctetString(out ReadOnlySpan<byte> contents))
{
reader.ThrowIfNotEmpty();
return contents.ToArray();
}
// TryGetPrimitiveOctetStringBytes will have thrown if the next tag wasn't
// Universal (primitive) OCTET STRING, since we're in DER mode.
// So there's really no way we can get here.
Debug.Fail($"TryGetPrimitiveOctetStringBytes returned false in DER mode");
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
catch (AsnContentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}
public override T? GetPrivateKeyForSigning<T>(X509Certificate2 certificate, bool silent) where T : class
{
return GetPrivateKey<T>(certificate);
}
public override T? GetPrivateKeyForDecryption<T>(X509Certificate2 certificate, bool silent) where T : class
{
return GetPrivateKey<T>(certificate);
}
private T? GetPrivateKey<T>(X509Certificate2 certificate) where T : AsymmetricAlgorithm
{
if (typeof(T) == typeof(RSA))
return (T?)(object?)certificate.GetRSAPrivateKey();
if (typeof(T) == typeof(ECDsa))
return (T?)(object?)certificate.GetECDsaPrivateKey();
#if NETCOREAPP || NETSTANDARD2_1
if (typeof(T) == typeof(DSA) && Internal.Cryptography.Helpers.IsDSASupported)
return (T?)(object?)certificate.GetDSAPrivateKey();
#endif
Debug.Fail($"Unknown key type requested: {typeof(T).FullName}");
return null;
}
private static SymmetricAlgorithm OpenAlgorithm(AlgorithmIdentifierAsn contentEncryptionAlgorithm)
{
SymmetricAlgorithm alg = OpenAlgorithm(contentEncryptionAlgorithm.Algorithm);
if (alg is RC2)
{
if (contentEncryptionAlgorithm.Parameters == null)
{
// Windows issues CRYPT_E_BAD_DECODE
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
Rc2CbcParameters rc2Params = Rc2CbcParameters.Decode(
contentEncryptionAlgorithm.Parameters.Value,
AsnEncodingRules.BER);
alg.KeySize = rc2Params.GetEffectiveKeyBits();
alg.IV = rc2Params.Iv.ToArray();
}
else
{
if (contentEncryptionAlgorithm.Parameters == null)
{
// Windows issues CRYPT_E_BAD_DECODE
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
try
{
AsnReader reader = new AsnReader(contentEncryptionAlgorithm.Parameters.Value, AsnEncodingRules.BER);
alg.IV = reader.ReadOctetString();
if (alg.IV.Length != alg.BlockSize / 8)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
}
catch (AsnContentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}
return alg;
}
private static SymmetricAlgorithm OpenAlgorithm(AlgorithmIdentifier algorithmIdentifier)
{
SymmetricAlgorithm alg = OpenAlgorithm(algorithmIdentifier.Oid.Value!);
if (alg is RC2)
{
if (algorithmIdentifier.KeyLength != 0)
{
alg.KeySize = algorithmIdentifier.KeyLength;
}
else
{
alg.KeySize = KeyLengths.Rc2_128Bit;
}
}
return alg;
}
private static SymmetricAlgorithm OpenAlgorithm(string algorithmIdentifier)
{
Debug.Assert(algorithmIdentifier != null);
SymmetricAlgorithm alg;
switch (algorithmIdentifier)
{
case Oids.Rc2Cbc:
if (!Helpers.IsRC2Supported)
{
throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_AlgorithmNotSupported, nameof(RC2)));
}
#pragma warning disable CA5351
alg = RC2.Create();
#pragma warning restore CA5351
break;
case Oids.DesCbc:
#pragma warning disable CA5351
alg = DES.Create();
#pragma warning restore CA5351
break;
case Oids.TripleDesCbc:
#pragma warning disable CA5350
alg = TripleDES.Create();
#pragma warning restore CA5350
break;
case Oids.Aes128Cbc:
alg = Aes.Create();
alg.KeySize = 128;
break;
case Oids.Aes192Cbc:
alg = Aes.Create();
alg.KeySize = 192;
break;
case Oids.Aes256Cbc:
alg = Aes.Create();
alg.KeySize = 256;
break;
default:
throw new CryptographicException(SR.Cryptography_Cms_UnknownAlgorithm, algorithmIdentifier);
}
// These are the defaults, but they're restated here for clarity.
alg.Padding = PaddingMode.PKCS7;
alg.Mode = CipherMode.CBC;
return alg;
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/CircularDependencyTests.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 Microsoft.Extensions.DependencyInjection.Tests.Fakes;
using Xunit;
namespace Microsoft.Extensions.DependencyInjection.Tests
{
public class CircularDependencyTests
{
[Fact]
public void SelfCircularDependency()
{
var expectedMessage = "A circular dependency was detected for the service of type " +
"'Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency'." +
Environment.NewLine +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency";
var serviceProvider = new ServiceCollection()
.AddTransient<SelfCircularDependency>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<SelfCircularDependency>());
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void SelfCircularDependencyInEnumerable()
{
var expectedMessage = "A circular dependency was detected for the service of type " +
"'Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency'." +
Environment.NewLine +
"System.Collections.Generic.IEnumerable<Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency> -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency";
var serviceProvider = new ServiceCollection()
.AddTransient<SelfCircularDependency>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<IEnumerable<SelfCircularDependency>>());
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void SelfCircularDependencyGenericDirect()
{
var expectedMessage = "A circular dependency was detected for the service of type " +
"'Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric<string>'." +
Environment.NewLine +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric<string> -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric<string>";
var serviceProvider = new ServiceCollection()
.AddTransient<SelfCircularDependencyGeneric<string>>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<SelfCircularDependencyGeneric<string>>());
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void SelfCircularDependencyGenericIndirect()
{
var expectedMessage = "A circular dependency was detected for the service of type " +
"'Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric<string>'." +
Environment.NewLine +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric<int> -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric<string> -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric<string>";
var serviceProvider = new ServiceCollection()
.AddTransient<SelfCircularDependencyGeneric<int>>()
.AddTransient<SelfCircularDependencyGeneric<string>>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<SelfCircularDependencyGeneric<int>>());
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void NoCircularDependencyGeneric()
{
var serviceProvider = new ServiceCollection()
.AddSingleton(new SelfCircularDependencyGeneric<string>())
.AddTransient<SelfCircularDependencyGeneric<int>>()
.BuildServiceProvider();
// This will not throw because we are creating an instance of the first time
// using the parameterless constructor which has no circular dependency
var resolvedService = serviceProvider.GetRequiredService<SelfCircularDependencyGeneric<int>>();
Assert.NotNull(resolvedService);
}
[Fact]
public void SelfCircularDependencyWithInterface()
{
var expectedMessage = "A circular dependency was detected for the service of type " +
"'Microsoft.Extensions.DependencyInjection.Tests.Fakes.ISelfCircularDependencyWithInterface'." +
Environment.NewLine +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyWithInterface -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.ISelfCircularDependencyWithInterface" +
"(Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyWithInterface) -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.ISelfCircularDependencyWithInterface";
var serviceProvider = new ServiceCollection()
.AddTransient<ISelfCircularDependencyWithInterface, SelfCircularDependencyWithInterface>()
.AddTransient<SelfCircularDependencyWithInterface>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<SelfCircularDependencyWithInterface>());
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void DirectCircularDependency()
{
var expectedMessage = "A circular dependency was detected for the service of type " +
"'Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyA'." +
Environment.NewLine +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyA -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyB -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyA";
var serviceProvider = new ServiceCollection()
.AddSingleton<DirectCircularDependencyA>()
.AddSingleton<DirectCircularDependencyB>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<DirectCircularDependencyA>());
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void IndirectCircularDependency()
{
var expectedMessage = "A circular dependency was detected for the service of type " +
"'Microsoft.Extensions.DependencyInjection.Tests.Fakes.IndirectCircularDependencyA'." +
Environment.NewLine +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.IndirectCircularDependencyA -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.IndirectCircularDependencyB -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.IndirectCircularDependencyC -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.IndirectCircularDependencyA";
var serviceProvider = new ServiceCollection()
.AddSingleton<IndirectCircularDependencyA>()
.AddTransient<IndirectCircularDependencyB>()
.AddTransient<IndirectCircularDependencyC>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<IndirectCircularDependencyA>());
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void NoCircularDependencySameTypeMultipleTimes()
{
var serviceProvider = new ServiceCollection()
.AddTransient<NoCircularDependencySameTypeMultipleTimesA>()
.AddTransient<NoCircularDependencySameTypeMultipleTimesB>()
.AddTransient<NoCircularDependencySameTypeMultipleTimesC>()
.BuildServiceProvider();
var resolvedService = serviceProvider.GetRequiredService<NoCircularDependencySameTypeMultipleTimesA>();
Assert.NotNull(resolvedService);
}
[Fact]
public void DependencyOnCircularDependency()
{
var expectedMessage = "A circular dependency was detected for the service of type " +
"'Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyA'." +
Environment.NewLine +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.DependencyOnCircularDependency -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyA -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyB -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyA";
var serviceProvider = new ServiceCollection()
.AddTransient<DependencyOnCircularDependency>()
.AddTransient<DirectCircularDependencyA>()
.AddTransient<DirectCircularDependencyB>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<DependencyOnCircularDependency>());
Assert.Equal(expectedMessage, exception.Message);
}
}
}
| // 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 Microsoft.Extensions.DependencyInjection.Tests.Fakes;
using Xunit;
namespace Microsoft.Extensions.DependencyInjection.Tests
{
public class CircularDependencyTests
{
[Fact]
public void SelfCircularDependency()
{
var expectedMessage = "A circular dependency was detected for the service of type " +
"'Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency'." +
Environment.NewLine +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency";
var serviceProvider = new ServiceCollection()
.AddTransient<SelfCircularDependency>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<SelfCircularDependency>());
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void SelfCircularDependencyInEnumerable()
{
var expectedMessage = "A circular dependency was detected for the service of type " +
"'Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency'." +
Environment.NewLine +
"System.Collections.Generic.IEnumerable<Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency> -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency";
var serviceProvider = new ServiceCollection()
.AddTransient<SelfCircularDependency>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<IEnumerable<SelfCircularDependency>>());
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void SelfCircularDependencyGenericDirect()
{
var expectedMessage = "A circular dependency was detected for the service of type " +
"'Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric<string>'." +
Environment.NewLine +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric<string> -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric<string>";
var serviceProvider = new ServiceCollection()
.AddTransient<SelfCircularDependencyGeneric<string>>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<SelfCircularDependencyGeneric<string>>());
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void SelfCircularDependencyGenericIndirect()
{
var expectedMessage = "A circular dependency was detected for the service of type " +
"'Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric<string>'." +
Environment.NewLine +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric<int> -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric<string> -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric<string>";
var serviceProvider = new ServiceCollection()
.AddTransient<SelfCircularDependencyGeneric<int>>()
.AddTransient<SelfCircularDependencyGeneric<string>>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<SelfCircularDependencyGeneric<int>>());
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void NoCircularDependencyGeneric()
{
var serviceProvider = new ServiceCollection()
.AddSingleton(new SelfCircularDependencyGeneric<string>())
.AddTransient<SelfCircularDependencyGeneric<int>>()
.BuildServiceProvider();
// This will not throw because we are creating an instance of the first time
// using the parameterless constructor which has no circular dependency
var resolvedService = serviceProvider.GetRequiredService<SelfCircularDependencyGeneric<int>>();
Assert.NotNull(resolvedService);
}
[Fact]
public void SelfCircularDependencyWithInterface()
{
var expectedMessage = "A circular dependency was detected for the service of type " +
"'Microsoft.Extensions.DependencyInjection.Tests.Fakes.ISelfCircularDependencyWithInterface'." +
Environment.NewLine +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyWithInterface -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.ISelfCircularDependencyWithInterface" +
"(Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyWithInterface) -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.ISelfCircularDependencyWithInterface";
var serviceProvider = new ServiceCollection()
.AddTransient<ISelfCircularDependencyWithInterface, SelfCircularDependencyWithInterface>()
.AddTransient<SelfCircularDependencyWithInterface>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<SelfCircularDependencyWithInterface>());
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void DirectCircularDependency()
{
var expectedMessage = "A circular dependency was detected for the service of type " +
"'Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyA'." +
Environment.NewLine +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyA -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyB -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyA";
var serviceProvider = new ServiceCollection()
.AddSingleton<DirectCircularDependencyA>()
.AddSingleton<DirectCircularDependencyB>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<DirectCircularDependencyA>());
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void IndirectCircularDependency()
{
var expectedMessage = "A circular dependency was detected for the service of type " +
"'Microsoft.Extensions.DependencyInjection.Tests.Fakes.IndirectCircularDependencyA'." +
Environment.NewLine +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.IndirectCircularDependencyA -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.IndirectCircularDependencyB -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.IndirectCircularDependencyC -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.IndirectCircularDependencyA";
var serviceProvider = new ServiceCollection()
.AddSingleton<IndirectCircularDependencyA>()
.AddTransient<IndirectCircularDependencyB>()
.AddTransient<IndirectCircularDependencyC>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<IndirectCircularDependencyA>());
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void NoCircularDependencySameTypeMultipleTimes()
{
var serviceProvider = new ServiceCollection()
.AddTransient<NoCircularDependencySameTypeMultipleTimesA>()
.AddTransient<NoCircularDependencySameTypeMultipleTimesB>()
.AddTransient<NoCircularDependencySameTypeMultipleTimesC>()
.BuildServiceProvider();
var resolvedService = serviceProvider.GetRequiredService<NoCircularDependencySameTypeMultipleTimesA>();
Assert.NotNull(resolvedService);
}
[Fact]
public void DependencyOnCircularDependency()
{
var expectedMessage = "A circular dependency was detected for the service of type " +
"'Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyA'." +
Environment.NewLine +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.DependencyOnCircularDependency -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyA -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyB -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyA";
var serviceProvider = new ServiceCollection()
.AddTransient<DependencyOnCircularDependency>()
.AddTransient<DirectCircularDependencyA>()
.AddTransient<DirectCircularDependencyB>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<DependencyOnCircularDependency>());
Assert.Equal(expectedMessage, exception.Message);
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/General/Vector128/Create.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\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void CreateUInt16()
{
var test = new VectorCreate__CreateUInt16();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorCreate__CreateUInt16
{
private static readonly int LargestVectorSize = 16;
private static readonly int ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
UInt16 value = TestLibrary.Generator.GetUInt16();
Vector128<UInt16> result = Vector128.Create(value);
ValidateResult(result, value);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
UInt16 value = TestLibrary.Generator.GetUInt16();
object result = typeof(Vector128)
.GetMethod(nameof(Vector128.Create), new Type[] { typeof(UInt16) })
.Invoke(null, new object[] { value });
ValidateResult((Vector128<UInt16>)(result), value);
}
private void ValidateResult(Vector128<UInt16> result, UInt16 expectedValue, [CallerMemberName] string method = "")
{
UInt16[] resultElements = new UInt16[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref resultElements[0]), result);
ValidateResult(resultElements, expectedValue, method);
}
private void ValidateResult(UInt16[] resultElements, UInt16 expectedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (resultElements[0] != expectedValue)
{
succeeded = false;
}
else
{
for (var i = 1; i < ElementCount; i++)
{
if (resultElements[i] != expectedValue)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128.Create(UInt16): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: {expectedValue}");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})");
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\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void CreateUInt16()
{
var test = new VectorCreate__CreateUInt16();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorCreate__CreateUInt16
{
private static readonly int LargestVectorSize = 16;
private static readonly int ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
UInt16 value = TestLibrary.Generator.GetUInt16();
Vector128<UInt16> result = Vector128.Create(value);
ValidateResult(result, value);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
UInt16 value = TestLibrary.Generator.GetUInt16();
object result = typeof(Vector128)
.GetMethod(nameof(Vector128.Create), new Type[] { typeof(UInt16) })
.Invoke(null, new object[] { value });
ValidateResult((Vector128<UInt16>)(result), value);
}
private void ValidateResult(Vector128<UInt16> result, UInt16 expectedValue, [CallerMemberName] string method = "")
{
UInt16[] resultElements = new UInt16[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref resultElements[0]), result);
ValidateResult(resultElements, expectedValue, method);
}
private void ValidateResult(UInt16[] resultElements, UInt16 expectedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (resultElements[0] != expectedValue)
{
succeeded = false;
}
else
{
for (var i = 1; i < ElementCount; i++)
{
if (resultElements[i] != expectedValue)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128.Create(UInt16): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: {expectedValue}");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/tests/JIT/HardwareIntrinsics/General/Vector256_1/op_Addition.Single.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void op_AdditionSingle()
{
var test = new VectorBinaryOpTest__op_AdditionSingle();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBinaryOpTest__op_AdditionSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Single> _fld1;
public Vector256<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__op_AdditionSingle testClass)
{
var result = _fld1 + _fld2;
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector256<Single> _clsVar1;
private static Vector256<Single> _clsVar2;
private Vector256<Single> _fld1;
private Vector256<Single> _fld2;
private DataTable _dataTable;
static VectorBinaryOpTest__op_AdditionSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
}
public VectorBinaryOpTest__op_AdditionSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr) + Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Vector256<Single>).GetMethod("op_Addition", new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = _clsVar1 + _clsVar2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr);
var result = op1 + op2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__op_AdditionSingle();
var result = test._fld1 + test._fld2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = _fld1 + _fld2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = test._fld1 + test._fld2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector256<Single> op1, Vector256<Single> op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (float)(left[0] + right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (float)(left[i] + right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_Addition<Single>(Vector256<Single>, Vector256<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void op_AdditionSingle()
{
var test = new VectorBinaryOpTest__op_AdditionSingle();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBinaryOpTest__op_AdditionSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Single> _fld1;
public Vector256<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__op_AdditionSingle testClass)
{
var result = _fld1 + _fld2;
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector256<Single> _clsVar1;
private static Vector256<Single> _clsVar2;
private Vector256<Single> _fld1;
private Vector256<Single> _fld2;
private DataTable _dataTable;
static VectorBinaryOpTest__op_AdditionSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
}
public VectorBinaryOpTest__op_AdditionSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr) + Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Vector256<Single>).GetMethod("op_Addition", new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = _clsVar1 + _clsVar2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr);
var result = op1 + op2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__op_AdditionSingle();
var result = test._fld1 + test._fld2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = _fld1 + _fld2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = test._fld1 + test._fld2;
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector256<Single> op1, Vector256<Single> op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (float)(left[0] + right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (float)(left[i] + right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_Addition<Single>(Vector256<Single>, Vector256<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,292 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete | Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | rzikm | 2022-03-07T12:54:44Z | 2022-03-08T17:44:17Z | 627851323fe8f15539c163aabd7d7c644766c549 | 00ed84ae9ba5c68ada6041ca4aa8083cc89e0669 | Mark EncryptionPolicy.NoEncryption and EncryptionPolicy.AllowNoEncryption as obsolete. Fixes #65545
I don't think the current wording of the warning message is appropriate, but I could not come up with anything better for now. Suggestions welcome. | ./src/coreclr/vm/nativelibrarynative.h | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// File: NativeLibraryNative.h
//
//
// QCall's for the NativeLibrary class
//
#ifndef __NATIVELIBRARYNATIVE_H__
#define __NATIVELIBRARYNATIVE_H__
extern "C" INT_PTR QCALLTYPE NativeLibrary_LoadFromPath(LPCWSTR path, BOOL throwOnError);
extern "C" INT_PTR QCALLTYPE NativeLibrary_LoadByName(LPCWSTR name, QCall::AssemblyHandle callingAssembly,
BOOL hasDllImportSearchPathFlag, DWORD dllImportSearchPathFlag,
BOOL throwOnError);
extern "C" void QCALLTYPE NativeLibrary_FreeLib(INT_PTR handle);
extern "C" INT_PTR QCALLTYPE NativeLibrary_GetSymbol(INT_PTR handle, LPCWSTR symbolName, BOOL throwOnError);
#endif // __NATIVELIBRARYNATIVE_H__
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// File: NativeLibraryNative.h
//
//
// QCall's for the NativeLibrary class
//
#ifndef __NATIVELIBRARYNATIVE_H__
#define __NATIVELIBRARYNATIVE_H__
extern "C" INT_PTR QCALLTYPE NativeLibrary_LoadFromPath(LPCWSTR path, BOOL throwOnError);
extern "C" INT_PTR QCALLTYPE NativeLibrary_LoadByName(LPCWSTR name, QCall::AssemblyHandle callingAssembly,
BOOL hasDllImportSearchPathFlag, DWORD dllImportSearchPathFlag,
BOOL throwOnError);
extern "C" void QCALLTYPE NativeLibrary_FreeLib(INT_PTR handle);
extern "C" INT_PTR QCALLTYPE NativeLibrary_GetSymbol(INT_PTR handle, LPCWSTR symbolName, BOOL throwOnError);
#endif // __NATIVELIBRARYNATIVE_H__
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.