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,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/mono/mono/tests/thread7.cs
|
//
// Subset of thread6.cs, just to watch for the hang at end.
// Note this test does not indicate success or failure well,
// it just runs quickly or slowly.
//
using System;
using System.Threading;
public class Tests {
public static int Main() {
return test_0_regress_4413();
}
public static int test_0_regress_4413 () {
// Check that thread abort exceptions originating in another thread are not automatically rethrown
object o = new object ();
Thread t = null;
bool waiting = false;
Action a = delegate () {
t = Thread.CurrentThread;
while (true) {
lock (o) {
if (waiting) {
Monitor.Pulse (o);
break;
}
}
Thread.Sleep (10);
}
while (true) {
Thread.Sleep (1000);
}
};
var ar = a.BeginInvoke (null, null);
lock (o) {
waiting = true;
Monitor.Wait (o);
}
t.Abort ();
try {
try {
a.EndInvoke (ar);
} catch (ThreadAbortException) {
}
} catch (ThreadAbortException) {
// This will fail
Thread.ResetAbort ();
return 1;
}
return 0;
}
}
|
//
// Subset of thread6.cs, just to watch for the hang at end.
// Note this test does not indicate success or failure well,
// it just runs quickly or slowly.
//
using System;
using System.Threading;
public class Tests {
public static int Main() {
return test_0_regress_4413();
}
public static int test_0_regress_4413 () {
// Check that thread abort exceptions originating in another thread are not automatically rethrown
object o = new object ();
Thread t = null;
bool waiting = false;
Action a = delegate () {
t = Thread.CurrentThread;
while (true) {
lock (o) {
if (waiting) {
Monitor.Pulse (o);
break;
}
}
Thread.Sleep (10);
}
while (true) {
Thread.Sleep (1000);
}
};
var ar = a.BeginInvoke (null, null);
lock (o) {
waiting = true;
Monitor.Wait (o);
}
t.Abort ();
try {
try {
a.EndInvoke (ar);
} catch (ThreadAbortException) {
}
} catch (ThreadAbortException) {
// This will fail
Thread.ResetAbort ();
return 1;
}
return 0;
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Memory/tests/ReadOnlySpan/LastIndexOfSequence.byte.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Xunit;
namespace System.SpanTests
{
public static partial class ReadOnlySpanTests
{
[Fact]
public static void LastIndexOfSequenceMatchAtStart_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 5, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 5, 1, 77 });
int index = span.LastIndexOf(value);
Assert.Equal(0, index);
}
[Fact]
public static void LastIndexOfSequenceMultipleMatch_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 1, 2, 3, 1, 2, 3, 1, 2, 3, 1 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 2, 3 });
int index = span.LastIndexOf(value);
Assert.Equal(7, index);
}
[Fact]
public static void LastIndexOfSequenceRestart_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 8, 9, 77, 0, 1 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 77, 77, 88 });
int index = span.LastIndexOf(value);
Assert.Equal(10, index);
}
[Fact]
public static void LastIndexOfSequenceNoMatch_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 77, 77, 88, 99 });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void LastIndexOfSequenceNotEvenAHeadMatch_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 100, 77, 88, 99 });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void LastIndexOfSequenceMatchAtVeryEnd_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 2, 3, 4, 5 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 3, 4, 5 });
int index = span.LastIndexOf(value);
Assert.Equal(3, index);
}
[Fact]
public static void LastIndexOfSequenceJustPastVeryEnd_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 2, 3, 4, 5 }, 0, 5);
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 3, 4, 5 });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void LastIndexOfSequenceZeroLengthValue_Byte()
{
// A zero-length value is always "found" at the end of the span.
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(Array.Empty<byte>());
int index = span.LastIndexOf(value);
Assert.Equal(span.Length, index);
}
[Fact]
public static void LastIndexOfSequenceZeroLengthSpan_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(Array.Empty<byte>());
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 1, 2, 3 });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void LastIndexOfSequenceLengthOneValue_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 2, 3, 4, 5 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 2 });
int index = span.LastIndexOf(value);
Assert.Equal(2, index);
}
[Fact]
public static void LastIndexOfSequenceLengthOneValueAtVeryEnd_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 2, 3, 4, 5 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 5 });
int index = span.LastIndexOf(value);
Assert.Equal(5, index);
}
[Fact]
public static void LastIndexOfSequenceLengthOneValueMultipleTimes_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 5, 3, 4, 5 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 5 });
int index = span.LastIndexOf(value);
Assert.Equal(5, index);
}
[Fact]
public static void LastIndexOfSequenceLengthOneValueJustPasttVeryEnd_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 2, 3, 4, 5 }, 0, 5);
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 5 });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Xunit;
namespace System.SpanTests
{
public static partial class ReadOnlySpanTests
{
[Fact]
public static void LastIndexOfSequenceMatchAtStart_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 5, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 5, 1, 77 });
int index = span.LastIndexOf(value);
Assert.Equal(0, index);
}
[Fact]
public static void LastIndexOfSequenceMultipleMatch_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 1, 2, 3, 1, 2, 3, 1, 2, 3, 1 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 2, 3 });
int index = span.LastIndexOf(value);
Assert.Equal(7, index);
}
[Fact]
public static void LastIndexOfSequenceRestart_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 8, 9, 77, 0, 1 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 77, 77, 88 });
int index = span.LastIndexOf(value);
Assert.Equal(10, index);
}
[Fact]
public static void LastIndexOfSequenceNoMatch_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 77, 77, 88, 99 });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void LastIndexOfSequenceNotEvenAHeadMatch_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 100, 77, 88, 99 });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void LastIndexOfSequenceMatchAtVeryEnd_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 2, 3, 4, 5 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 3, 4, 5 });
int index = span.LastIndexOf(value);
Assert.Equal(3, index);
}
[Fact]
public static void LastIndexOfSequenceJustPastVeryEnd_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 2, 3, 4, 5 }, 0, 5);
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 3, 4, 5 });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void LastIndexOfSequenceZeroLengthValue_Byte()
{
// A zero-length value is always "found" at the end of the span.
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(Array.Empty<byte>());
int index = span.LastIndexOf(value);
Assert.Equal(span.Length, index);
}
[Fact]
public static void LastIndexOfSequenceZeroLengthSpan_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(Array.Empty<byte>());
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 1, 2, 3 });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void LastIndexOfSequenceLengthOneValue_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 2, 3, 4, 5 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 2 });
int index = span.LastIndexOf(value);
Assert.Equal(2, index);
}
[Fact]
public static void LastIndexOfSequenceLengthOneValueAtVeryEnd_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 2, 3, 4, 5 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 5 });
int index = span.LastIndexOf(value);
Assert.Equal(5, index);
}
[Fact]
public static void LastIndexOfSequenceLengthOneValueMultipleTimes_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 5, 3, 4, 5 });
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 5 });
int index = span.LastIndexOf(value);
Assert.Equal(5, index);
}
[Fact]
public static void LastIndexOfSequenceLengthOneValueJustPasttVeryEnd_Byte()
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(new byte[] { 0, 1, 2, 3, 4, 5 }, 0, 5);
ReadOnlySpan<byte> value = new ReadOnlySpan<byte>(new byte[] { 5 });
int index = span.LastIndexOf(value);
Assert.Equal(-1, index);
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/opt/CSE/NarrowStore.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
namespace NarrowStore
{
class Program
{
byte x01;
byte t01;
int Test()
{
x01 = 3;
t01 = (byte)~x01;
if (t01 == 252)
{
Console.WriteLine("Pass");
return 100;
}
else
{
Console.WriteLine("FAIL");
return -1;
}
}
static int Main(string[] args)
{
Program prog = new Program();
int result = prog.Test();
return result;
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
namespace NarrowStore
{
class Program
{
byte x01;
byte t01;
int Test()
{
x01 = 3;
t01 = (byte)~x01;
if (t01 == 252)
{
Console.WriteLine("Pass");
return 100;
}
else
{
Console.WriteLine("FAIL");
return -1;
}
}
static int Main(string[] args)
{
Program prog = new Program();
int result = prog.Test();
return result;
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/Methodical/explicit/basic/refarg_i1_ro.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>None</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="refarg_i1.cs" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>None</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="refarg_i1.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/Visitors/ExpressionTreeRewriter.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal sealed class ExpressionTreeRewriter : ExprVisitorBase
{
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
public static ExprBinOp Rewrite(ExprBoundLambda expr) => new ExpressionTreeRewriter().VisitBoundLambda(expr);
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr Dispatch(Expr expr)
{
Debug.Assert(expr != null);
Expr result = base.Dispatch(expr);
if (result == expr)
{
throw Error.InternalCompilerError();
}
return result;
}
/////////////////////////////////////////////////////////////////////////////////
// Statement types.
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitASSIGNMENT(ExprAssignment assignment)
{
Debug.Assert(assignment != null);
// For assignments, we either have a member assignment or an indexed assignment.
//Debug.Assert(assignment.GetLHS().isPROP() || assignment.GetLHS().isFIELD() || assignment.GetLHS().isARRAYINDEX() || assignment.GetLHS().isLOCAL());
Expr lhs;
if (assignment.LHS is ExprProperty prop)
{
if (prop.OptionalArguments == null)
{
// Regular property.
lhs = Visit(prop);
}
else
{
// Indexed assignment. Here we need to find the instance of the object, create the
// PropInfo for the thing, and get the array of expressions that make up the index arguments.
//
// The LHS becomes Expression.Property(instance, indexerInfo, arguments).
Expr instance = Visit(prop.MemberGroup.OptionalObject);
Expr propInfo = ExprFactory.CreatePropertyInfo(prop.PropWithTypeSlot.Prop(), prop.PropWithTypeSlot.Ats);
Expr arguments = GenerateParamsArray(
GenerateArgsList(prop.OptionalArguments),
PredefinedType.PT_EXPRESSION);
lhs = GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, instance, propInfo, arguments);
}
}
else
{
lhs = Visit(assignment.LHS);
}
Expr rhs = Visit(assignment.RHS);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitMULTIGET(ExprMultiGet pExpr)
{
return Visit(pExpr.OptionalMulti.Left);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitMULTI(ExprMulti pExpr)
{
Expr rhs = Visit(pExpr.Operator);
Expr lhs = Visit(pExpr.Left);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs);
}
/////////////////////////////////////////////////////////////////////////////////
// Expression types.
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private ExprBinOp VisitBoundLambda(ExprBoundLambda anonmeth)
{
Debug.Assert(anonmeth != null);
MethodSymbol lambdaMethod = GetPreDefMethod(PREDEFMETH.PM_EXPRESSION_LAMBDA);
AggregateType delegateType = anonmeth.DelegateType;
TypeArray lambdaTypeParams = TypeArray.Allocate(delegateType);
AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION);
MethWithInst mwi = new MethWithInst(lambdaMethod, expressionType, lambdaTypeParams);
Expr createParameters = CreateWraps(anonmeth);
Debug.Assert(createParameters != null);
Debug.Assert(anonmeth.Expression != null);
Expr body = Visit(anonmeth.Expression);
Debug.Assert(anonmeth.ArgumentScope.nextChild == null);
Expr parameters = GenerateParamsArray(null, PredefinedType.PT_PARAMETEREXPRESSION);
Expr args = ExprFactory.CreateList(body, parameters);
CType typeRet = TypeManager.SubstType(mwi.Meth().RetType, mwi.GetType(), mwi.TypeArgs);
ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi);
ExprCall call = ExprFactory.CreateCall(0, typeRet, args, pMemGroup, mwi);
call.PredefinedMethod = PREDEFMETH.PM_EXPRESSION_LAMBDA;
return ExprFactory.CreateSequence(createParameters, call);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitCONSTANT(ExprConstant expr)
{
Debug.Assert(expr != null);
return GenerateConstant(expr);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitLOCAL(ExprLocal local)
{
Debug.Assert(local != null);
Debug.Assert(local.Local.wrap != null);
return local.Local.wrap;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitFIELD(ExprField expr)
{
Debug.Assert(expr != null);
Expr pObject;
if (expr.OptionalObject == null)
{
pObject = ExprFactory.CreateNull();
}
else
{
pObject = Visit(expr.OptionalObject);
}
ExprFieldInfo pFieldInfo = ExprFactory.CreateFieldInfo(expr.FieldWithType.Field(), expr.FieldWithType.GetType());
return GenerateCall(PREDEFMETH.PM_EXPRESSION_FIELD, pObject, pFieldInfo);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitUSERDEFINEDCONVERSION(ExprUserDefinedConversion expr)
{
Debug.Assert(expr != null);
return GenerateUserDefinedConversion(expr, expr.Argument);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitCAST(ExprCast pExpr)
{
Debug.Assert(pExpr != null);
Expr pArgument = pExpr.Argument;
// If we have generated an identity cast or reference cast to a base class
// we can omit the cast.
if (pArgument.Type == pExpr.Type ||
SymbolLoader.IsBaseClassOfClass(pArgument.Type, pExpr.Type) ||
CConversions.FImpRefConv(pArgument.Type, pExpr.Type))
{
return Visit(pArgument);
}
// If we have a cast to PredefinedType.PT_G_EXPRESSION and the thing that we're casting is
// a EXPRBOUNDLAMBDA that is an expression tree, then just visit the expression tree.
if (pExpr.Type != null &&
pExpr.Type.IsPredefType(PredefinedType.PT_G_EXPRESSION) &&
pArgument is ExprBoundLambda)
{
return Visit(pArgument);
}
Expr result = GenerateConversion(pArgument, pExpr.Type, pExpr.isChecked());
if ((pExpr.Flags & EXPRFLAG.EXF_UNBOXRUNTIME) != 0)
{
// Propagate the unbox flag to the call for the ExpressionTreeCallRewriter.
result.Flags |= EXPRFLAG.EXF_UNBOXRUNTIME;
}
return result;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitCONCAT(ExprConcat expr)
{
Debug.Assert(expr != null);
PREDEFMETH pdm;
if (expr.FirstArgument.Type.IsPredefType(PredefinedType.PT_STRING) && expr.SecondArgument.Type.IsPredefType(PredefinedType.PT_STRING))
{
pdm = PREDEFMETH.PM_STRING_CONCAT_STRING_2;
}
else
{
pdm = PREDEFMETH.PM_STRING_CONCAT_OBJECT_2;
}
Expr p1 = Visit(expr.FirstArgument);
Expr p2 = Visit(expr.SecondArgument);
MethodSymbol method = GetPreDefMethod(pdm);
Expr methodInfo = ExprFactory.CreateMethodInfo(method, SymbolLoader.GetPredefindType(PredefinedType.PT_STRING), null);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED, p1, p2, methodInfo);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitBINOP(ExprBinOp expr)
{
Debug.Assert(expr != null);
if (expr.UserDefinedCallMethod != null)
{
return GenerateUserDefinedBinaryOperator(expr);
}
else
{
return GenerateBuiltInBinaryOperator(expr);
}
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitUNARYOP(ExprUnaryOp pExpr)
{
Debug.Assert(pExpr != null);
if (pExpr.UserDefinedCallMethod != null)
{
return GenerateUserDefinedUnaryOperator(pExpr);
}
else
{
return GenerateBuiltInUnaryOperator(pExpr);
}
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitARRAYINDEX(ExprArrayIndex pExpr)
{
Debug.Assert(pExpr != null);
Expr arr = Visit(pExpr.Array);
Expr args = GenerateIndexList(pExpr.Index);
if (args is ExprList)
{
Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2, arr, Params);
}
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX, arr, args);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitCALL(ExprCall expr)
{
Debug.Assert(expr != null);
switch (expr.NullableCallLiftKind)
{
default:
break;
case NullableCallLiftKind.NullableIntermediateConversion:
case NullableCallLiftKind.NullableConversion:
case NullableCallLiftKind.NullableConversionConstructor:
return GenerateConversion(expr.OptionalArguments, expr.Type, expr.isChecked());
case NullableCallLiftKind.NotLiftedIntermediateConversion:
case NullableCallLiftKind.UserDefinedConversion:
return GenerateUserDefinedConversion(expr.OptionalArguments, expr.Type, expr.MethWithInst);
}
if (expr.MethWithInst.Meth().IsConstructor())
{
return GenerateConstructor(expr);
}
ExprMemberGroup memberGroup = expr.MemberGroup;
if (memberGroup.IsDelegate)
{
return GenerateDelegateInvoke(expr);
}
Expr pObject;
if (expr.MethWithInst.Meth().isStatic || expr.MemberGroup.OptionalObject == null)
{
pObject = ExprFactory.CreateNull();
}
else
{
pObject = expr.MemberGroup.OptionalObject;
// If we have, say, an int? which is the object of a call to ToString
// then we do NOT want to generate ((object)i).ToString() because that
// will convert a null-valued int? to a null object. Rather what we want
// to do is box it to a ValueType and call ValueType.ToString.
//
// To implement this we say that if the object of the call is an implicit boxing cast
// then just generate the object, not the cast. If the cast is explicit in the
// source code then it will be an EXPLICITCAST and we will visit it normally.
//
// It might be better to rewrite the expression tree API so that it
// can handle in the general case all implicit boxing conversions. Right now it
// requires that all arguments to a call that need to be boxed be explicitly boxed.
if (pObject != null && pObject is ExprCast cast && cast.IsBoxingCast)
{
pObject = cast.Argument;
}
pObject = Visit(pObject);
}
Expr methodInfo = ExprFactory.CreateMethodInfo(expr.MethWithInst);
Expr args = GenerateArgsList(expr.OptionalArguments);
Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
PREDEFMETH pdm = PREDEFMETH.PM_EXPRESSION_CALL;
Debug.Assert(!expr.MethWithInst.Meth().isVirtual || expr.MemberGroup.OptionalObject != null);
return GenerateCall(pdm, pObject, methodInfo, Params);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitPROP(ExprProperty expr)
{
Debug.Assert(expr != null);
Expr pObject;
if (expr.PropWithTypeSlot.Prop().isStatic || expr.MemberGroup.OptionalObject == null)
{
pObject = ExprFactory.CreateNull();
}
else
{
pObject = Visit(expr.MemberGroup.OptionalObject);
}
Expr propInfo = ExprFactory.CreatePropertyInfo(expr.PropWithTypeSlot.Prop(), expr.PropWithTypeSlot.GetType());
if (expr.OptionalArguments != null)
{
// It is an indexer property. Turn it into a virtual method call.
Expr args = GenerateArgsList(expr.OptionalArguments);
Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo, Params);
}
return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitARRINIT(ExprArrayInit expr)
{
Debug.Assert(expr != null);
// POSSIBLE ERROR: Multi-d should be an error?
Expr pTypeOf = CreateTypeOf(((ArrayType)expr.Type).ElementType);
Expr args = GenerateArgsList(expr.OptionalArguments);
Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT, pTypeOf, Params);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitZEROINIT(ExprZeroInit expr)
{
Debug.Assert(expr != null);
return GenerateConstant(expr);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitTYPEOF(ExprTypeOf expr)
{
Debug.Assert(expr != null);
return GenerateConstant(expr);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateDelegateInvoke(ExprCall expr)
{
Debug.Assert(expr != null);
ExprMemberGroup memberGroup = expr.MemberGroup;
Debug.Assert(memberGroup.IsDelegate);
Expr oldObject = memberGroup.OptionalObject;
Debug.Assert(oldObject != null);
Expr pObject = Visit(oldObject);
Expr args = GenerateArgsList(expr.OptionalArguments);
Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_INVOKE, pObject, Params);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateBuiltInBinaryOperator(ExprBinOp expr)
{
Debug.Assert(expr != null);
PREDEFMETH pdm = expr.Kind switch
{
ExpressionKind.LeftShirt => PREDEFMETH.PM_EXPRESSION_LEFTSHIFT,
ExpressionKind.RightShift => PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT,
ExpressionKind.BitwiseExclusiveOr => PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR,
ExpressionKind.BitwiseOr => PREDEFMETH.PM_EXPRESSION_OR,
ExpressionKind.BitwiseAnd => PREDEFMETH.PM_EXPRESSION_AND,
ExpressionKind.LogicalAnd => PREDEFMETH.PM_EXPRESSION_ANDALSO,
ExpressionKind.LogicalOr => PREDEFMETH.PM_EXPRESSION_ORELSE,
ExpressionKind.StringEq => PREDEFMETH.PM_EXPRESSION_EQUAL,
ExpressionKind.Eq => PREDEFMETH.PM_EXPRESSION_EQUAL,
ExpressionKind.StringNotEq => PREDEFMETH.PM_EXPRESSION_NOTEQUAL,
ExpressionKind.NotEq => PREDEFMETH.PM_EXPRESSION_NOTEQUAL,
ExpressionKind.GreaterThanOrEqual => PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL,
ExpressionKind.LessThanOrEqual => PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL,
ExpressionKind.LessThan => PREDEFMETH.PM_EXPRESSION_LESSTHAN,
ExpressionKind.GreaterThan => PREDEFMETH.PM_EXPRESSION_GREATERTHAN,
ExpressionKind.Modulo => PREDEFMETH.PM_EXPRESSION_MODULO,
ExpressionKind.Divide => PREDEFMETH.PM_EXPRESSION_DIVIDE,
ExpressionKind.Multiply => expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED : PREDEFMETH.PM_EXPRESSION_MULTIPLY,
ExpressionKind.Subtract => expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED : PREDEFMETH.PM_EXPRESSION_SUBTRACT,
ExpressionKind.Add => expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED : PREDEFMETH.PM_EXPRESSION_ADD,
_ => throw Error.InternalCompilerError(),
};
Expr origL = expr.OptionalLeftChild;
Expr origR = expr.OptionalRightChild;
Debug.Assert(origL != null);
Debug.Assert(origR != null);
CType typeL = origL.Type;
CType typeR = origR.Type;
Expr newL = Visit(origL);
Expr newR = Visit(origR);
bool didEnumConversion = false;
CType convertL = null;
CType convertR = null;
if (typeL.IsEnumType)
{
// We have already inserted casts if not lifted, so we should never see an enum.
Debug.Assert(expr.IsLifted);
convertL = TypeManager.GetNullable(typeL.UnderlyingEnumType);
typeL = convertL;
didEnumConversion = true;
}
else if (typeL is NullableType nubL && nubL.UnderlyingType.IsEnumType)
{
Debug.Assert(expr.IsLifted);
convertL = TypeManager.GetNullable(nubL.UnderlyingType.UnderlyingEnumType);
typeL = convertL;
didEnumConversion = true;
}
if (typeR.IsEnumType)
{
Debug.Assert(expr.IsLifted);
convertR = TypeManager.GetNullable(typeR.UnderlyingEnumType);
typeR = convertR;
didEnumConversion = true;
}
else if (typeR is NullableType nubR && nubR.UnderlyingType.IsEnumType)
{
Debug.Assert(expr.IsLifted);
convertR = TypeManager.GetNullable(nubR.UnderlyingType.UnderlyingEnumType);
typeR = convertR;
didEnumConversion = true;
}
if (typeL is NullableType nubL2 && nubL2.UnderlyingType == typeR)
{
convertR = typeL;
}
if (typeR is NullableType nubR2 && nubR2.UnderlyingType == typeL)
{
convertL = typeR;
}
if (convertL != null)
{
newL = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newL, CreateTypeOf(convertL));
}
if (convertR != null)
{
newR = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newR, CreateTypeOf(convertR));
}
Expr call = GenerateCall(pdm, newL, newR);
if (didEnumConversion && expr.Type.StripNubs().IsEnumType)
{
call = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, CreateTypeOf(expr.Type));
}
return call;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateBuiltInUnaryOperator(ExprUnaryOp expr)
{
Debug.Assert(expr != null);
PREDEFMETH pdm;
switch (expr.Kind)
{
case ExpressionKind.UnaryPlus:
return Visit(expr.Child);
case ExpressionKind.BitwiseNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break;
case ExpressionKind.LogicalNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break;
case ExpressionKind.Negate:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED : PREDEFMETH.PM_EXPRESSION_NEGATE;
break;
default:
throw Error.InternalCompilerError();
}
Expr origOp = expr.Child;
// Such operations are always already casts on operations on casts.
Debug.Assert(!(origOp.Type is NullableType nub) || !nub.UnderlyingType.IsEnumType);
return GenerateCall(pdm, Visit(origOp));
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateUserDefinedBinaryOperator(ExprBinOp expr)
{
Debug.Assert(expr != null);
PREDEFMETH pdm;
switch (expr.Kind)
{
case ExpressionKind.LogicalOr: pdm = PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED; break;
case ExpressionKind.LogicalAnd: pdm = PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED; break;
case ExpressionKind.LeftShirt: pdm = PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED; break;
case ExpressionKind.RightShift: pdm = PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED; break;
case ExpressionKind.BitwiseExclusiveOr: pdm = PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED; break;
case ExpressionKind.BitwiseOr: pdm = PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED; break;
case ExpressionKind.BitwiseAnd: pdm = PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED; break;
case ExpressionKind.Modulo: pdm = PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED; break;
case ExpressionKind.Divide: pdm = PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED; break;
case ExpressionKind.StringEq:
case ExpressionKind.StringNotEq:
case ExpressionKind.DelegateEq:
case ExpressionKind.DelegateNotEq:
case ExpressionKind.Eq:
case ExpressionKind.NotEq:
case ExpressionKind.GreaterThanOrEqual:
case ExpressionKind.GreaterThan:
case ExpressionKind.LessThanOrEqual:
case ExpressionKind.LessThan:
return GenerateUserDefinedComparisonOperator(expr);
case ExpressionKind.DelegateSubtract:
case ExpressionKind.Subtract:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED;
break;
case ExpressionKind.DelegateAdd:
case ExpressionKind.Add:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED;
break;
case ExpressionKind.Multiply:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED;
break;
default:
throw Error.InternalCompilerError();
}
Expr p1 = expr.OptionalLeftChild;
Expr p2 = expr.OptionalRightChild;
Expr udcall = expr.OptionalUserDefinedCall;
if (udcall != null)
{
Debug.Assert(udcall.Kind == ExpressionKind.Call || udcall.Kind == ExpressionKind.UserLogicalOp);
if (udcall is ExprCall ascall)
{
ExprList args = (ExprList)ascall.OptionalArguments;
Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List);
p1 = args.OptionalElement;
p2 = args.OptionalNextListNode;
}
else
{
ExprUserLogicalOp userLogOp = udcall as ExprUserLogicalOp;
Debug.Assert(userLogOp != null);
ExprList args = (ExprList)userLogOp.OperatorCall.OptionalArguments;
Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List);
p1 = ((ExprWrap)args.OptionalElement).OptionalExpression;
p2 = args.OptionalNextListNode;
}
}
p1 = Visit(p1);
p2 = Visit(p2);
FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2);
Expr methodInfo = ExprFactory.CreateMethodInfo(expr.UserDefinedCallMethod);
Expr call = GenerateCall(pdm, p1, p2, methodInfo);
// Delegate add/subtract generates a call to Combine/Remove, which returns System.Delegate,
// not the operand delegate CType. We must cast to the delegate CType.
if (expr.Kind == ExpressionKind.DelegateSubtract || expr.Kind == ExpressionKind.DelegateAdd)
{
Expr pTypeOf = CreateTypeOf(expr.Type);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, pTypeOf);
}
return call;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateUserDefinedUnaryOperator(ExprUnaryOp expr)
{
Debug.Assert(expr != null);
PREDEFMETH pdm;
Expr arg = expr.Child;
ExprCall call = (ExprCall)expr.OptionalUserDefinedCall;
if (call != null)
{
// Use the actual argument of the call; it may contain user-defined
// conversions or be a bound lambda, and that will not be in the original
// argument stashed away in the left child of the operator.
arg = call.OptionalArguments;
}
Debug.Assert(arg != null && arg.Kind != ExpressionKind.List);
switch (expr.Kind)
{
case ExpressionKind.True:
case ExpressionKind.False:
return Visit(call);
case ExpressionKind.UnaryPlus:
pdm = PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED;
break;
case ExpressionKind.BitwiseNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break;
case ExpressionKind.LogicalNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break;
case ExpressionKind.DecimalNegate:
case ExpressionKind.Negate:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED;
break;
case ExpressionKind.Inc:
case ExpressionKind.Dec:
case ExpressionKind.DecimalInc:
case ExpressionKind.DecimalDec:
pdm = PREDEFMETH.PM_EXPRESSION_CALL;
break;
default:
throw Error.InternalCompilerError();
}
Expr op = Visit(arg);
Expr methodInfo = ExprFactory.CreateMethodInfo(expr.UserDefinedCallMethod);
if (expr.Kind == ExpressionKind.Inc || expr.Kind == ExpressionKind.Dec ||
expr.Kind == ExpressionKind.DecimalInc || expr.Kind == ExpressionKind.DecimalDec)
{
return GenerateCall(pdm, null, methodInfo, GenerateParamsArray(op, PredefinedType.PT_EXPRESSION));
}
return GenerateCall(pdm, op, methodInfo);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateUserDefinedComparisonOperator(ExprBinOp expr)
{
Debug.Assert(expr != null);
PREDEFMETH pdm = expr.Kind switch
{
ExpressionKind.StringEq => PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED,
ExpressionKind.StringNotEq => PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED,
ExpressionKind.DelegateEq => PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED,
ExpressionKind.DelegateNotEq => PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED,
ExpressionKind.Eq => PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED,
ExpressionKind.NotEq => PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED,
ExpressionKind.LessThanOrEqual => PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED,
ExpressionKind.LessThan => PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED,
ExpressionKind.GreaterThanOrEqual => PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED,
ExpressionKind.GreaterThan => PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED,
_ => throw Error.InternalCompilerError(),
};
Expr p1 = expr.OptionalLeftChild;
Expr p2 = expr.OptionalRightChild;
if (expr.OptionalUserDefinedCall != null)
{
ExprCall udcall = (ExprCall)expr.OptionalUserDefinedCall;
ExprList args = (ExprList)udcall.OptionalArguments;
Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List);
p1 = args.OptionalElement;
p2 = args.OptionalNextListNode;
}
p1 = Visit(p1);
p2 = Visit(p2);
FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2);
Expr lift = ExprFactory.CreateBoolConstant(false); // We never lift to null in C#.
Expr methodInfo = ExprFactory.CreateMethodInfo(expr.UserDefinedCallMethod);
return GenerateCall(pdm, p1, p2, lift, methodInfo);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateConversion(Expr arg, CType CType, bool bChecked) =>
GenerateConversionWithSource(Visit(arg), CType, bChecked || arg.isChecked());
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static Expr GenerateConversionWithSource(Expr pTarget, CType pType, bool bChecked)
{
PREDEFMETH pdm = bChecked ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT;
Expr pTypeOf = CreateTypeOf(pType);
return GenerateCall(pdm, pTarget, pTypeOf);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateValueAccessConversion(Expr pArgument)
{
Debug.Assert(pArgument != null);
CType pStrippedTypeOfArgument = pArgument.Type.StripNubs();
Expr pStrippedTypeExpr = CreateTypeOf(pStrippedTypeOfArgument);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, Visit(pArgument), pStrippedTypeExpr);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateUserDefinedConversion(Expr arg, CType type, MethWithInst method)
{
Expr target = Visit(arg);
return GenerateUserDefinedConversion(arg, type, target, method);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static Expr GenerateUserDefinedConversion(Expr arg, CType CType, Expr target, MethWithInst method)
{
// The user-defined explicit conversion from enum? to decimal or decimal? requires
// that we convert the enum? to its nullable underlying CType.
if (isEnumToDecimalConversion(arg.Type, CType))
{
// Special case: If we have enum? to decimal? then we need to emit
// a conversion from enum? to its nullable underlying CType first.
// This is unfortunate; we ought to reorganize how conversions are
// represented in the Expr tree so that this is more transparent.
// converting an enum to its underlying CType never fails, so no need to check it.
CType underlyingType = arg.Type.StripNubs().UnderlyingEnumType;
CType nullableType = TypeManager.GetNullable(underlyingType);
Expr typeofNubEnum = CreateTypeOf(nullableType);
target = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, target, typeofNubEnum);
}
// If the methodinfo does not return the target CType AND this is not a lifted conversion
// from one value CType to another, then we need to wrap the whole thing in another conversion,
// e.g. if we have a user-defined conversion from int to S? and we have (S)myint, then we need to generate
// Convert(Convert(myint, typeof(S?), op_implicit), typeof(S))
CType pMethodReturnType = TypeManager.SubstType(method.Meth().RetType,
method.GetType(), method.TypeArgs);
bool fDontLiftReturnType = (pMethodReturnType == CType || (IsNullableValueType(arg.Type) && IsNullableValueType(CType)));
Expr typeofInner = CreateTypeOf(fDontLiftReturnType ? CType : pMethodReturnType);
Expr methodInfo = ExprFactory.CreateMethodInfo(method);
PREDEFMETH pdmInner = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED;
Expr callUserDefinedConversion = GenerateCall(pdmInner, target, typeofInner, methodInfo);
if (fDontLiftReturnType)
{
return callUserDefinedConversion;
}
PREDEFMETH pdmOuter = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT;
Expr typeofOuter = CreateTypeOf(CType);
return GenerateCall(pdmOuter, callUserDefinedConversion, typeofOuter);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateUserDefinedConversion(ExprUserDefinedConversion pExpr, Expr pArgument)
{
Expr pCastCall = pExpr.UserDefinedCall;
Expr pCastArgument = pExpr.Argument;
Expr pConversionSource;
if (!isEnumToDecimalConversion(pArgument.Type, pExpr.Type)
&& IsNullableValueAccess(pCastArgument, pArgument))
{
// We have an implicit conversion of nullable CType to the value CType, generate a convert node for it.
pConversionSource = GenerateValueAccessConversion(pArgument);
}
else
{
ExprCall call = pCastCall as ExprCall;
Expr pUDConversion = call?.PConversions;
if (pUDConversion != null)
{
if (pUDConversion is ExprCall convCall)
{
Expr pUDConversionArgument = convCall.OptionalArguments;
if (IsNullableValueAccess(pUDConversionArgument, pArgument))
{
pConversionSource = GenerateValueAccessConversion(pArgument);
}
else
{
pConversionSource = Visit(pUDConversionArgument);
}
return GenerateConversionWithSource(pConversionSource, pCastCall.Type, call.isChecked());
}
// This can happen if we have a UD conversion from C to, say, int,
// and we have an explicit cast to decimal?. The conversion should
// then be bound as two chained user-defined conversions.
Debug.Assert(pUDConversion is ExprUserDefinedConversion);
// Just recurse.
return GenerateUserDefinedConversion((ExprUserDefinedConversion)pUDConversion, pArgument);
}
pConversionSource = Visit(pCastArgument);
}
return GenerateUserDefinedConversion(pCastArgument, pExpr.Type, pConversionSource, pExpr.UserDefinedCallMethod);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static Expr GenerateParameter(string name, CType CType)
{
SymbolLoader.GetPredefindType(PredefinedType.PT_STRING); // force an ensure state
ExprConstant nameString = ExprFactory.CreateStringConstant(name);
ExprTypeOf pTypeOf = CreateTypeOf(CType);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_PARAMETER, pTypeOf, nameString);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static MethodSymbol GetPreDefMethod(PREDEFMETH pdm) => PredefinedMembers.GetMethod(pdm);
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static ExprTypeOf CreateTypeOf(CType type) => ExprFactory.CreateTypeOf(type);
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static Expr CreateWraps(ExprBoundLambda anonmeth)
{
Expr sequence = null;
for (Symbol sym = anonmeth.ArgumentScope.firstChild; sym != null; sym = sym.nextChild)
{
if (!(sym is LocalVariableSymbol local))
{
continue;
}
Debug.Assert(anonmeth.Expression != null);
Expr create = GenerateParameter(local.name.Text, local.GetType());
local.wrap = ExprFactory.CreateWrap(create);
Expr save = ExprFactory.CreateSave(local.wrap);
if (sequence == null)
{
sequence = save;
}
else
{
sequence = ExprFactory.CreateSequence(sequence, save);
}
}
return sequence;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateConstructor(ExprCall expr)
{
Debug.Assert(expr != null);
Debug.Assert(expr.MethWithInst.Meth().IsConstructor());
Expr constructorInfo = ExprFactory.CreateMethodInfo(expr.MethWithInst);
Expr args = GenerateArgsList(expr.OptionalArguments);
Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEW, constructorInfo, Params);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateArgsList(Expr oldArgs)
{
Expr newArgs = null;
Expr newArgsTail = newArgs;
for (ExpressionIterator it = new ExpressionIterator(oldArgs); !it.AtEnd(); it.MoveNext())
{
Expr oldArg = it.Current();
ExprFactory.AppendItemToList(Visit(oldArg), ref newArgs, ref newArgsTail);
}
return newArgs;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateIndexList(Expr oldIndices)
{
CType intType = SymbolLoader.GetPredefindType(PredefinedType.PT_INT);
Expr newIndices = null;
Expr newIndicesTail = newIndices;
for (ExpressionIterator it = new ExpressionIterator(oldIndices); !it.AtEnd(); it.MoveNext())
{
Expr newIndex = it.Current();
if (newIndex.Type != intType)
{
newIndex = ExprFactory.CreateCast(EXPRFLAG.EXF_INDEXEXPR, intType, newIndex);
newIndex.Flags |= EXPRFLAG.EXF_CHECKOVERFLOW;
}
Expr rewrittenIndex = Visit(newIndex);
ExprFactory.AppendItemToList(rewrittenIndex, ref newIndices, ref newIndicesTail);
}
return newIndices;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static Expr GenerateConstant(Expr expr)
{
EXPRFLAG flags = 0;
AggregateType pObject = SymbolLoader.GetPredefindType(PredefinedType.PT_OBJECT);
if (expr.Type is NullType)
{
ExprTypeOf pTypeOf = CreateTypeOf(pObject);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, expr, pTypeOf);
}
AggregateType stringType = SymbolLoader.GetPredefindType(PredefinedType.PT_STRING);
if (expr.Type != stringType)
{
flags = EXPRFLAG.EXF_BOX;
}
ExprCast cast = ExprFactory.CreateCast(flags, pObject, expr);
ExprTypeOf pTypeOf2 = CreateTypeOf(expr.Type);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, cast, pTypeOf2);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1)
{
MethodSymbol method = GetPreDefMethod(pdm);
// this should be enforced in an earlier pass and the transform pass should not
// be handling this error
if (method == null)
return null;
AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION);
MethWithInst mwi = new MethWithInst(method, expressionType);
ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi);
ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, arg1, pMemGroup, mwi);
call.PredefinedMethod = pdm;
return call;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2)
{
MethodSymbol method = GetPreDefMethod(pdm);
if (method == null)
return null;
AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION);
Expr args = ExprFactory.CreateList(arg1, arg2);
MethWithInst mwi = new MethWithInst(method, expressionType);
ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi);
ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi);
call.PredefinedMethod = pdm;
return call;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2, Expr arg3)
{
MethodSymbol method = GetPreDefMethod(pdm);
if (method == null)
return null;
AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION);
Expr args = ExprFactory.CreateList(arg1, arg2, arg3);
MethWithInst mwi = new MethWithInst(method, expressionType);
ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi);
ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi);
call.PredefinedMethod = pdm;
return call;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2, Expr arg3, Expr arg4)
{
MethodSymbol method = GetPreDefMethod(pdm);
if (method == null)
return null;
AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION);
Expr args = ExprFactory.CreateList(arg1, arg2, arg3, arg4);
MethWithInst mwi = new MethWithInst(method, expressionType);
ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi);
ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi);
call.PredefinedMethod = pdm;
return call;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static ExprArrayInit GenerateParamsArray(Expr args, PredefinedType pt)
{
int parameterCount = ExpressionIterator.Count(args);
AggregateType paramsArrayElementType = SymbolLoader.GetPredefindType(pt);
ArrayType paramsArrayType = TypeManager.GetArray(paramsArrayElementType, 1, true);
ExprConstant paramsArrayArg = ExprFactory.CreateIntegerConstant(parameterCount);
return ExprFactory.CreateArrayInit(paramsArrayType, args, paramsArrayArg, new int[] { parameterCount });
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static void FixLiftedUserDefinedBinaryOperators(ExprBinOp expr, ref Expr pp1, ref Expr pp2)
{
// If we have lifted T1 op T2 to T1? op T2?, and we have an expression T1 op T2? or T1? op T2 then
// we need to ensure that the unlifted actual arguments are promoted to their nullable CType.
Debug.Assert(expr != null);
Debug.Assert(pp1 != null);
Debug.Assert(pp1 != null);
Debug.Assert(pp2 != null);
Debug.Assert(pp2 != null);
MethodSymbol method = expr.UserDefinedCallMethod.Meth();
Expr orig1 = expr.OptionalLeftChild;
Expr orig2 = expr.OptionalRightChild;
Debug.Assert(orig1 != null && orig2 != null);
Expr new1 = pp1;
Expr new2 = pp2;
CType fptype1 = method.Params[0];
CType fptype2 = method.Params[1];
CType aatype1 = orig1.Type;
CType aatype2 = orig2.Type;
// Is the operator even a candidate for lifting?
if (!(fptype1 is AggregateType fat1)
|| !fat1.OwningAggregate.IsValueType()
|| !(fptype2 is AggregateType fat2)
|| !fat2.OwningAggregate.IsValueType())
{
return;
}
CType nubfptype1 = TypeManager.GetNullable(fptype1);
CType nubfptype2 = TypeManager.GetNullable(fptype2);
// If we have null op X, or T1 op T2?, or T1 op null, lift first arg to T1?
if (aatype1 is NullType || aatype1 == fptype1 && (aatype2 == nubfptype2 || aatype2 is NullType))
{
new1 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new1, CreateTypeOf(nubfptype1));
}
// If we have X op null, or T1? op T2, or null op T2, lift second arg to T2?
if (aatype2 is NullType || aatype2 == fptype2 && (aatype1 == nubfptype1 || aatype1 is NullType))
{
new2 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new2, CreateTypeOf(nubfptype2));
}
pp1 = new1;
pp2 = new2;
}
private static bool IsNullableValueType(CType pType) =>
pType is NullableType && pType.StripNubs() is AggregateType agg && agg.OwningAggregate.IsValueType();
private static bool IsNullableValueAccess(Expr pExpr, Expr pObject)
{
Debug.Assert(pExpr != null);
return pExpr is ExprProperty prop && prop.MemberGroup.OptionalObject == pObject && pObject.Type is NullableType;
}
private static bool isEnumToDecimalConversion(CType argtype, CType desttype) =>
argtype.StripNubs().IsEnumType && desttype.StripNubs().IsPredefType(PredefinedType.PT_DECIMAL);
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal sealed class ExpressionTreeRewriter : ExprVisitorBase
{
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
public static ExprBinOp Rewrite(ExprBoundLambda expr) => new ExpressionTreeRewriter().VisitBoundLambda(expr);
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr Dispatch(Expr expr)
{
Debug.Assert(expr != null);
Expr result = base.Dispatch(expr);
if (result == expr)
{
throw Error.InternalCompilerError();
}
return result;
}
/////////////////////////////////////////////////////////////////////////////////
// Statement types.
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitASSIGNMENT(ExprAssignment assignment)
{
Debug.Assert(assignment != null);
// For assignments, we either have a member assignment or an indexed assignment.
//Debug.Assert(assignment.GetLHS().isPROP() || assignment.GetLHS().isFIELD() || assignment.GetLHS().isARRAYINDEX() || assignment.GetLHS().isLOCAL());
Expr lhs;
if (assignment.LHS is ExprProperty prop)
{
if (prop.OptionalArguments == null)
{
// Regular property.
lhs = Visit(prop);
}
else
{
// Indexed assignment. Here we need to find the instance of the object, create the
// PropInfo for the thing, and get the array of expressions that make up the index arguments.
//
// The LHS becomes Expression.Property(instance, indexerInfo, arguments).
Expr instance = Visit(prop.MemberGroup.OptionalObject);
Expr propInfo = ExprFactory.CreatePropertyInfo(prop.PropWithTypeSlot.Prop(), prop.PropWithTypeSlot.Ats);
Expr arguments = GenerateParamsArray(
GenerateArgsList(prop.OptionalArguments),
PredefinedType.PT_EXPRESSION);
lhs = GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, instance, propInfo, arguments);
}
}
else
{
lhs = Visit(assignment.LHS);
}
Expr rhs = Visit(assignment.RHS);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitMULTIGET(ExprMultiGet pExpr)
{
return Visit(pExpr.OptionalMulti.Left);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitMULTI(ExprMulti pExpr)
{
Expr rhs = Visit(pExpr.Operator);
Expr lhs = Visit(pExpr.Left);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs);
}
/////////////////////////////////////////////////////////////////////////////////
// Expression types.
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private ExprBinOp VisitBoundLambda(ExprBoundLambda anonmeth)
{
Debug.Assert(anonmeth != null);
MethodSymbol lambdaMethod = GetPreDefMethod(PREDEFMETH.PM_EXPRESSION_LAMBDA);
AggregateType delegateType = anonmeth.DelegateType;
TypeArray lambdaTypeParams = TypeArray.Allocate(delegateType);
AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION);
MethWithInst mwi = new MethWithInst(lambdaMethod, expressionType, lambdaTypeParams);
Expr createParameters = CreateWraps(anonmeth);
Debug.Assert(createParameters != null);
Debug.Assert(anonmeth.Expression != null);
Expr body = Visit(anonmeth.Expression);
Debug.Assert(anonmeth.ArgumentScope.nextChild == null);
Expr parameters = GenerateParamsArray(null, PredefinedType.PT_PARAMETEREXPRESSION);
Expr args = ExprFactory.CreateList(body, parameters);
CType typeRet = TypeManager.SubstType(mwi.Meth().RetType, mwi.GetType(), mwi.TypeArgs);
ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi);
ExprCall call = ExprFactory.CreateCall(0, typeRet, args, pMemGroup, mwi);
call.PredefinedMethod = PREDEFMETH.PM_EXPRESSION_LAMBDA;
return ExprFactory.CreateSequence(createParameters, call);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitCONSTANT(ExprConstant expr)
{
Debug.Assert(expr != null);
return GenerateConstant(expr);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitLOCAL(ExprLocal local)
{
Debug.Assert(local != null);
Debug.Assert(local.Local.wrap != null);
return local.Local.wrap;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitFIELD(ExprField expr)
{
Debug.Assert(expr != null);
Expr pObject;
if (expr.OptionalObject == null)
{
pObject = ExprFactory.CreateNull();
}
else
{
pObject = Visit(expr.OptionalObject);
}
ExprFieldInfo pFieldInfo = ExprFactory.CreateFieldInfo(expr.FieldWithType.Field(), expr.FieldWithType.GetType());
return GenerateCall(PREDEFMETH.PM_EXPRESSION_FIELD, pObject, pFieldInfo);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitUSERDEFINEDCONVERSION(ExprUserDefinedConversion expr)
{
Debug.Assert(expr != null);
return GenerateUserDefinedConversion(expr, expr.Argument);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitCAST(ExprCast pExpr)
{
Debug.Assert(pExpr != null);
Expr pArgument = pExpr.Argument;
// If we have generated an identity cast or reference cast to a base class
// we can omit the cast.
if (pArgument.Type == pExpr.Type ||
SymbolLoader.IsBaseClassOfClass(pArgument.Type, pExpr.Type) ||
CConversions.FImpRefConv(pArgument.Type, pExpr.Type))
{
return Visit(pArgument);
}
// If we have a cast to PredefinedType.PT_G_EXPRESSION and the thing that we're casting is
// a EXPRBOUNDLAMBDA that is an expression tree, then just visit the expression tree.
if (pExpr.Type != null &&
pExpr.Type.IsPredefType(PredefinedType.PT_G_EXPRESSION) &&
pArgument is ExprBoundLambda)
{
return Visit(pArgument);
}
Expr result = GenerateConversion(pArgument, pExpr.Type, pExpr.isChecked());
if ((pExpr.Flags & EXPRFLAG.EXF_UNBOXRUNTIME) != 0)
{
// Propagate the unbox flag to the call for the ExpressionTreeCallRewriter.
result.Flags |= EXPRFLAG.EXF_UNBOXRUNTIME;
}
return result;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitCONCAT(ExprConcat expr)
{
Debug.Assert(expr != null);
PREDEFMETH pdm;
if (expr.FirstArgument.Type.IsPredefType(PredefinedType.PT_STRING) && expr.SecondArgument.Type.IsPredefType(PredefinedType.PT_STRING))
{
pdm = PREDEFMETH.PM_STRING_CONCAT_STRING_2;
}
else
{
pdm = PREDEFMETH.PM_STRING_CONCAT_OBJECT_2;
}
Expr p1 = Visit(expr.FirstArgument);
Expr p2 = Visit(expr.SecondArgument);
MethodSymbol method = GetPreDefMethod(pdm);
Expr methodInfo = ExprFactory.CreateMethodInfo(method, SymbolLoader.GetPredefindType(PredefinedType.PT_STRING), null);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED, p1, p2, methodInfo);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitBINOP(ExprBinOp expr)
{
Debug.Assert(expr != null);
if (expr.UserDefinedCallMethod != null)
{
return GenerateUserDefinedBinaryOperator(expr);
}
else
{
return GenerateBuiltInBinaryOperator(expr);
}
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitUNARYOP(ExprUnaryOp pExpr)
{
Debug.Assert(pExpr != null);
if (pExpr.UserDefinedCallMethod != null)
{
return GenerateUserDefinedUnaryOperator(pExpr);
}
else
{
return GenerateBuiltInUnaryOperator(pExpr);
}
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitARRAYINDEX(ExprArrayIndex pExpr)
{
Debug.Assert(pExpr != null);
Expr arr = Visit(pExpr.Array);
Expr args = GenerateIndexList(pExpr.Index);
if (args is ExprList)
{
Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2, arr, Params);
}
return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX, arr, args);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitCALL(ExprCall expr)
{
Debug.Assert(expr != null);
switch (expr.NullableCallLiftKind)
{
default:
break;
case NullableCallLiftKind.NullableIntermediateConversion:
case NullableCallLiftKind.NullableConversion:
case NullableCallLiftKind.NullableConversionConstructor:
return GenerateConversion(expr.OptionalArguments, expr.Type, expr.isChecked());
case NullableCallLiftKind.NotLiftedIntermediateConversion:
case NullableCallLiftKind.UserDefinedConversion:
return GenerateUserDefinedConversion(expr.OptionalArguments, expr.Type, expr.MethWithInst);
}
if (expr.MethWithInst.Meth().IsConstructor())
{
return GenerateConstructor(expr);
}
ExprMemberGroup memberGroup = expr.MemberGroup;
if (memberGroup.IsDelegate)
{
return GenerateDelegateInvoke(expr);
}
Expr pObject;
if (expr.MethWithInst.Meth().isStatic || expr.MemberGroup.OptionalObject == null)
{
pObject = ExprFactory.CreateNull();
}
else
{
pObject = expr.MemberGroup.OptionalObject;
// If we have, say, an int? which is the object of a call to ToString
// then we do NOT want to generate ((object)i).ToString() because that
// will convert a null-valued int? to a null object. Rather what we want
// to do is box it to a ValueType and call ValueType.ToString.
//
// To implement this we say that if the object of the call is an implicit boxing cast
// then just generate the object, not the cast. If the cast is explicit in the
// source code then it will be an EXPLICITCAST and we will visit it normally.
//
// It might be better to rewrite the expression tree API so that it
// can handle in the general case all implicit boxing conversions. Right now it
// requires that all arguments to a call that need to be boxed be explicitly boxed.
if (pObject != null && pObject is ExprCast cast && cast.IsBoxingCast)
{
pObject = cast.Argument;
}
pObject = Visit(pObject);
}
Expr methodInfo = ExprFactory.CreateMethodInfo(expr.MethWithInst);
Expr args = GenerateArgsList(expr.OptionalArguments);
Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
PREDEFMETH pdm = PREDEFMETH.PM_EXPRESSION_CALL;
Debug.Assert(!expr.MethWithInst.Meth().isVirtual || expr.MemberGroup.OptionalObject != null);
return GenerateCall(pdm, pObject, methodInfo, Params);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitPROP(ExprProperty expr)
{
Debug.Assert(expr != null);
Expr pObject;
if (expr.PropWithTypeSlot.Prop().isStatic || expr.MemberGroup.OptionalObject == null)
{
pObject = ExprFactory.CreateNull();
}
else
{
pObject = Visit(expr.MemberGroup.OptionalObject);
}
Expr propInfo = ExprFactory.CreatePropertyInfo(expr.PropWithTypeSlot.Prop(), expr.PropWithTypeSlot.GetType());
if (expr.OptionalArguments != null)
{
// It is an indexer property. Turn it into a virtual method call.
Expr args = GenerateArgsList(expr.OptionalArguments);
Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo, Params);
}
return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitARRINIT(ExprArrayInit expr)
{
Debug.Assert(expr != null);
// POSSIBLE ERROR: Multi-d should be an error?
Expr pTypeOf = CreateTypeOf(((ArrayType)expr.Type).ElementType);
Expr args = GenerateArgsList(expr.OptionalArguments);
Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT, pTypeOf, Params);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitZEROINIT(ExprZeroInit expr)
{
Debug.Assert(expr != null);
return GenerateConstant(expr);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
protected override Expr VisitTYPEOF(ExprTypeOf expr)
{
Debug.Assert(expr != null);
return GenerateConstant(expr);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateDelegateInvoke(ExprCall expr)
{
Debug.Assert(expr != null);
ExprMemberGroup memberGroup = expr.MemberGroup;
Debug.Assert(memberGroup.IsDelegate);
Expr oldObject = memberGroup.OptionalObject;
Debug.Assert(oldObject != null);
Expr pObject = Visit(oldObject);
Expr args = GenerateArgsList(expr.OptionalArguments);
Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_INVOKE, pObject, Params);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateBuiltInBinaryOperator(ExprBinOp expr)
{
Debug.Assert(expr != null);
PREDEFMETH pdm = expr.Kind switch
{
ExpressionKind.LeftShirt => PREDEFMETH.PM_EXPRESSION_LEFTSHIFT,
ExpressionKind.RightShift => PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT,
ExpressionKind.BitwiseExclusiveOr => PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR,
ExpressionKind.BitwiseOr => PREDEFMETH.PM_EXPRESSION_OR,
ExpressionKind.BitwiseAnd => PREDEFMETH.PM_EXPRESSION_AND,
ExpressionKind.LogicalAnd => PREDEFMETH.PM_EXPRESSION_ANDALSO,
ExpressionKind.LogicalOr => PREDEFMETH.PM_EXPRESSION_ORELSE,
ExpressionKind.StringEq => PREDEFMETH.PM_EXPRESSION_EQUAL,
ExpressionKind.Eq => PREDEFMETH.PM_EXPRESSION_EQUAL,
ExpressionKind.StringNotEq => PREDEFMETH.PM_EXPRESSION_NOTEQUAL,
ExpressionKind.NotEq => PREDEFMETH.PM_EXPRESSION_NOTEQUAL,
ExpressionKind.GreaterThanOrEqual => PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL,
ExpressionKind.LessThanOrEqual => PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL,
ExpressionKind.LessThan => PREDEFMETH.PM_EXPRESSION_LESSTHAN,
ExpressionKind.GreaterThan => PREDEFMETH.PM_EXPRESSION_GREATERTHAN,
ExpressionKind.Modulo => PREDEFMETH.PM_EXPRESSION_MODULO,
ExpressionKind.Divide => PREDEFMETH.PM_EXPRESSION_DIVIDE,
ExpressionKind.Multiply => expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED : PREDEFMETH.PM_EXPRESSION_MULTIPLY,
ExpressionKind.Subtract => expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED : PREDEFMETH.PM_EXPRESSION_SUBTRACT,
ExpressionKind.Add => expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED : PREDEFMETH.PM_EXPRESSION_ADD,
_ => throw Error.InternalCompilerError(),
};
Expr origL = expr.OptionalLeftChild;
Expr origR = expr.OptionalRightChild;
Debug.Assert(origL != null);
Debug.Assert(origR != null);
CType typeL = origL.Type;
CType typeR = origR.Type;
Expr newL = Visit(origL);
Expr newR = Visit(origR);
bool didEnumConversion = false;
CType convertL = null;
CType convertR = null;
if (typeL.IsEnumType)
{
// We have already inserted casts if not lifted, so we should never see an enum.
Debug.Assert(expr.IsLifted);
convertL = TypeManager.GetNullable(typeL.UnderlyingEnumType);
typeL = convertL;
didEnumConversion = true;
}
else if (typeL is NullableType nubL && nubL.UnderlyingType.IsEnumType)
{
Debug.Assert(expr.IsLifted);
convertL = TypeManager.GetNullable(nubL.UnderlyingType.UnderlyingEnumType);
typeL = convertL;
didEnumConversion = true;
}
if (typeR.IsEnumType)
{
Debug.Assert(expr.IsLifted);
convertR = TypeManager.GetNullable(typeR.UnderlyingEnumType);
typeR = convertR;
didEnumConversion = true;
}
else if (typeR is NullableType nubR && nubR.UnderlyingType.IsEnumType)
{
Debug.Assert(expr.IsLifted);
convertR = TypeManager.GetNullable(nubR.UnderlyingType.UnderlyingEnumType);
typeR = convertR;
didEnumConversion = true;
}
if (typeL is NullableType nubL2 && nubL2.UnderlyingType == typeR)
{
convertR = typeL;
}
if (typeR is NullableType nubR2 && nubR2.UnderlyingType == typeL)
{
convertL = typeR;
}
if (convertL != null)
{
newL = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newL, CreateTypeOf(convertL));
}
if (convertR != null)
{
newR = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newR, CreateTypeOf(convertR));
}
Expr call = GenerateCall(pdm, newL, newR);
if (didEnumConversion && expr.Type.StripNubs().IsEnumType)
{
call = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, CreateTypeOf(expr.Type));
}
return call;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateBuiltInUnaryOperator(ExprUnaryOp expr)
{
Debug.Assert(expr != null);
PREDEFMETH pdm;
switch (expr.Kind)
{
case ExpressionKind.UnaryPlus:
return Visit(expr.Child);
case ExpressionKind.BitwiseNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break;
case ExpressionKind.LogicalNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break;
case ExpressionKind.Negate:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED : PREDEFMETH.PM_EXPRESSION_NEGATE;
break;
default:
throw Error.InternalCompilerError();
}
Expr origOp = expr.Child;
// Such operations are always already casts on operations on casts.
Debug.Assert(!(origOp.Type is NullableType nub) || !nub.UnderlyingType.IsEnumType);
return GenerateCall(pdm, Visit(origOp));
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateUserDefinedBinaryOperator(ExprBinOp expr)
{
Debug.Assert(expr != null);
PREDEFMETH pdm;
switch (expr.Kind)
{
case ExpressionKind.LogicalOr: pdm = PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED; break;
case ExpressionKind.LogicalAnd: pdm = PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED; break;
case ExpressionKind.LeftShirt: pdm = PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED; break;
case ExpressionKind.RightShift: pdm = PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED; break;
case ExpressionKind.BitwiseExclusiveOr: pdm = PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED; break;
case ExpressionKind.BitwiseOr: pdm = PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED; break;
case ExpressionKind.BitwiseAnd: pdm = PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED; break;
case ExpressionKind.Modulo: pdm = PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED; break;
case ExpressionKind.Divide: pdm = PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED; break;
case ExpressionKind.StringEq:
case ExpressionKind.StringNotEq:
case ExpressionKind.DelegateEq:
case ExpressionKind.DelegateNotEq:
case ExpressionKind.Eq:
case ExpressionKind.NotEq:
case ExpressionKind.GreaterThanOrEqual:
case ExpressionKind.GreaterThan:
case ExpressionKind.LessThanOrEqual:
case ExpressionKind.LessThan:
return GenerateUserDefinedComparisonOperator(expr);
case ExpressionKind.DelegateSubtract:
case ExpressionKind.Subtract:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED;
break;
case ExpressionKind.DelegateAdd:
case ExpressionKind.Add:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED;
break;
case ExpressionKind.Multiply:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED;
break;
default:
throw Error.InternalCompilerError();
}
Expr p1 = expr.OptionalLeftChild;
Expr p2 = expr.OptionalRightChild;
Expr udcall = expr.OptionalUserDefinedCall;
if (udcall != null)
{
Debug.Assert(udcall.Kind == ExpressionKind.Call || udcall.Kind == ExpressionKind.UserLogicalOp);
if (udcall is ExprCall ascall)
{
ExprList args = (ExprList)ascall.OptionalArguments;
Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List);
p1 = args.OptionalElement;
p2 = args.OptionalNextListNode;
}
else
{
ExprUserLogicalOp userLogOp = udcall as ExprUserLogicalOp;
Debug.Assert(userLogOp != null);
ExprList args = (ExprList)userLogOp.OperatorCall.OptionalArguments;
Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List);
p1 = ((ExprWrap)args.OptionalElement).OptionalExpression;
p2 = args.OptionalNextListNode;
}
}
p1 = Visit(p1);
p2 = Visit(p2);
FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2);
Expr methodInfo = ExprFactory.CreateMethodInfo(expr.UserDefinedCallMethod);
Expr call = GenerateCall(pdm, p1, p2, methodInfo);
// Delegate add/subtract generates a call to Combine/Remove, which returns System.Delegate,
// not the operand delegate CType. We must cast to the delegate CType.
if (expr.Kind == ExpressionKind.DelegateSubtract || expr.Kind == ExpressionKind.DelegateAdd)
{
Expr pTypeOf = CreateTypeOf(expr.Type);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, pTypeOf);
}
return call;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateUserDefinedUnaryOperator(ExprUnaryOp expr)
{
Debug.Assert(expr != null);
PREDEFMETH pdm;
Expr arg = expr.Child;
ExprCall call = (ExprCall)expr.OptionalUserDefinedCall;
if (call != null)
{
// Use the actual argument of the call; it may contain user-defined
// conversions or be a bound lambda, and that will not be in the original
// argument stashed away in the left child of the operator.
arg = call.OptionalArguments;
}
Debug.Assert(arg != null && arg.Kind != ExpressionKind.List);
switch (expr.Kind)
{
case ExpressionKind.True:
case ExpressionKind.False:
return Visit(call);
case ExpressionKind.UnaryPlus:
pdm = PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED;
break;
case ExpressionKind.BitwiseNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break;
case ExpressionKind.LogicalNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break;
case ExpressionKind.DecimalNegate:
case ExpressionKind.Negate:
pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED;
break;
case ExpressionKind.Inc:
case ExpressionKind.Dec:
case ExpressionKind.DecimalInc:
case ExpressionKind.DecimalDec:
pdm = PREDEFMETH.PM_EXPRESSION_CALL;
break;
default:
throw Error.InternalCompilerError();
}
Expr op = Visit(arg);
Expr methodInfo = ExprFactory.CreateMethodInfo(expr.UserDefinedCallMethod);
if (expr.Kind == ExpressionKind.Inc || expr.Kind == ExpressionKind.Dec ||
expr.Kind == ExpressionKind.DecimalInc || expr.Kind == ExpressionKind.DecimalDec)
{
return GenerateCall(pdm, null, methodInfo, GenerateParamsArray(op, PredefinedType.PT_EXPRESSION));
}
return GenerateCall(pdm, op, methodInfo);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateUserDefinedComparisonOperator(ExprBinOp expr)
{
Debug.Assert(expr != null);
PREDEFMETH pdm = expr.Kind switch
{
ExpressionKind.StringEq => PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED,
ExpressionKind.StringNotEq => PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED,
ExpressionKind.DelegateEq => PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED,
ExpressionKind.DelegateNotEq => PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED,
ExpressionKind.Eq => PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED,
ExpressionKind.NotEq => PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED,
ExpressionKind.LessThanOrEqual => PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED,
ExpressionKind.LessThan => PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED,
ExpressionKind.GreaterThanOrEqual => PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED,
ExpressionKind.GreaterThan => PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED,
_ => throw Error.InternalCompilerError(),
};
Expr p1 = expr.OptionalLeftChild;
Expr p2 = expr.OptionalRightChild;
if (expr.OptionalUserDefinedCall != null)
{
ExprCall udcall = (ExprCall)expr.OptionalUserDefinedCall;
ExprList args = (ExprList)udcall.OptionalArguments;
Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List);
p1 = args.OptionalElement;
p2 = args.OptionalNextListNode;
}
p1 = Visit(p1);
p2 = Visit(p2);
FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2);
Expr lift = ExprFactory.CreateBoolConstant(false); // We never lift to null in C#.
Expr methodInfo = ExprFactory.CreateMethodInfo(expr.UserDefinedCallMethod);
return GenerateCall(pdm, p1, p2, lift, methodInfo);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateConversion(Expr arg, CType CType, bool bChecked) =>
GenerateConversionWithSource(Visit(arg), CType, bChecked || arg.isChecked());
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static Expr GenerateConversionWithSource(Expr pTarget, CType pType, bool bChecked)
{
PREDEFMETH pdm = bChecked ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT;
Expr pTypeOf = CreateTypeOf(pType);
return GenerateCall(pdm, pTarget, pTypeOf);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateValueAccessConversion(Expr pArgument)
{
Debug.Assert(pArgument != null);
CType pStrippedTypeOfArgument = pArgument.Type.StripNubs();
Expr pStrippedTypeExpr = CreateTypeOf(pStrippedTypeOfArgument);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, Visit(pArgument), pStrippedTypeExpr);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateUserDefinedConversion(Expr arg, CType type, MethWithInst method)
{
Expr target = Visit(arg);
return GenerateUserDefinedConversion(arg, type, target, method);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static Expr GenerateUserDefinedConversion(Expr arg, CType CType, Expr target, MethWithInst method)
{
// The user-defined explicit conversion from enum? to decimal or decimal? requires
// that we convert the enum? to its nullable underlying CType.
if (isEnumToDecimalConversion(arg.Type, CType))
{
// Special case: If we have enum? to decimal? then we need to emit
// a conversion from enum? to its nullable underlying CType first.
// This is unfortunate; we ought to reorganize how conversions are
// represented in the Expr tree so that this is more transparent.
// converting an enum to its underlying CType never fails, so no need to check it.
CType underlyingType = arg.Type.StripNubs().UnderlyingEnumType;
CType nullableType = TypeManager.GetNullable(underlyingType);
Expr typeofNubEnum = CreateTypeOf(nullableType);
target = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, target, typeofNubEnum);
}
// If the methodinfo does not return the target CType AND this is not a lifted conversion
// from one value CType to another, then we need to wrap the whole thing in another conversion,
// e.g. if we have a user-defined conversion from int to S? and we have (S)myint, then we need to generate
// Convert(Convert(myint, typeof(S?), op_implicit), typeof(S))
CType pMethodReturnType = TypeManager.SubstType(method.Meth().RetType,
method.GetType(), method.TypeArgs);
bool fDontLiftReturnType = (pMethodReturnType == CType || (IsNullableValueType(arg.Type) && IsNullableValueType(CType)));
Expr typeofInner = CreateTypeOf(fDontLiftReturnType ? CType : pMethodReturnType);
Expr methodInfo = ExprFactory.CreateMethodInfo(method);
PREDEFMETH pdmInner = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED;
Expr callUserDefinedConversion = GenerateCall(pdmInner, target, typeofInner, methodInfo);
if (fDontLiftReturnType)
{
return callUserDefinedConversion;
}
PREDEFMETH pdmOuter = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT;
Expr typeofOuter = CreateTypeOf(CType);
return GenerateCall(pdmOuter, callUserDefinedConversion, typeofOuter);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateUserDefinedConversion(ExprUserDefinedConversion pExpr, Expr pArgument)
{
Expr pCastCall = pExpr.UserDefinedCall;
Expr pCastArgument = pExpr.Argument;
Expr pConversionSource;
if (!isEnumToDecimalConversion(pArgument.Type, pExpr.Type)
&& IsNullableValueAccess(pCastArgument, pArgument))
{
// We have an implicit conversion of nullable CType to the value CType, generate a convert node for it.
pConversionSource = GenerateValueAccessConversion(pArgument);
}
else
{
ExprCall call = pCastCall as ExprCall;
Expr pUDConversion = call?.PConversions;
if (pUDConversion != null)
{
if (pUDConversion is ExprCall convCall)
{
Expr pUDConversionArgument = convCall.OptionalArguments;
if (IsNullableValueAccess(pUDConversionArgument, pArgument))
{
pConversionSource = GenerateValueAccessConversion(pArgument);
}
else
{
pConversionSource = Visit(pUDConversionArgument);
}
return GenerateConversionWithSource(pConversionSource, pCastCall.Type, call.isChecked());
}
// This can happen if we have a UD conversion from C to, say, int,
// and we have an explicit cast to decimal?. The conversion should
// then be bound as two chained user-defined conversions.
Debug.Assert(pUDConversion is ExprUserDefinedConversion);
// Just recurse.
return GenerateUserDefinedConversion((ExprUserDefinedConversion)pUDConversion, pArgument);
}
pConversionSource = Visit(pCastArgument);
}
return GenerateUserDefinedConversion(pCastArgument, pExpr.Type, pConversionSource, pExpr.UserDefinedCallMethod);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static Expr GenerateParameter(string name, CType CType)
{
SymbolLoader.GetPredefindType(PredefinedType.PT_STRING); // force an ensure state
ExprConstant nameString = ExprFactory.CreateStringConstant(name);
ExprTypeOf pTypeOf = CreateTypeOf(CType);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_PARAMETER, pTypeOf, nameString);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static MethodSymbol GetPreDefMethod(PREDEFMETH pdm) => PredefinedMembers.GetMethod(pdm);
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static ExprTypeOf CreateTypeOf(CType type) => ExprFactory.CreateTypeOf(type);
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static Expr CreateWraps(ExprBoundLambda anonmeth)
{
Expr sequence = null;
for (Symbol sym = anonmeth.ArgumentScope.firstChild; sym != null; sym = sym.nextChild)
{
if (!(sym is LocalVariableSymbol local))
{
continue;
}
Debug.Assert(anonmeth.Expression != null);
Expr create = GenerateParameter(local.name.Text, local.GetType());
local.wrap = ExprFactory.CreateWrap(create);
Expr save = ExprFactory.CreateSave(local.wrap);
if (sequence == null)
{
sequence = save;
}
else
{
sequence = ExprFactory.CreateSequence(sequence, save);
}
}
return sequence;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateConstructor(ExprCall expr)
{
Debug.Assert(expr != null);
Debug.Assert(expr.MethWithInst.Meth().IsConstructor());
Expr constructorInfo = ExprFactory.CreateMethodInfo(expr.MethWithInst);
Expr args = GenerateArgsList(expr.OptionalArguments);
Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEW, constructorInfo, Params);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateArgsList(Expr oldArgs)
{
Expr newArgs = null;
Expr newArgsTail = newArgs;
for (ExpressionIterator it = new ExpressionIterator(oldArgs); !it.AtEnd(); it.MoveNext())
{
Expr oldArg = it.Current();
ExprFactory.AppendItemToList(Visit(oldArg), ref newArgs, ref newArgsTail);
}
return newArgs;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private Expr GenerateIndexList(Expr oldIndices)
{
CType intType = SymbolLoader.GetPredefindType(PredefinedType.PT_INT);
Expr newIndices = null;
Expr newIndicesTail = newIndices;
for (ExpressionIterator it = new ExpressionIterator(oldIndices); !it.AtEnd(); it.MoveNext())
{
Expr newIndex = it.Current();
if (newIndex.Type != intType)
{
newIndex = ExprFactory.CreateCast(EXPRFLAG.EXF_INDEXEXPR, intType, newIndex);
newIndex.Flags |= EXPRFLAG.EXF_CHECKOVERFLOW;
}
Expr rewrittenIndex = Visit(newIndex);
ExprFactory.AppendItemToList(rewrittenIndex, ref newIndices, ref newIndicesTail);
}
return newIndices;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static Expr GenerateConstant(Expr expr)
{
EXPRFLAG flags = 0;
AggregateType pObject = SymbolLoader.GetPredefindType(PredefinedType.PT_OBJECT);
if (expr.Type is NullType)
{
ExprTypeOf pTypeOf = CreateTypeOf(pObject);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, expr, pTypeOf);
}
AggregateType stringType = SymbolLoader.GetPredefindType(PredefinedType.PT_STRING);
if (expr.Type != stringType)
{
flags = EXPRFLAG.EXF_BOX;
}
ExprCast cast = ExprFactory.CreateCast(flags, pObject, expr);
ExprTypeOf pTypeOf2 = CreateTypeOf(expr.Type);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, cast, pTypeOf2);
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1)
{
MethodSymbol method = GetPreDefMethod(pdm);
// this should be enforced in an earlier pass and the transform pass should not
// be handling this error
if (method == null)
return null;
AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION);
MethWithInst mwi = new MethWithInst(method, expressionType);
ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi);
ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, arg1, pMemGroup, mwi);
call.PredefinedMethod = pdm;
return call;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2)
{
MethodSymbol method = GetPreDefMethod(pdm);
if (method == null)
return null;
AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION);
Expr args = ExprFactory.CreateList(arg1, arg2);
MethWithInst mwi = new MethWithInst(method, expressionType);
ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi);
ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi);
call.PredefinedMethod = pdm;
return call;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2, Expr arg3)
{
MethodSymbol method = GetPreDefMethod(pdm);
if (method == null)
return null;
AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION);
Expr args = ExprFactory.CreateList(arg1, arg2, arg3);
MethWithInst mwi = new MethWithInst(method, expressionType);
ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi);
ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi);
call.PredefinedMethod = pdm;
return call;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2, Expr arg3, Expr arg4)
{
MethodSymbol method = GetPreDefMethod(pdm);
if (method == null)
return null;
AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION);
Expr args = ExprFactory.CreateList(arg1, arg2, arg3, arg4);
MethWithInst mwi = new MethWithInst(method, expressionType);
ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi);
ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi);
call.PredefinedMethod = pdm;
return call;
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static ExprArrayInit GenerateParamsArray(Expr args, PredefinedType pt)
{
int parameterCount = ExpressionIterator.Count(args);
AggregateType paramsArrayElementType = SymbolLoader.GetPredefindType(pt);
ArrayType paramsArrayType = TypeManager.GetArray(paramsArrayElementType, 1, true);
ExprConstant paramsArrayArg = ExprFactory.CreateIntegerConstant(parameterCount);
return ExprFactory.CreateArrayInit(paramsArrayType, args, paramsArrayArg, new int[] { parameterCount });
}
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
private static void FixLiftedUserDefinedBinaryOperators(ExprBinOp expr, ref Expr pp1, ref Expr pp2)
{
// If we have lifted T1 op T2 to T1? op T2?, and we have an expression T1 op T2? or T1? op T2 then
// we need to ensure that the unlifted actual arguments are promoted to their nullable CType.
Debug.Assert(expr != null);
Debug.Assert(pp1 != null);
Debug.Assert(pp1 != null);
Debug.Assert(pp2 != null);
Debug.Assert(pp2 != null);
MethodSymbol method = expr.UserDefinedCallMethod.Meth();
Expr orig1 = expr.OptionalLeftChild;
Expr orig2 = expr.OptionalRightChild;
Debug.Assert(orig1 != null && orig2 != null);
Expr new1 = pp1;
Expr new2 = pp2;
CType fptype1 = method.Params[0];
CType fptype2 = method.Params[1];
CType aatype1 = orig1.Type;
CType aatype2 = orig2.Type;
// Is the operator even a candidate for lifting?
if (!(fptype1 is AggregateType fat1)
|| !fat1.OwningAggregate.IsValueType()
|| !(fptype2 is AggregateType fat2)
|| !fat2.OwningAggregate.IsValueType())
{
return;
}
CType nubfptype1 = TypeManager.GetNullable(fptype1);
CType nubfptype2 = TypeManager.GetNullable(fptype2);
// If we have null op X, or T1 op T2?, or T1 op null, lift first arg to T1?
if (aatype1 is NullType || aatype1 == fptype1 && (aatype2 == nubfptype2 || aatype2 is NullType))
{
new1 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new1, CreateTypeOf(nubfptype1));
}
// If we have X op null, or T1? op T2, or null op T2, lift second arg to T2?
if (aatype2 is NullType || aatype2 == fptype2 && (aatype1 == nubfptype1 || aatype1 is NullType))
{
new2 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new2, CreateTypeOf(nubfptype2));
}
pp1 = new1;
pp2 = new2;
}
private static bool IsNullableValueType(CType pType) =>
pType is NullableType && pType.StripNubs() is AggregateType agg && agg.OwningAggregate.IsValueType();
private static bool IsNullableValueAccess(Expr pExpr, Expr pObject)
{
Debug.Assert(pExpr != null);
return pExpr is ExprProperty prop && prop.MemberGroup.OptionalObject == pObject && pObject.Type is NullableType;
}
private static bool isEnumToDecimalConversion(CType argtype, CType desttype) =>
argtype.StripNubs().IsEnumType && desttype.StripNubs().IsPredefType(PredefinedType.PT_DECIMAL);
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/jit64/valuetypes/nullable/castclass/generics/castclass-generics040.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
</PropertyGroup>
<ItemGroup>
<Compile Include="castclass-generics040.cs" />
<Compile Include="..\structdef.cs" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
</PropertyGroup>
<ItemGroup>
<Compile Include="castclass-generics040.cs" />
<Compile Include="..\structdef.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/installer/tests/HostActivation.Tests/NativeUnitTests.cs
|
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using FluentAssertions;
using System;
using System.IO;
using Microsoft.DotNet.CoreSetup.Test;
using Microsoft.DotNet.Cli.Build.Framework;
namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.NativeUnitTests
{
public class NativeUnitTests
{
[Fact]
public void Native_Test_Fx_Ver()
{
RepoDirectoriesProvider repoDirectoriesProvider = new RepoDirectoriesProvider();
string testPath = Path.Combine(repoDirectoriesProvider.Artifacts, "corehost_test", RuntimeInformationExtensions.GetExeFileNameForCurrentPlatform("test_fx_ver"));
Command testCommand = Command.Create(testPath);
testCommand
.Execute()
.Should()
.Pass();
}
}
}
|
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using FluentAssertions;
using System;
using System.IO;
using Microsoft.DotNet.CoreSetup.Test;
using Microsoft.DotNet.Cli.Build.Framework;
namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.NativeUnitTests
{
public class NativeUnitTests
{
[Fact]
public void Native_Test_Fx_Ver()
{
RepoDirectoriesProvider repoDirectoriesProvider = new RepoDirectoriesProvider();
string testPath = Path.Combine(repoDirectoriesProvider.Artifacts, "corehost_test", RuntimeInformationExtensions.GetExeFileNameForCurrentPlatform("test_fx_ver"));
Command testCommand = Command.Create(testPath);
testCommand
.Execute()
.Should()
.Pass();
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/nativeaot/SmokeTests/DynamicGenerics/arrays.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
#if INTERNAL_CONTRACTS
using Internal.Runtime.Augments;
#endif
using CoreFXTestLibrary;
using TypeOfRepo;
namespace ArrayTests
{
public class SomeClassForArrayTests
{
public string m_Member;
public SomeClassForArrayTests() { }
public override string ToString() { return m_Member; }
}
public struct GenericStruct<T>
{
public GenericStruct(T t)
{ _val = t; }
T _val;
public override string ToString() { return _val.ToString(); }
}
public class GenericClass<T>
{
public GenericClass(T t)
{ _val = t; }
T _val;
public override string ToString() { return _val.ToString(); }
}
public abstract class SetArrayValBase
{
public abstract void SetVal(object array, object val, params int[] indices);
}
public class SetArrayVal<T> : SetArrayValBase
{
public override void SetVal(object array, object val, params int[] indices)
{
if (indices.Length == 2)
{
((T[,])array)[indices[0], indices[1]] = (T)Activator.CreateInstance(typeof(T), val);
}
else if (indices.Length == 1)
{
((T[])array)[indices[0]] = (T)Activator.CreateInstance(typeof(T), val);
}
}
}
public abstract class IndexOfValBase
{
public abstract int IndexOf(object array, object val);
public abstract void FillArray(object array, object val);
}
public class IndexOfVal<T> : IndexOfValBase where T:struct
{
public override void FillArray(object array, object val)
{
T?[] tArray = (T?[])array;
for (int i = 0; i < tArray.Length; i++)
tArray[i] = (T)val;
}
public override int IndexOf(object array, object val)
{
return Array.IndexOf<T?>((T?[])array, (T)val);
}
}
public struct GenStructImplementsIEquatable<T> : IEquatable<GenStructImplementsIEquatable<T>>
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public bool Equals(GenStructImplementsIEquatable<T> other) { return true; }
public override bool Equals(object other) { return false; }
public override int GetHashCode() { return 0; }
}
public struct GenStructImplementsIEquatable2<T> : IEquatable<GenStructImplementsIEquatable2<T>>
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public bool Equals(GenStructImplementsIEquatable2<T> other) { return true; }
public override bool Equals(object other) { return false; }
public override int GetHashCode() { return 0; }
}
public class ArrayTests
{
static void TestForEach(object[] array)
{
foreach(var item1 in array)
{
foreach (var item2 in (object[])item1)
{
Console.WriteLine(item2);
}
}
}
static void AddItemsToArray(object o)
{
Array array = (Array)o;
array.SetValue(new SomeClassForArrayTests[]
{
new SomeClassForArrayTests{ m_Member = "a1" },
new SomeClassForArrayTests{ m_Member = "a2" },
new SomeClassForArrayTests{ m_Member = "a3" },
}, 0);
array.SetValue(array.GetValue(0), 1);
array.SetValue(new SomeClassForArrayTests[]
{
new SomeClassForArrayTests{ m_Member = "a4" },
new SomeClassForArrayTests{ m_Member = "a5" },
}, 2);
}
public static void DynamicMDArrayTest<T>(Func<T,T> getValue)
{
T lastValue = default(T);
T[,,] array = new T[1, 2, 3];
for (int i = 0; i < 1; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 3; k++)
array[i, j, k] = lastValue = getValue(lastValue);
int index = 0;
string[] expected = new string[] { "10", "20", "30", "40", "50", "60" };
foreach (var item in (IEnumerable)array)
Assert.AreEqual(expected[index++], item.ToString());
}
[TestMethod]
public static void TestArrays()
{
TypeInfo objArray = TypeOf.Object.MakeArrayType().GetTypeInfo();
Assert.AreEqual("System.Object[]", objArray.ToString());
TypeInfo myArray = TypeOf.AT_ArrayTests.MakeArrayType().GetTypeInfo();
Assert.AreEqual("ArrayTests.ArrayTests[]", myArray.ToString());
TypeInfo listArray = TypeOf.List.MakeGenericType(TypeOf.AT_ArrayTests).MakeArrayType().GetTypeInfo();
Assert.AreEqual("System.Collections.Generic.List`1[ArrayTests.ArrayTests][]", listArray.ToString());
// Array types can have multiple EETypes representing them.
// Verify that at the end of the day, all of them are "equal" and castable to each other.
// Same array types created twice using MakeArrayType() to test the caching logic in the runtime.
Type t1 = TypeOf.AT_SomeClassForArrayTests.MakeArrayType().MakeArrayType();
Type t2 = TypeOf.AT_SomeClassForArrayTests.MakeArrayType().MakeArrayType();
Type t3 = TypeOf.AT_SomeClassForArrayTests2;
Type t4 = (new SomeClassForArrayTests[6][]).GetType();
Type t5 = TypeOf.AT_SomeClassForArrayTests1.MakeArrayType();
Type t6 = TypeOf.AT_SomeClassForArrayTests1.MakeArrayType();
Console.WriteLine("{0} == {1}? : {2}", t1, t2, t1 == t2);
Console.WriteLine("{0} == {1}? : {2}", t2, t3, t2 == t3);
Console.WriteLine("{0} == {1}? : {2}", t3, t4, t3 == t4);
Console.WriteLine("{0} == {1}? : {2}", t4, t5, t4 == t5);
Console.WriteLine("{0} == {1}? : {2}", t5, t6, t5 == t6);
Assert.AreEqual(t1, t2);
Assert.AreEqual(t2, t3);
Assert.AreEqual(t3, t4);
Assert.AreEqual(t4, t5);
Assert.AreEqual(t5, t6);
Assert.AreEqual(Activator.CreateInstance(t1, 3).GetType().ToString(), t1.ToString());
Assert.AreEqual(Activator.CreateInstance(t2, 3).GetType().ToString(), t2.ToString());
Assert.AreEqual(Activator.CreateInstance(t3, 3).GetType().ToString(), t3.ToString());
Assert.AreEqual(Activator.CreateInstance(t4, 3).GetType().ToString(), t4.ToString());
Assert.AreEqual(Activator.CreateInstance(t5, 3).GetType().ToString(), t5.ToString());
Assert.AreEqual(Activator.CreateInstance(t6, 3).GetType().ToString(), t6.ToString());
var array = Activator.CreateInstance(t2, 3);
AddItemsToArray(array);
TestForEach((object[])array);
}
[TestMethod]
public static void TestDynamicArrays()
{
#if UNIVERSAL_GENERICS
var typeofGenStructOfString = typeof(GenericStruct<>).MakeGenericType(TypeOf.String);
var typeofSetArrayValGenStructOfString = typeof(SetArrayVal<>).MakeGenericType(typeofGenStructOfString);
var typeofGenStructOfShort = typeof(GenericStruct<>).MakeGenericType(TypeOf.Short);
var typeofSetArrayValGenStructOfShort = typeof(SetArrayVal<>).MakeGenericType(typeofGenStructOfShort);
var typeofGenClassOfString = typeof(GenericClass<>).MakeGenericType(TypeOf.String);
var typeofSetArrayValGenClassOfString = typeof(SetArrayVal<>).MakeGenericType(typeofGenClassOfString);
var typeofGenClassOfShort = typeof(GenericClass<>).MakeGenericType(TypeOf.Short);
var typeofSetArrayValGenClassOfShort = typeof(SetArrayVal<>).MakeGenericType(typeofGenClassOfShort);
#if INTERNAL_CONTRACTS
Assert.IsTrue(RuntimeAugments.IsDynamicType(typeofSetArrayValGenStructOfString.TypeHandle));
Assert.IsTrue(RuntimeAugments.IsDynamicType(typeofSetArrayValGenStructOfShort.TypeHandle));
Assert.IsTrue(RuntimeAugments.IsDynamicType(typeofSetArrayValGenClassOfString.TypeHandle));
Assert.IsTrue(RuntimeAugments.IsDynamicType(typeofSetArrayValGenClassOfShort.TypeHandle));
#endif
Array array_GS_String = Array.CreateInstance(typeofGenStructOfString, 1);
var mdArrayRank2_GS_String = Array.CreateInstance(typeofGenStructOfString, 2, 3);
SetArrayValBase setVal_GS_String = (SetArrayValBase)Activator.CreateInstance(typeofSetArrayValGenStructOfString);
var array_GS_Short = Array.CreateInstance(typeofGenStructOfShort, 4);
var mdArrayRank2_GS_Short = Array.CreateInstance(typeofGenStructOfShort, 5, 6);
SetArrayValBase setVal_GS_Short = (SetArrayValBase)Activator.CreateInstance(typeofSetArrayValGenStructOfShort);
var array_GC_String = Array.CreateInstance(typeofGenClassOfString, 7);
var mdArrayRank2_GC_String = Array.CreateInstance(typeofGenClassOfString, 8, 9);
SetArrayValBase setVal_GC_String = (SetArrayValBase)Activator.CreateInstance(typeofSetArrayValGenClassOfString);
var array_GC_Short = Array.CreateInstance(typeofGenClassOfShort, 10);
var mdArrayRank2_GC_Short = Array.CreateInstance(typeofGenClassOfShort, 11, 12);
SetArrayValBase setVal_GC_Short = (SetArrayValBase)Activator.CreateInstance(typeofSetArrayValGenClassOfShort);
setVal_GS_String.SetVal(array_GS_String, "TestStr", 0);
setVal_GS_String.SetVal(mdArrayRank2_GS_String, "TestStr", 1, 2);
Assert.AreEqual("TestStr", array_GS_String.GetValue(0).ToString());
Assert.AreEqual("TestStr", mdArrayRank2_GS_String.GetValue(1,2).ToString());
setVal_GS_Short.SetVal(array_GS_Short, (short)123, 0);
setVal_GS_Short.SetVal(mdArrayRank2_GS_Short, (short)123, 1, 2);
Assert.AreEqual("123", array_GS_Short.GetValue(0).ToString());
Assert.AreEqual("123", mdArrayRank2_GS_Short.GetValue(1,2).ToString());
setVal_GC_String.SetVal(array_GC_String, "TestStr", 0);
setVal_GC_String.SetVal(mdArrayRank2_GC_String, "TestStr", 1, 2);
Assert.AreEqual("TestStr", array_GC_String.GetValue(0).ToString());
Assert.AreEqual("TestStr", mdArrayRank2_GC_String.GetValue(1,2).ToString());
setVal_GC_Short.SetVal(array_GC_Short, (short)123, 0);
setVal_GC_Short.SetVal(mdArrayRank2_GC_Short, (short)123, 1, 2);
Assert.AreEqual("123", array_GC_Short.GetValue(0).ToString());
Assert.AreEqual("123", mdArrayRank2_GC_Short.GetValue(1,2).ToString());
#endif
}
[TestMethod]
public static void TestMDArrays()
{
#if UNIVERSAL_GENERICS
int[,,] array = new int[1, 2, 3];
int value = 1;
for (int i = 0; i < 1; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 3; k++)
array[i, j, k] = value++;
int index = 0;
string[] expected = new string[] { "1", "2", "3", "4", "5", "6" };
foreach (var item in (IEnumerable)array)
Assert.AreEqual(expected[index++], item.ToString());
MethodInfo mi = typeof(ArrayTests).GetTypeInfo().GetDeclaredMethod("DynamicMDArrayTest").MakeGenericMethod(TypeOf.Short);
mi.Invoke(null, new object[] { new Func<short, short>((val) => (short)(val + 10)) });
#endif
}
[TestMethod]
public static void TestArrayIndexOfNullableStructOfCanon_USG()
{
#if UNIVERSAL_GENERICS
// Test USG Scenario
var typeofGenStructOfString = typeof(GenStructImplementsIEquatable<>).MakeGenericType(TypeOf.String);
var typeofIndexOfValGenStructOfString = typeof(IndexOfVal<>).MakeGenericType(typeofGenStructOfString);
#if INTERNAL_CONTRACTS
Assert.IsTrue(RuntimeAugments.IsDynamicType(typeofGenStructOfString.TypeHandle));
#endif
var typeofNullableGenStructOfString = typeof(Nullable<>).MakeGenericType(typeofGenStructOfString);
Array array_GS_String = Array.CreateInstance(typeofNullableGenStructOfString, 1);
IndexOfValBase indexOf_GS_String = (IndexOfValBase)Activator.CreateInstance(typeofIndexOfValGenStructOfString);
indexOf_GS_String.FillArray(array_GS_String, Activator.CreateInstance(typeofGenStructOfString));
Assert.AreEqual(0, indexOf_GS_String.IndexOf(array_GS_String, Activator.CreateInstance(typeofGenStructOfString)));
#endif
}
[TestMethod]
public static void TestArrayIndexOfNullableStructOfCanon_Canon()
{
// Force canonical implementation Array.IndexOf<GenStructImplementsIEquatable2<__Canon>?>() to be generated and used
GenStructImplementsIEquatable2<object>?[] arr = new GenStructImplementsIEquatable2<object>?[10];
IndexOfValBase indexOfValCanonForcer = new IndexOfVal<GenStructImplementsIEquatable2<object>>();
indexOfValCanonForcer.FillArray(arr, default(GenStructImplementsIEquatable2<object>));
Console.WriteLine(indexOfValCanonForcer.IndexOf(arr, default(GenStructImplementsIEquatable2<object>)));
// Just as in the above USG logic
var typeofGenStructOfString = typeof(GenStructImplementsIEquatable2<>).MakeGenericType(TypeOf.String);
var typeofIndexOfValGenStructOfString = typeof(IndexOfVal<>).MakeGenericType(typeofGenStructOfString);
#if INTERNAL_CONTRACTS
Assert.IsTrue(RuntimeAugments.IsDynamicType(typeofGenStructOfString.TypeHandle));
#endif
var typeofNullableGenStructOfString = typeof(Nullable<>).MakeGenericType(typeofGenStructOfString);
Array array_GS_String = Array.CreateInstance(typeofNullableGenStructOfString, 1);
IndexOfValBase indexOf_GS_String = (IndexOfValBase)Activator.CreateInstance(typeofIndexOfValGenStructOfString);
indexOf_GS_String.FillArray(array_GS_String, Activator.CreateInstance(typeofGenStructOfString));
Assert.AreEqual(0, indexOf_GS_String.IndexOf(array_GS_String, Activator.CreateInstance(typeofGenStructOfString)));
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
#if INTERNAL_CONTRACTS
using Internal.Runtime.Augments;
#endif
using CoreFXTestLibrary;
using TypeOfRepo;
namespace ArrayTests
{
public class SomeClassForArrayTests
{
public string m_Member;
public SomeClassForArrayTests() { }
public override string ToString() { return m_Member; }
}
public struct GenericStruct<T>
{
public GenericStruct(T t)
{ _val = t; }
T _val;
public override string ToString() { return _val.ToString(); }
}
public class GenericClass<T>
{
public GenericClass(T t)
{ _val = t; }
T _val;
public override string ToString() { return _val.ToString(); }
}
public abstract class SetArrayValBase
{
public abstract void SetVal(object array, object val, params int[] indices);
}
public class SetArrayVal<T> : SetArrayValBase
{
public override void SetVal(object array, object val, params int[] indices)
{
if (indices.Length == 2)
{
((T[,])array)[indices[0], indices[1]] = (T)Activator.CreateInstance(typeof(T), val);
}
else if (indices.Length == 1)
{
((T[])array)[indices[0]] = (T)Activator.CreateInstance(typeof(T), val);
}
}
}
public abstract class IndexOfValBase
{
public abstract int IndexOf(object array, object val);
public abstract void FillArray(object array, object val);
}
public class IndexOfVal<T> : IndexOfValBase where T:struct
{
public override void FillArray(object array, object val)
{
T?[] tArray = (T?[])array;
for (int i = 0; i < tArray.Length; i++)
tArray[i] = (T)val;
}
public override int IndexOf(object array, object val)
{
return Array.IndexOf<T?>((T?[])array, (T)val);
}
}
public struct GenStructImplementsIEquatable<T> : IEquatable<GenStructImplementsIEquatable<T>>
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public bool Equals(GenStructImplementsIEquatable<T> other) { return true; }
public override bool Equals(object other) { return false; }
public override int GetHashCode() { return 0; }
}
public struct GenStructImplementsIEquatable2<T> : IEquatable<GenStructImplementsIEquatable2<T>>
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public bool Equals(GenStructImplementsIEquatable2<T> other) { return true; }
public override bool Equals(object other) { return false; }
public override int GetHashCode() { return 0; }
}
public class ArrayTests
{
static void TestForEach(object[] array)
{
foreach(var item1 in array)
{
foreach (var item2 in (object[])item1)
{
Console.WriteLine(item2);
}
}
}
static void AddItemsToArray(object o)
{
Array array = (Array)o;
array.SetValue(new SomeClassForArrayTests[]
{
new SomeClassForArrayTests{ m_Member = "a1" },
new SomeClassForArrayTests{ m_Member = "a2" },
new SomeClassForArrayTests{ m_Member = "a3" },
}, 0);
array.SetValue(array.GetValue(0), 1);
array.SetValue(new SomeClassForArrayTests[]
{
new SomeClassForArrayTests{ m_Member = "a4" },
new SomeClassForArrayTests{ m_Member = "a5" },
}, 2);
}
public static void DynamicMDArrayTest<T>(Func<T,T> getValue)
{
T lastValue = default(T);
T[,,] array = new T[1, 2, 3];
for (int i = 0; i < 1; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 3; k++)
array[i, j, k] = lastValue = getValue(lastValue);
int index = 0;
string[] expected = new string[] { "10", "20", "30", "40", "50", "60" };
foreach (var item in (IEnumerable)array)
Assert.AreEqual(expected[index++], item.ToString());
}
[TestMethod]
public static void TestArrays()
{
TypeInfo objArray = TypeOf.Object.MakeArrayType().GetTypeInfo();
Assert.AreEqual("System.Object[]", objArray.ToString());
TypeInfo myArray = TypeOf.AT_ArrayTests.MakeArrayType().GetTypeInfo();
Assert.AreEqual("ArrayTests.ArrayTests[]", myArray.ToString());
TypeInfo listArray = TypeOf.List.MakeGenericType(TypeOf.AT_ArrayTests).MakeArrayType().GetTypeInfo();
Assert.AreEqual("System.Collections.Generic.List`1[ArrayTests.ArrayTests][]", listArray.ToString());
// Array types can have multiple EETypes representing them.
// Verify that at the end of the day, all of them are "equal" and castable to each other.
// Same array types created twice using MakeArrayType() to test the caching logic in the runtime.
Type t1 = TypeOf.AT_SomeClassForArrayTests.MakeArrayType().MakeArrayType();
Type t2 = TypeOf.AT_SomeClassForArrayTests.MakeArrayType().MakeArrayType();
Type t3 = TypeOf.AT_SomeClassForArrayTests2;
Type t4 = (new SomeClassForArrayTests[6][]).GetType();
Type t5 = TypeOf.AT_SomeClassForArrayTests1.MakeArrayType();
Type t6 = TypeOf.AT_SomeClassForArrayTests1.MakeArrayType();
Console.WriteLine("{0} == {1}? : {2}", t1, t2, t1 == t2);
Console.WriteLine("{0} == {1}? : {2}", t2, t3, t2 == t3);
Console.WriteLine("{0} == {1}? : {2}", t3, t4, t3 == t4);
Console.WriteLine("{0} == {1}? : {2}", t4, t5, t4 == t5);
Console.WriteLine("{0} == {1}? : {2}", t5, t6, t5 == t6);
Assert.AreEqual(t1, t2);
Assert.AreEqual(t2, t3);
Assert.AreEqual(t3, t4);
Assert.AreEqual(t4, t5);
Assert.AreEqual(t5, t6);
Assert.AreEqual(Activator.CreateInstance(t1, 3).GetType().ToString(), t1.ToString());
Assert.AreEqual(Activator.CreateInstance(t2, 3).GetType().ToString(), t2.ToString());
Assert.AreEqual(Activator.CreateInstance(t3, 3).GetType().ToString(), t3.ToString());
Assert.AreEqual(Activator.CreateInstance(t4, 3).GetType().ToString(), t4.ToString());
Assert.AreEqual(Activator.CreateInstance(t5, 3).GetType().ToString(), t5.ToString());
Assert.AreEqual(Activator.CreateInstance(t6, 3).GetType().ToString(), t6.ToString());
var array = Activator.CreateInstance(t2, 3);
AddItemsToArray(array);
TestForEach((object[])array);
}
[TestMethod]
public static void TestDynamicArrays()
{
#if UNIVERSAL_GENERICS
var typeofGenStructOfString = typeof(GenericStruct<>).MakeGenericType(TypeOf.String);
var typeofSetArrayValGenStructOfString = typeof(SetArrayVal<>).MakeGenericType(typeofGenStructOfString);
var typeofGenStructOfShort = typeof(GenericStruct<>).MakeGenericType(TypeOf.Short);
var typeofSetArrayValGenStructOfShort = typeof(SetArrayVal<>).MakeGenericType(typeofGenStructOfShort);
var typeofGenClassOfString = typeof(GenericClass<>).MakeGenericType(TypeOf.String);
var typeofSetArrayValGenClassOfString = typeof(SetArrayVal<>).MakeGenericType(typeofGenClassOfString);
var typeofGenClassOfShort = typeof(GenericClass<>).MakeGenericType(TypeOf.Short);
var typeofSetArrayValGenClassOfShort = typeof(SetArrayVal<>).MakeGenericType(typeofGenClassOfShort);
#if INTERNAL_CONTRACTS
Assert.IsTrue(RuntimeAugments.IsDynamicType(typeofSetArrayValGenStructOfString.TypeHandle));
Assert.IsTrue(RuntimeAugments.IsDynamicType(typeofSetArrayValGenStructOfShort.TypeHandle));
Assert.IsTrue(RuntimeAugments.IsDynamicType(typeofSetArrayValGenClassOfString.TypeHandle));
Assert.IsTrue(RuntimeAugments.IsDynamicType(typeofSetArrayValGenClassOfShort.TypeHandle));
#endif
Array array_GS_String = Array.CreateInstance(typeofGenStructOfString, 1);
var mdArrayRank2_GS_String = Array.CreateInstance(typeofGenStructOfString, 2, 3);
SetArrayValBase setVal_GS_String = (SetArrayValBase)Activator.CreateInstance(typeofSetArrayValGenStructOfString);
var array_GS_Short = Array.CreateInstance(typeofGenStructOfShort, 4);
var mdArrayRank2_GS_Short = Array.CreateInstance(typeofGenStructOfShort, 5, 6);
SetArrayValBase setVal_GS_Short = (SetArrayValBase)Activator.CreateInstance(typeofSetArrayValGenStructOfShort);
var array_GC_String = Array.CreateInstance(typeofGenClassOfString, 7);
var mdArrayRank2_GC_String = Array.CreateInstance(typeofGenClassOfString, 8, 9);
SetArrayValBase setVal_GC_String = (SetArrayValBase)Activator.CreateInstance(typeofSetArrayValGenClassOfString);
var array_GC_Short = Array.CreateInstance(typeofGenClassOfShort, 10);
var mdArrayRank2_GC_Short = Array.CreateInstance(typeofGenClassOfShort, 11, 12);
SetArrayValBase setVal_GC_Short = (SetArrayValBase)Activator.CreateInstance(typeofSetArrayValGenClassOfShort);
setVal_GS_String.SetVal(array_GS_String, "TestStr", 0);
setVal_GS_String.SetVal(mdArrayRank2_GS_String, "TestStr", 1, 2);
Assert.AreEqual("TestStr", array_GS_String.GetValue(0).ToString());
Assert.AreEqual("TestStr", mdArrayRank2_GS_String.GetValue(1,2).ToString());
setVal_GS_Short.SetVal(array_GS_Short, (short)123, 0);
setVal_GS_Short.SetVal(mdArrayRank2_GS_Short, (short)123, 1, 2);
Assert.AreEqual("123", array_GS_Short.GetValue(0).ToString());
Assert.AreEqual("123", mdArrayRank2_GS_Short.GetValue(1,2).ToString());
setVal_GC_String.SetVal(array_GC_String, "TestStr", 0);
setVal_GC_String.SetVal(mdArrayRank2_GC_String, "TestStr", 1, 2);
Assert.AreEqual("TestStr", array_GC_String.GetValue(0).ToString());
Assert.AreEqual("TestStr", mdArrayRank2_GC_String.GetValue(1,2).ToString());
setVal_GC_Short.SetVal(array_GC_Short, (short)123, 0);
setVal_GC_Short.SetVal(mdArrayRank2_GC_Short, (short)123, 1, 2);
Assert.AreEqual("123", array_GC_Short.GetValue(0).ToString());
Assert.AreEqual("123", mdArrayRank2_GC_Short.GetValue(1,2).ToString());
#endif
}
[TestMethod]
public static void TestMDArrays()
{
#if UNIVERSAL_GENERICS
int[,,] array = new int[1, 2, 3];
int value = 1;
for (int i = 0; i < 1; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 3; k++)
array[i, j, k] = value++;
int index = 0;
string[] expected = new string[] { "1", "2", "3", "4", "5", "6" };
foreach (var item in (IEnumerable)array)
Assert.AreEqual(expected[index++], item.ToString());
MethodInfo mi = typeof(ArrayTests).GetTypeInfo().GetDeclaredMethod("DynamicMDArrayTest").MakeGenericMethod(TypeOf.Short);
mi.Invoke(null, new object[] { new Func<short, short>((val) => (short)(val + 10)) });
#endif
}
[TestMethod]
public static void TestArrayIndexOfNullableStructOfCanon_USG()
{
#if UNIVERSAL_GENERICS
// Test USG Scenario
var typeofGenStructOfString = typeof(GenStructImplementsIEquatable<>).MakeGenericType(TypeOf.String);
var typeofIndexOfValGenStructOfString = typeof(IndexOfVal<>).MakeGenericType(typeofGenStructOfString);
#if INTERNAL_CONTRACTS
Assert.IsTrue(RuntimeAugments.IsDynamicType(typeofGenStructOfString.TypeHandle));
#endif
var typeofNullableGenStructOfString = typeof(Nullable<>).MakeGenericType(typeofGenStructOfString);
Array array_GS_String = Array.CreateInstance(typeofNullableGenStructOfString, 1);
IndexOfValBase indexOf_GS_String = (IndexOfValBase)Activator.CreateInstance(typeofIndexOfValGenStructOfString);
indexOf_GS_String.FillArray(array_GS_String, Activator.CreateInstance(typeofGenStructOfString));
Assert.AreEqual(0, indexOf_GS_String.IndexOf(array_GS_String, Activator.CreateInstance(typeofGenStructOfString)));
#endif
}
[TestMethod]
public static void TestArrayIndexOfNullableStructOfCanon_Canon()
{
// Force canonical implementation Array.IndexOf<GenStructImplementsIEquatable2<__Canon>?>() to be generated and used
GenStructImplementsIEquatable2<object>?[] arr = new GenStructImplementsIEquatable2<object>?[10];
IndexOfValBase indexOfValCanonForcer = new IndexOfVal<GenStructImplementsIEquatable2<object>>();
indexOfValCanonForcer.FillArray(arr, default(GenStructImplementsIEquatable2<object>));
Console.WriteLine(indexOfValCanonForcer.IndexOf(arr, default(GenStructImplementsIEquatable2<object>)));
// Just as in the above USG logic
var typeofGenStructOfString = typeof(GenStructImplementsIEquatable2<>).MakeGenericType(TypeOf.String);
var typeofIndexOfValGenStructOfString = typeof(IndexOfVal<>).MakeGenericType(typeofGenStructOfString);
#if INTERNAL_CONTRACTS
Assert.IsTrue(RuntimeAugments.IsDynamicType(typeofGenStructOfString.TypeHandle));
#endif
var typeofNullableGenStructOfString = typeof(Nullable<>).MakeGenericType(typeofGenStructOfString);
Array array_GS_String = Array.CreateInstance(typeofNullableGenStructOfString, 1);
IndexOfValBase indexOf_GS_String = (IndexOfValBase)Activator.CreateInstance(typeofIndexOfValGenStructOfString);
indexOf_GS_String.FillArray(array_GS_String, Activator.CreateInstance(typeofGenStructOfString));
Assert.AreEqual(0, indexOf_GS_String.IndexOf(array_GS_String, Activator.CreateInstance(typeofGenStructOfString)));
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CustomConverterTests/CustomConverterTests.Dynamic.Sample.Tests.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.Tests;
using System.Text.Json.Serialization.Samples;
using Xunit;
using static System.Text.Json.Serialization.Samples.JsonSerializerExtensions;
namespace System.Text.Json.Serialization.Tests
{
public static partial class CustomConverterTests
{
private const string ExpectedDomJson = "{\"MyString\":\"Hello!\",\"MyNull\":null,\"MyBoolean\":false,\"MyArray\":[2,3,42]," +
"\"MyInt\":43,\"MyDateTime\":\"2020-07-08T00:00:00\",\"MyGuid\":\"ed957609-cdfe-412f-88c1-02daca1b4f51\"," +
"\"MyObject\":{\"MyString\":\"Hello!!\"},\"Child\":{\"ChildProp\":1}}";
private enum MyCustomEnum
{
Default = 0,
FortyTwo = 42,
Hello = 77
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void VerifyPrimitives()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
options.Converters.Add(new JsonStringEnumConverter());
dynamic obj = JsonSerializer.Deserialize<dynamic>(DynamicTests.Json, options);
Assert.IsType<JsonDynamicObject>(obj);
// JsonDynamicString has an implicit cast to string.
Assert.IsType<JsonDynamicString>(obj.MyString);
Assert.Equal("Hello", obj.MyString);
// Verify other string-based types.
Assert.Equal(MyCustomEnum.Hello, (MyCustomEnum)obj.MyString);
Assert.Equal(DynamicTests.MyDateTime, (DateTime)obj.MyDateTime);
Assert.Equal(DynamicTests.MyGuid, (Guid)obj.MyGuid);
// JsonDynamicBoolean has an implicit cast to bool.
Assert.IsType<JsonDynamicBoolean>(obj.MyBoolean);
Assert.True(obj.MyBoolean);
// Numbers must specify the type through a cast or assignment.
Assert.IsType<JsonDynamicNumber>(obj.MyInt);
Assert.ThrowsAny<Exception>(() => obj.MyInt == 42L);
Assert.Equal(42L, (long)obj.MyInt);
Assert.Equal((byte)42, (byte)obj.MyInt);
// Verify int-based Enum support through "unknown number type" fallback.
Assert.Equal(MyCustomEnum.FortyTwo, (MyCustomEnum)obj.MyInt);
// Verify floating point.
obj = JsonSerializer.Deserialize<dynamic>("4.2", options);
Assert.IsType<JsonDynamicNumber>(obj);
double dbl = (double)obj;
#if !BUILDING_INBOX_LIBRARY
string temp = dbl.ToString(System.Globalization.CultureInfo.InvariantCulture);
// The reader uses "G17" format which causes temp to be 4.2000000000000002 in this case.
dbl = double.Parse(temp, System.Globalization.CultureInfo.InvariantCulture);
#endif
Assert.Equal(4.2, dbl);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void VerifyArray()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
options.Converters.Add(new JsonStringEnumConverter());
dynamic obj = JsonSerializer.Deserialize<dynamic>(DynamicTests.Json, options);
Assert.IsType<JsonDynamicObject>(obj);
Assert.IsType<JsonDynamicObject>(obj);
Assert.IsType<JsonDynamicArray>(obj.MyArray);
Assert.Equal(2, obj.MyArray.Count);
Assert.Equal(1, (int)obj.MyArray[0]);
Assert.Equal(2, (int)obj.MyArray[1]);
// Ensure we can enumerate
int count = 0;
foreach (long value in obj.MyArray)
{
count++;
}
Assert.Equal(2, count);
// Ensure we can mutate through indexers
obj.MyArray[0] = 10;
Assert.Equal(10, (int)obj.MyArray[0]);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void JsonDynamicTypes_Serialize()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
// Guid (string)
string GuidJson = $"{DynamicTests.MyGuid.ToString("D")}";
string GuidJsonWithQuotes = $"\"{GuidJson}\"";
dynamic dynamicString = new JsonDynamicString(GuidJson, options);
Assert.Equal(DynamicTests.MyGuid, (Guid)dynamicString);
string json = JsonSerializer.Serialize(dynamicString, options);
Assert.Equal(GuidJsonWithQuotes, json);
// char (string)
dynamicString = new JsonDynamicString("a", options);
Assert.Equal('a', (char)dynamicString);
json = JsonSerializer.Serialize(dynamicString, options);
Assert.Equal("\"a\"", json);
// Number (JsonElement)
using (JsonDocument doc = JsonDocument.Parse($"{decimal.MaxValue}"))
{
dynamic dynamicNumber = new JsonDynamicNumber(doc.RootElement, options);
Assert.Equal<decimal>(decimal.MaxValue, (decimal)dynamicNumber);
json = JsonSerializer.Serialize(dynamicNumber, options);
Assert.Equal(decimal.MaxValue.ToString(), json);
}
// Boolean
dynamic dynamicBool = new JsonDynamicBoolean(true, options);
Assert.True(dynamicBool);
json = JsonSerializer.Serialize(dynamicBool, options);
Assert.Equal("true", json);
// Array
dynamic arr = new JsonDynamicArray(options);
arr.Add(1);
arr.Add(2);
json = JsonSerializer.Serialize(arr, options);
Assert.Equal("[1,2]", json);
// Object
dynamic dynamicObject = new JsonDynamicObject(options);
dynamicObject["One"] = 1;
dynamicObject["Two"] = 2;
json = JsonSerializer.Serialize(dynamicObject, options);
JsonTestHelper.AssertJsonEqual("{\"One\":1,\"Two\":2}", json);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void JsonDynamicTypes_Deserialize()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
JsonSerializer.Deserialize<JsonDynamicType>("{}", options);
JsonSerializer.Deserialize<JsonDynamicArray>("[]", options);
JsonSerializer.Deserialize<JsonDynamicBoolean>("true", options);
JsonSerializer.Deserialize<JsonDynamicNumber>("0", options);
JsonSerializer.Deserialize<JsonDynamicNumber>("1.2", options);
JsonSerializer.Deserialize<JsonDynamicObject>("{}", options);
JsonSerializer.Deserialize<JsonDynamicString>("\"str\"", options);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void JsonDynamicTypes_Deserialize_AsObject()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
Assert.IsType<JsonDynamicArray>(JsonSerializer.Deserialize<object>("[]", options));
Assert.IsType<JsonDynamicBoolean>(JsonSerializer.Deserialize<object>("true", options));
Assert.IsType<JsonDynamicNumber>(JsonSerializer.Deserialize<object>("0", options));
Assert.IsType<JsonDynamicNumber>(JsonSerializer.Deserialize<object>("1.2", options));
Assert.IsType<JsonDynamicObject>(JsonSerializer.Deserialize<object>("{}", options));
Assert.IsType<JsonDynamicString>(JsonSerializer.Deserialize<object>("\"str\"", options));
}
/// <summary>
/// Use a mutable DOM with the 'dynamic' keyword.
/// </summary>
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void VerifyMutableDom_UsingDynamicKeyword()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
dynamic obj = JsonSerializer.Deserialize<dynamic>(DynamicTests.Json, options);
Assert.IsType<JsonDynamicObject>(obj);
// Change some primitives.
obj.MyString = "Hello!";
obj.MyBoolean = false;
obj.MyInt = 43;
// Add nested objects.
// Use JsonDynamicObject; ExpandoObject should not be used since it doesn't have the same semantics including
// null handling and case-sensitivity that respects JsonSerializerOptions.PropertyNameCaseInsensitive.
dynamic myObject = new JsonDynamicObject(options);
myObject.MyString = "Hello!!";
obj.MyObject = myObject;
dynamic child = new JsonDynamicObject(options);
child.ChildProp = 1;
obj.Child = child;
// Modify number elements.
dynamic arr = obj["MyArray"];
arr[0] = (int)arr[0] + 1;
arr[1] = (int)arr[1] + 1;
// Add an element.
arr.Add(42);
string json = JsonSerializer.Serialize(obj, options);
JsonTestHelper.AssertJsonEqual(ExpectedDomJson, json);
}
/// <summary>
/// Use a mutable DOM without the 'dynamic' keyword.
/// </summary>
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void VerifyMutableDom_WithoutUsingDynamicKeyword()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
JsonDynamicObject obj = (JsonDynamicObject)JsonSerializer.Deserialize<object>(DynamicTests.Json, options);
// Change some primitives.
obj["MyString"] = "Hello!";
obj["MyBoolean"] = false;
obj["MyInt"] = 43;
// Add nested objects.
obj["MyObject"] = new JsonDynamicObject(options)
{
["MyString"] = "Hello!!"
};
obj["Child"] = new JsonDynamicObject(options)
{
["ChildProp"] = 1
};
// Modify number elements.
var arr = (JsonDynamicArray)obj["MyArray"];
var elem = (JsonDynamicNumber)arr[0];
elem.SetValue(elem.GetValue<int>() + 1);
elem = (JsonDynamicNumber)arr[1];
elem.SetValue(elem.GetValue<int>() + 1);
// Add an element.
arr.Add(42);
string json = JsonSerializer.Serialize(obj, options);
JsonTestHelper.AssertJsonEqual(ExpectedDomJson, json);
}
/// <summary>
/// Use a mutable DOM without the 'dynamic' keyword and use round-trippable values
/// meaning the 'JsonDynamicType' values are used instead of raw primitives.
/// </summary>
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void VerifyMutableDom_WithoutUsingDynamicKeyword_JsonDynamicType()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
JsonDynamicObject obj = (JsonDynamicObject)JsonSerializer.Deserialize<object>(DynamicTests.Json, options);
Verify();
// Verify the values are round-trippable.
((JsonDynamicArray)obj["MyArray"]).RemoveAt(2);
Verify();
void Verify()
{
// Change some primitives.
((JsonDynamicType)obj["MyString"]).SetValue("Hello!");
((JsonDynamicType)obj["MyBoolean"]).SetValue(false);
((JsonDynamicType)obj["MyInt"]).SetValue(43);
// Add nested objects.
obj["MyObject"] = new JsonDynamicObject(options)
{
["MyString"] = new JsonDynamicString("Hello!!", options)
};
obj["Child"] = new JsonDynamicObject(options)
{
["ChildProp"] = new JsonDynamicNumber(1, options)
};
// Modify number elements.
var arr = (JsonDynamicArray)obj["MyArray"];
((JsonDynamicType)arr[0]).SetValue(2);
((JsonDynamicType)arr[1]).SetValue(3);
// Add an element.
arr.Add(new JsonDynamicNumber(42, options));
string json = JsonSerializer.Serialize(obj, options);
JsonTestHelper.AssertJsonEqual(ExpectedDomJson, json);
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void DynamicObject_MissingProperty()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
dynamic obj = JsonSerializer.Deserialize<dynamic>("{}", options);
// We return null here; ExpandoObject throws for missing properties.
Assert.Equal(null, obj.NonExistingProperty);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void DynamicObject_CaseSensitivity()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
dynamic obj = JsonSerializer.Deserialize<dynamic>("{\"MyProperty\":42}", options);
Assert.Equal(42, (int)obj.MyProperty);
Assert.Null(obj.myproperty);
Assert.Null(obj.MYPROPERTY);
options = new JsonSerializerOptions();
options.EnableDynamicTypes();
options.PropertyNameCaseInsensitive = true;
obj = JsonSerializer.Deserialize<dynamic>("{\"MyProperty\":42}", options);
Assert.Equal(42, (int)obj.MyProperty);
Assert.Equal(42, (int)obj.myproperty);
Assert.Equal(42, (int)obj.MYPROPERTY);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void NamingPoliciesAreNotUsed()
{
const string Json = "{\"myProperty\":42}";
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
options.PropertyNamingPolicy = new SimpleSnakeCasePolicy();
dynamic obj = JsonSerializer.Deserialize<dynamic>(Json, options);
string json = JsonSerializer.Serialize(obj, options);
JsonTestHelper.AssertJsonEqual(Json, json);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void NullHandling()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
dynamic obj = JsonSerializer.Deserialize<dynamic>("null", options);
Assert.Null(obj);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void QuotedNumbers_Deserialize()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
options.NumberHandling = JsonNumberHandling.AllowReadingFromString |
JsonNumberHandling.AllowNamedFloatingPointLiterals;
dynamic obj = JsonSerializer.Deserialize<dynamic>("\"42\"", options);
Assert.IsType<JsonDynamicString>(obj);
Assert.Equal(42, (int)obj);
obj = JsonSerializer.Deserialize<dynamic>("\"NaN\"", options);
Assert.IsType<JsonDynamicString>(obj);
using (new ThreadCultureChange(CultureInfo.InvariantCulture))
{
Assert.Equal(double.NaN, (double)obj);
Assert.Equal(float.NaN, (float)obj);
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void QuotedNumbers_Serialize()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
options.NumberHandling = JsonNumberHandling.WriteAsString;
dynamic obj = 42L;
string json = JsonSerializer.Serialize<dynamic>(obj, options);
Assert.Equal("\"42\"", json);
obj = double.NaN;
json = JsonSerializer.Serialize<dynamic>(obj, options);
Assert.Equal("\"NaN\"", json);
}
}
}
|
// 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.Dynamic;
using System.Globalization;
using System.Tests;
using System.Text.Json.Serialization.Samples;
using Xunit;
using static System.Text.Json.Serialization.Samples.JsonSerializerExtensions;
namespace System.Text.Json.Serialization.Tests
{
public static partial class CustomConverterTests
{
private const string ExpectedDomJson = "{\"MyString\":\"Hello!\",\"MyNull\":null,\"MyBoolean\":false,\"MyArray\":[2,3,42]," +
"\"MyInt\":43,\"MyDateTime\":\"2020-07-08T00:00:00\",\"MyGuid\":\"ed957609-cdfe-412f-88c1-02daca1b4f51\"," +
"\"MyObject\":{\"MyString\":\"Hello!!\"},\"Child\":{\"ChildProp\":1}}";
private enum MyCustomEnum
{
Default = 0,
FortyTwo = 42,
Hello = 77
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void VerifyPrimitives()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
options.Converters.Add(new JsonStringEnumConverter());
dynamic obj = JsonSerializer.Deserialize<dynamic>(DynamicTests.Json, options);
Assert.IsType<JsonDynamicObject>(obj);
// JsonDynamicString has an implicit cast to string.
Assert.IsType<JsonDynamicString>(obj.MyString);
Assert.Equal("Hello", obj.MyString);
// Verify other string-based types.
Assert.Equal(MyCustomEnum.Hello, (MyCustomEnum)obj.MyString);
Assert.Equal(DynamicTests.MyDateTime, (DateTime)obj.MyDateTime);
Assert.Equal(DynamicTests.MyGuid, (Guid)obj.MyGuid);
// JsonDynamicBoolean has an implicit cast to bool.
Assert.IsType<JsonDynamicBoolean>(obj.MyBoolean);
Assert.True(obj.MyBoolean);
// Numbers must specify the type through a cast or assignment.
Assert.IsType<JsonDynamicNumber>(obj.MyInt);
Assert.ThrowsAny<Exception>(() => obj.MyInt == 42L);
Assert.Equal(42L, (long)obj.MyInt);
Assert.Equal((byte)42, (byte)obj.MyInt);
// Verify int-based Enum support through "unknown number type" fallback.
Assert.Equal(MyCustomEnum.FortyTwo, (MyCustomEnum)obj.MyInt);
// Verify floating point.
obj = JsonSerializer.Deserialize<dynamic>("4.2", options);
Assert.IsType<JsonDynamicNumber>(obj);
double dbl = (double)obj;
#if !BUILDING_INBOX_LIBRARY
string temp = dbl.ToString(System.Globalization.CultureInfo.InvariantCulture);
// The reader uses "G17" format which causes temp to be 4.2000000000000002 in this case.
dbl = double.Parse(temp, System.Globalization.CultureInfo.InvariantCulture);
#endif
Assert.Equal(4.2, dbl);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void VerifyArray()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
options.Converters.Add(new JsonStringEnumConverter());
dynamic obj = JsonSerializer.Deserialize<dynamic>(DynamicTests.Json, options);
Assert.IsType<JsonDynamicObject>(obj);
Assert.IsType<JsonDynamicObject>(obj);
Assert.IsType<JsonDynamicArray>(obj.MyArray);
Assert.Equal(2, obj.MyArray.Count);
Assert.Equal(1, (int)obj.MyArray[0]);
Assert.Equal(2, (int)obj.MyArray[1]);
// Ensure we can enumerate
int count = 0;
foreach (long value in obj.MyArray)
{
count++;
}
Assert.Equal(2, count);
// Ensure we can mutate through indexers
obj.MyArray[0] = 10;
Assert.Equal(10, (int)obj.MyArray[0]);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void JsonDynamicTypes_Serialize()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
// Guid (string)
string GuidJson = $"{DynamicTests.MyGuid.ToString("D")}";
string GuidJsonWithQuotes = $"\"{GuidJson}\"";
dynamic dynamicString = new JsonDynamicString(GuidJson, options);
Assert.Equal(DynamicTests.MyGuid, (Guid)dynamicString);
string json = JsonSerializer.Serialize(dynamicString, options);
Assert.Equal(GuidJsonWithQuotes, json);
// char (string)
dynamicString = new JsonDynamicString("a", options);
Assert.Equal('a', (char)dynamicString);
json = JsonSerializer.Serialize(dynamicString, options);
Assert.Equal("\"a\"", json);
// Number (JsonElement)
using (JsonDocument doc = JsonDocument.Parse($"{decimal.MaxValue}"))
{
dynamic dynamicNumber = new JsonDynamicNumber(doc.RootElement, options);
Assert.Equal<decimal>(decimal.MaxValue, (decimal)dynamicNumber);
json = JsonSerializer.Serialize(dynamicNumber, options);
Assert.Equal(decimal.MaxValue.ToString(), json);
}
// Boolean
dynamic dynamicBool = new JsonDynamicBoolean(true, options);
Assert.True(dynamicBool);
json = JsonSerializer.Serialize(dynamicBool, options);
Assert.Equal("true", json);
// Array
dynamic arr = new JsonDynamicArray(options);
arr.Add(1);
arr.Add(2);
json = JsonSerializer.Serialize(arr, options);
Assert.Equal("[1,2]", json);
// Object
dynamic dynamicObject = new JsonDynamicObject(options);
dynamicObject["One"] = 1;
dynamicObject["Two"] = 2;
json = JsonSerializer.Serialize(dynamicObject, options);
JsonTestHelper.AssertJsonEqual("{\"One\":1,\"Two\":2}", json);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void JsonDynamicTypes_Deserialize()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
JsonSerializer.Deserialize<JsonDynamicType>("{}", options);
JsonSerializer.Deserialize<JsonDynamicArray>("[]", options);
JsonSerializer.Deserialize<JsonDynamicBoolean>("true", options);
JsonSerializer.Deserialize<JsonDynamicNumber>("0", options);
JsonSerializer.Deserialize<JsonDynamicNumber>("1.2", options);
JsonSerializer.Deserialize<JsonDynamicObject>("{}", options);
JsonSerializer.Deserialize<JsonDynamicString>("\"str\"", options);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void JsonDynamicTypes_Deserialize_AsObject()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
Assert.IsType<JsonDynamicArray>(JsonSerializer.Deserialize<object>("[]", options));
Assert.IsType<JsonDynamicBoolean>(JsonSerializer.Deserialize<object>("true", options));
Assert.IsType<JsonDynamicNumber>(JsonSerializer.Deserialize<object>("0", options));
Assert.IsType<JsonDynamicNumber>(JsonSerializer.Deserialize<object>("1.2", options));
Assert.IsType<JsonDynamicObject>(JsonSerializer.Deserialize<object>("{}", options));
Assert.IsType<JsonDynamicString>(JsonSerializer.Deserialize<object>("\"str\"", options));
}
/// <summary>
/// Use a mutable DOM with the 'dynamic' keyword.
/// </summary>
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void VerifyMutableDom_UsingDynamicKeyword()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
dynamic obj = JsonSerializer.Deserialize<dynamic>(DynamicTests.Json, options);
Assert.IsType<JsonDynamicObject>(obj);
// Change some primitives.
obj.MyString = "Hello!";
obj.MyBoolean = false;
obj.MyInt = 43;
// Add nested objects.
// Use JsonDynamicObject; ExpandoObject should not be used since it doesn't have the same semantics including
// null handling and case-sensitivity that respects JsonSerializerOptions.PropertyNameCaseInsensitive.
dynamic myObject = new JsonDynamicObject(options);
myObject.MyString = "Hello!!";
obj.MyObject = myObject;
dynamic child = new JsonDynamicObject(options);
child.ChildProp = 1;
obj.Child = child;
// Modify number elements.
dynamic arr = obj["MyArray"];
arr[0] = (int)arr[0] + 1;
arr[1] = (int)arr[1] + 1;
// Add an element.
arr.Add(42);
string json = JsonSerializer.Serialize(obj, options);
JsonTestHelper.AssertJsonEqual(ExpectedDomJson, json);
}
/// <summary>
/// Use a mutable DOM without the 'dynamic' keyword.
/// </summary>
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void VerifyMutableDom_WithoutUsingDynamicKeyword()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
JsonDynamicObject obj = (JsonDynamicObject)JsonSerializer.Deserialize<object>(DynamicTests.Json, options);
// Change some primitives.
obj["MyString"] = "Hello!";
obj["MyBoolean"] = false;
obj["MyInt"] = 43;
// Add nested objects.
obj["MyObject"] = new JsonDynamicObject(options)
{
["MyString"] = "Hello!!"
};
obj["Child"] = new JsonDynamicObject(options)
{
["ChildProp"] = 1
};
// Modify number elements.
var arr = (JsonDynamicArray)obj["MyArray"];
var elem = (JsonDynamicNumber)arr[0];
elem.SetValue(elem.GetValue<int>() + 1);
elem = (JsonDynamicNumber)arr[1];
elem.SetValue(elem.GetValue<int>() + 1);
// Add an element.
arr.Add(42);
string json = JsonSerializer.Serialize(obj, options);
JsonTestHelper.AssertJsonEqual(ExpectedDomJson, json);
}
/// <summary>
/// Use a mutable DOM without the 'dynamic' keyword and use round-trippable values
/// meaning the 'JsonDynamicType' values are used instead of raw primitives.
/// </summary>
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void VerifyMutableDom_WithoutUsingDynamicKeyword_JsonDynamicType()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
JsonDynamicObject obj = (JsonDynamicObject)JsonSerializer.Deserialize<object>(DynamicTests.Json, options);
Verify();
// Verify the values are round-trippable.
((JsonDynamicArray)obj["MyArray"]).RemoveAt(2);
Verify();
void Verify()
{
// Change some primitives.
((JsonDynamicType)obj["MyString"]).SetValue("Hello!");
((JsonDynamicType)obj["MyBoolean"]).SetValue(false);
((JsonDynamicType)obj["MyInt"]).SetValue(43);
// Add nested objects.
obj["MyObject"] = new JsonDynamicObject(options)
{
["MyString"] = new JsonDynamicString("Hello!!", options)
};
obj["Child"] = new JsonDynamicObject(options)
{
["ChildProp"] = new JsonDynamicNumber(1, options)
};
// Modify number elements.
var arr = (JsonDynamicArray)obj["MyArray"];
((JsonDynamicType)arr[0]).SetValue(2);
((JsonDynamicType)arr[1]).SetValue(3);
// Add an element.
arr.Add(new JsonDynamicNumber(42, options));
string json = JsonSerializer.Serialize(obj, options);
JsonTestHelper.AssertJsonEqual(ExpectedDomJson, json);
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void DynamicObject_MissingProperty()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
dynamic obj = JsonSerializer.Deserialize<dynamic>("{}", options);
// We return null here; ExpandoObject throws for missing properties.
Assert.Equal(null, obj.NonExistingProperty);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void DynamicObject_CaseSensitivity()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
dynamic obj = JsonSerializer.Deserialize<dynamic>("{\"MyProperty\":42}", options);
Assert.Equal(42, (int)obj.MyProperty);
Assert.Null(obj.myproperty);
Assert.Null(obj.MYPROPERTY);
options = new JsonSerializerOptions();
options.EnableDynamicTypes();
options.PropertyNameCaseInsensitive = true;
obj = JsonSerializer.Deserialize<dynamic>("{\"MyProperty\":42}", options);
Assert.Equal(42, (int)obj.MyProperty);
Assert.Equal(42, (int)obj.myproperty);
Assert.Equal(42, (int)obj.MYPROPERTY);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void NamingPoliciesAreNotUsed()
{
const string Json = "{\"myProperty\":42}";
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
options.PropertyNamingPolicy = new SimpleSnakeCasePolicy();
dynamic obj = JsonSerializer.Deserialize<dynamic>(Json, options);
string json = JsonSerializer.Serialize(obj, options);
JsonTestHelper.AssertJsonEqual(Json, json);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void NullHandling()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
dynamic obj = JsonSerializer.Deserialize<dynamic>("null", options);
Assert.Null(obj);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void QuotedNumbers_Deserialize()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
options.NumberHandling = JsonNumberHandling.AllowReadingFromString |
JsonNumberHandling.AllowNamedFloatingPointLiterals;
dynamic obj = JsonSerializer.Deserialize<dynamic>("\"42\"", options);
Assert.IsType<JsonDynamicString>(obj);
Assert.Equal(42, (int)obj);
obj = JsonSerializer.Deserialize<dynamic>("\"NaN\"", options);
Assert.IsType<JsonDynamicString>(obj);
using (new ThreadCultureChange(CultureInfo.InvariantCulture))
{
Assert.Equal(double.NaN, (double)obj);
Assert.Equal(float.NaN, (float)obj);
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))]
public static void QuotedNumbers_Serialize()
{
var options = new JsonSerializerOptions();
options.EnableDynamicTypes();
options.NumberHandling = JsonNumberHandling.WriteAsString;
dynamic obj = 42L;
string json = JsonSerializer.Serialize<dynamic>(obj, options);
Assert.Equal("\"42\"", json);
obj = double.NaN;
json = JsonSerializer.Serialize<dynamic>(obj, options);
Assert.Equal("\"NaN\"", json);
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/Regression/Dev11/Dev11_646049/Dev11_646049.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</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>PdbOnly</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/Directed/Arrays/Complex2.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
</PropertyGroup>
<ItemGroup>
<Compile Include="complex2.cs" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
</PropertyGroup>
<ItemGroup>
<Compile Include="complex2.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M13-RTM/b91855/b91855.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).cs" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/mono/mono/tests/iface7.cs
|
using System;
namespace TestMono
{
public interface IBase {
int Do();
}
public interface IDerived : IBase {
}
public class Base : IBase {
int IBase.Do() {
return 1 + Do();
}
public virtual int Do() {
return 1;
}
}
public class Derived : Base, IDerived {
}
class Class1
{
static int Main(string[] args)
{
IDerived id = new Derived();
if (id.Do() != 2)
return 1;
IBase ib = (IBase) id;
if (ib.Do() != 2)
return 2;
Derived d = (Derived) id;
if (d.Do() != 1)
return 3;
Base b = (Base) id;
if (b.Do() != 1)
return 4;
return 0;
}
}
}
|
using System;
namespace TestMono
{
public interface IBase {
int Do();
}
public interface IDerived : IBase {
}
public class Base : IBase {
int IBase.Do() {
return 1 + Do();
}
public virtual int Do() {
return 1;
}
}
public class Derived : Base, IDerived {
}
class Class1
{
static int Main(string[] args)
{
IDerived id = new Derived();
if (id.Do() != 2)
return 1;
IBase ib = (IBase) id;
if (ib.Do() != 2)
return 2;
Derived d = (Derived) id;
if (d.Do() != 1)
return 3;
Base b = (Base) id;
if (b.Do() != 1)
return 4;
return 0;
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshalHelpers.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.IL;
using Debug = System.Diagnostics.Debug;
using Internal.IL.Stubs;
using Internal.TypeSystem.Ecma;
namespace Internal.TypeSystem.Interop
{
public static partial class MarshalHelpers
{
internal static TypeDesc GetNativeTypeFromMarshallerKind(TypeDesc type,
MarshallerKind kind,
MarshallerKind elementMarshallerKind,
#if !READYTORUN
InteropStateManager interopStateManager,
#endif
MarshalAsDescriptor marshalAs,
bool isArrayElement = false)
{
TypeSystemContext context = type.Context;
NativeTypeKind nativeType = NativeTypeKind.Default;
if (marshalAs != null)
{
nativeType = isArrayElement ? marshalAs.ArraySubType : marshalAs.Type;
}
switch (kind)
{
case MarshallerKind.BlittableValue:
{
switch (nativeType)
{
case NativeTypeKind.I1:
return context.GetWellKnownType(WellKnownType.SByte);
case NativeTypeKind.U1:
return context.GetWellKnownType(WellKnownType.Byte);
case NativeTypeKind.I2:
return context.GetWellKnownType(WellKnownType.Int16);
case NativeTypeKind.U2:
return context.GetWellKnownType(WellKnownType.UInt16);
case NativeTypeKind.I4:
return context.GetWellKnownType(WellKnownType.Int32);
case NativeTypeKind.U4:
return context.GetWellKnownType(WellKnownType.UInt32);
case NativeTypeKind.I8:
return context.GetWellKnownType(WellKnownType.Int64);
case NativeTypeKind.U8:
return context.GetWellKnownType(WellKnownType.UInt64);
case NativeTypeKind.R4:
return context.GetWellKnownType(WellKnownType.Single);
case NativeTypeKind.R8:
return context.GetWellKnownType(WellKnownType.Double);
default:
return type.UnderlyingType;
}
}
case MarshallerKind.Bool:
return context.GetWellKnownType(WellKnownType.Int32);
case MarshallerKind.CBool:
return context.GetWellKnownType(WellKnownType.Byte);
case MarshallerKind.VariantBool:
return context.GetWellKnownType(WellKnownType.Int16);
case MarshallerKind.Enum:
case MarshallerKind.BlittableStruct:
case MarshallerKind.Decimal:
case MarshallerKind.VoidReturn:
return type;
#if !READYTORUN
case MarshallerKind.Struct:
case MarshallerKind.LayoutClass:
Debug.Assert(interopStateManager is not null, "An InteropStateManager is required to look up the native representation of a non-blittable struct or class with layout.");
return interopStateManager.GetStructMarshallingNativeType((MetadataType)type);
#endif
case MarshallerKind.BlittableStructPtr:
return type.MakePointerType();
case MarshallerKind.HandleRef:
return context.GetWellKnownType(WellKnownType.IntPtr);
case MarshallerKind.UnicodeChar:
if (nativeType == NativeTypeKind.U2)
return context.GetWellKnownType(WellKnownType.UInt16);
else
return context.GetWellKnownType(WellKnownType.Int16);
case MarshallerKind.OleDateTime:
return context.GetWellKnownType(WellKnownType.Double);
case MarshallerKind.FailedTypeLoad:
return context.GetWellKnownType(WellKnownType.IntPtr);
case MarshallerKind.SafeHandle:
case MarshallerKind.CriticalHandle:
return context.GetWellKnownType(WellKnownType.IntPtr);
case MarshallerKind.BSTRString:
case MarshallerKind.UnicodeString:
case MarshallerKind.UnicodeStringBuilder:
return context.GetWellKnownType(WellKnownType.Char).MakePointerType();
case MarshallerKind.AnsiBSTRString:
case MarshallerKind.AnsiString:
case MarshallerKind.AnsiStringBuilder:
case MarshallerKind.UTF8String:
return context.GetWellKnownType(WellKnownType.Byte).MakePointerType();
case MarshallerKind.BlittableArray:
case MarshallerKind.Array:
case MarshallerKind.AnsiCharArray:
{
ArrayType arrayType = type as ArrayType;
Debug.Assert(arrayType != null, "Expecting array");
//
// We need to construct the unsafe array from the right unsafe array element type
//
TypeDesc elementNativeType = GetNativeTypeFromMarshallerKind(
arrayType.ElementType,
elementMarshallerKind,
MarshallerKind.Unknown,
#if !READYTORUN
interopStateManager,
#endif
marshalAs,
isArrayElement: true);
return elementNativeType.MakePointerType();
}
case MarshallerKind.AnsiChar:
return context.GetWellKnownType(WellKnownType.Byte);
case MarshallerKind.FunctionPointer:
return context.GetWellKnownType(WellKnownType.IntPtr);
#if !READYTORUN
case MarshallerKind.ByValUnicodeString:
case MarshallerKind.ByValAnsiString:
{
var inlineArrayCandidate = GetInlineArrayCandidate(context.GetWellKnownType(WellKnownType.Char), elementMarshallerKind, interopStateManager, marshalAs);
return interopStateManager.GetInlineArrayType(inlineArrayCandidate);
}
case MarshallerKind.ByValAnsiCharArray:
case MarshallerKind.ByValArray:
{
ArrayType arrayType = type as ArrayType;
Debug.Assert(arrayType != null, "Expecting array");
var inlineArrayCandidate = GetInlineArrayCandidate(arrayType.ElementType, elementMarshallerKind, interopStateManager, marshalAs);
return interopStateManager.GetInlineArrayType(inlineArrayCandidate);
}
#endif
case MarshallerKind.LayoutClassPtr:
case MarshallerKind.AsAnyA:
case MarshallerKind.AsAnyW:
return context.GetWellKnownType(WellKnownType.IntPtr);
case MarshallerKind.ComInterface:
return context.GetWellKnownType(WellKnownType.IntPtr);
#if !READYTORUN
case MarshallerKind.Variant:
return InteropTypes.GetVariant(context);
case MarshallerKind.CustomMarshaler:
return context.GetWellKnownType(WellKnownType.IntPtr);
#endif
case MarshallerKind.OleCurrency:
return context.GetWellKnownType(WellKnownType.Int64);
case MarshallerKind.Unknown:
default:
throw new NotSupportedException();
}
}
private static bool HasCopyConstructorCustomModifier(int? parameterIndex,
EmbeddedSignatureData[] customModifierData)
{
if (!parameterIndex.HasValue || customModifierData == null)
return false;
string customModifierIndex = MethodSignature.GetIndexOfCustomModifierOnPointedAtTypeByParameterIndex(parameterIndex.Value);
foreach (var customModifier in customModifierData)
{
if (customModifier.kind != EmbeddedSignatureDataKind.RequiredCustomModifier)
continue;
if (customModifier.index != customModifierIndex)
continue;
var customModifierType = customModifier.type as DefType;
if (customModifierType == null)
continue;
if ((customModifierType.Namespace == "System.Runtime.CompilerServices" && customModifierType.Name == "IsCopyConstructed") ||
(customModifierType.Namespace == "Microsoft.VisualC" && customModifierType.Name == "NeedsCopyConstructorModifier"))
{
return true;
}
}
return false;
}
internal static MarshallerKind GetMarshallerKind(
TypeDesc type,
int? parameterIndex,
EmbeddedSignatureData[] customModifierData,
MarshalAsDescriptor marshalAs,
bool isReturn,
bool isAnsi,
MarshallerType marshallerType,
out MarshallerKind elementMarshallerKind)
{
elementMarshallerKind = MarshallerKind.Invalid;
bool isByRef = false;
if (type.IsByRef)
{
isByRef = true;
type = type.GetParameterType();
if (!type.IsPrimitive && type.IsValueType && marshallerType != MarshallerType.Field
&& HasCopyConstructorCustomModifier(parameterIndex, customModifierData))
{
return MarshallerKind.BlittableValueClassWithCopyCtor;
}
// Compat note: CLR allows ref returning blittable structs for IJW
if (isReturn)
return MarshallerKind.Invalid;
}
TypeSystemContext context = type.Context;
NativeTypeKind nativeType = NativeTypeKind.Default;
bool isField = marshallerType == MarshallerType.Field;
if (marshalAs != null)
nativeType = marshalAs.Type;
if (nativeType == NativeTypeKind.CustomMarshaler)
{
if (isField)
return MarshallerKind.FailedTypeLoad;
else
return MarshallerKind.CustomMarshaler;
}
//
// Determine MarshalerKind
//
if (type.IsPrimitive)
{
switch (type.Category)
{
case TypeFlags.Void:
return MarshallerKind.VoidReturn;
case TypeFlags.Boolean:
switch (nativeType)
{
case NativeTypeKind.Default:
case NativeTypeKind.Boolean:
return MarshallerKind.Bool;
case NativeTypeKind.U1:
case NativeTypeKind.I1:
return MarshallerKind.CBool;
case NativeTypeKind.VariantBool:
if (context.Target.IsWindows)
return MarshallerKind.VariantBool;
else
return MarshallerKind.Invalid;
default:
return MarshallerKind.Invalid;
}
case TypeFlags.Char:
switch (nativeType)
{
case NativeTypeKind.I1:
case NativeTypeKind.U1:
return MarshallerKind.AnsiChar;
case NativeTypeKind.I2:
case NativeTypeKind.U2:
return MarshallerKind.UnicodeChar;
case NativeTypeKind.Default:
if (isAnsi)
return MarshallerKind.AnsiChar;
else
return MarshallerKind.UnicodeChar;
default:
return MarshallerKind.Invalid;
}
case TypeFlags.SByte:
case TypeFlags.Byte:
if (nativeType == NativeTypeKind.I1 || nativeType == NativeTypeKind.U1 || nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Int16:
case TypeFlags.UInt16:
if (nativeType == NativeTypeKind.I2 || nativeType == NativeTypeKind.U2 || nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Int32:
case TypeFlags.UInt32:
if (nativeType == NativeTypeKind.I4 || nativeType == NativeTypeKind.U4 || nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Int64:
case TypeFlags.UInt64:
if (nativeType == NativeTypeKind.I8 || nativeType == NativeTypeKind.U8 || nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.IntPtr:
case TypeFlags.UIntPtr:
if (nativeType == NativeTypeKind.SysInt || nativeType == NativeTypeKind.SysUInt || nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Single:
if (nativeType == NativeTypeKind.R4 || nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Double:
if (nativeType == NativeTypeKind.R8 || nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
default:
return MarshallerKind.Invalid;
}
}
else if (type.IsValueType)
{
if (type.IsEnum)
return MarshallerKind.Enum;
if (InteropTypes.IsSystemDateTime(context, type))
{
if (nativeType == NativeTypeKind.Default ||
nativeType == NativeTypeKind.Struct)
return MarshallerKind.OleDateTime;
else
return MarshallerKind.Invalid;
}
else if (InteropTypes.IsHandleRef(context, type))
{
if (nativeType == NativeTypeKind.Default)
return MarshallerKind.HandleRef;
else
return MarshallerKind.Invalid;
}
else if (InteropTypes.IsSystemDecimal(context, type))
{
if (nativeType == NativeTypeKind.Struct || nativeType == NativeTypeKind.Default)
return MarshallerKind.Decimal;
else if (nativeType == NativeTypeKind.LPStruct && !isField)
return MarshallerKind.BlittableStructPtr;
else if (nativeType == NativeTypeKind.Currency)
return MarshallerKind.OleCurrency;
else
return MarshallerKind.Invalid;
}
else if (InteropTypes.IsSystemGuid(context, type))
{
if (nativeType == NativeTypeKind.Struct || nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableStruct;
else if (nativeType == NativeTypeKind.LPStruct && !isField)
return MarshallerKind.BlittableStructPtr;
else
return MarshallerKind.Invalid;
}
else if (InteropTypes.IsSystemArgIterator(context, type))
{
// Don't want to fall through to the blittable/haslayout case
return MarshallerKind.Invalid;
}
bool isBlittable = MarshalUtils.IsBlittableType(type);
// Blittable generics are allowed to be marshalled with the following exceptions:
// * ByReference<T>: This represents an interior pointer and is not actually blittable
// * Nullable<T>: We don't want to be locked into the default behavior as we may want special handling later
// * Vector64<T>: Represents the __m64 ABI primitive which requires currently unimplemented handling
// * Vector128<T>: Represents the __m128 ABI primitive which requires currently unimplemented handling
// * Vector256<T>: Represents the __m256 ABI primitive which requires currently unimplemented handling
// * Vector<T>: Has a variable size (either __m128 or __m256) and isn't readily usable for interop scenarios
// We can't block these types for field scenarios for back-compat reasons.
if (type.HasInstantiation && !isField && (!isBlittable
|| InteropTypes.IsSystemByReference(context, type)
|| InteropTypes.IsSystemSpan(context, type)
|| InteropTypes.IsSystemReadOnlySpan(context, type)
|| InteropTypes.IsSystemNullable(context, type)
|| InteropTypes.IsSystemRuntimeIntrinsicsVector64T(context, type)
|| InteropTypes.IsSystemRuntimeIntrinsicsVector128T(context, type)
|| InteropTypes.IsSystemRuntimeIntrinsicsVector256T(context, type)
|| InteropTypes.IsSystemNumericsVectorT(context, type)))
{
// Generic types cannot be marshaled.
return MarshallerKind.Invalid;
}
if (isBlittable)
{
if (nativeType != NativeTypeKind.Default && nativeType != NativeTypeKind.Struct)
return MarshallerKind.Invalid;
return MarshallerKind.BlittableStruct;
}
else if (((MetadataType)type).HasLayout())
{
if (nativeType != NativeTypeKind.Default && nativeType != NativeTypeKind.Struct)
return MarshallerKind.Invalid;
return MarshallerKind.Struct;
}
else
{
return MarshallerKind.Invalid;
}
}
else if (type.IsSzArray)
{
#if READYTORUN
// We don't want the additional test/maintenance cost of this in R2R.
if (isByRef)
return MarshallerKind.Invalid;
#else
_ = isByRef;
#endif
if (nativeType == NativeTypeKind.Default)
nativeType = NativeTypeKind.Array;
switch (nativeType)
{
case NativeTypeKind.Array:
{
if (isField)
return MarshallerKind.FailedTypeLoad;
var arrayType = (ArrayType)type;
elementMarshallerKind = GetArrayElementMarshallerKind(
arrayType,
marshalAs,
isAnsi);
// If element is invalid type, the array itself is invalid
if (elementMarshallerKind == MarshallerKind.Invalid)
return MarshallerKind.Invalid;
if (elementMarshallerKind == MarshallerKind.AnsiChar)
return MarshallerKind.AnsiCharArray;
else if (elementMarshallerKind == MarshallerKind.UnicodeChar // Arrays of unicode char should be marshalled as blittable arrays
|| elementMarshallerKind == MarshallerKind.Enum
|| elementMarshallerKind == MarshallerKind.BlittableValue)
return MarshallerKind.BlittableArray;
else
return MarshallerKind.Array;
}
case NativeTypeKind.ByValArray: // fix sized array
{
var arrayType = (ArrayType)type;
elementMarshallerKind = GetArrayElementMarshallerKind(
arrayType,
marshalAs,
isAnsi);
// If element is invalid type, the array itself is invalid
if (elementMarshallerKind == MarshallerKind.Invalid)
return MarshallerKind.Invalid;
if (elementMarshallerKind == MarshallerKind.AnsiChar)
return MarshallerKind.ByValAnsiCharArray;
else
return MarshallerKind.ByValArray;
}
default:
return MarshallerKind.Invalid;
}
}
else if (type.IsPointer)
{
if (nativeType == NativeTypeKind.Default)
{
var pointedAtType = type.GetParameterType();
if (!pointedAtType.IsPrimitive && !type.IsEnum && marshallerType != MarshallerType.Field
&& HasCopyConstructorCustomModifier(parameterIndex, customModifierData))
{
return MarshallerKind.BlittableValueClassWithCopyCtor;
}
return MarshallerKind.BlittableValue;
}
else
return MarshallerKind.Invalid;
}
else if (type.IsFunctionPointer)
{
if (nativeType == NativeTypeKind.Func || nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
}
else if (type.IsDelegate || InteropTypes.IsSystemDelegate(context, type) || InteropTypes.IsSystemMulticastDelegate(context, type))
{
if (type.HasInstantiation)
{
// Generic types cannot be marshaled.
return MarshallerKind.Invalid;
}
if (nativeType == NativeTypeKind.Default || nativeType == NativeTypeKind.Func)
return MarshallerKind.FunctionPointer;
else
return MarshallerKind.Invalid;
}
else if (type.IsString)
{
switch (nativeType)
{
case NativeTypeKind.LPWStr:
return MarshallerKind.UnicodeString;
case NativeTypeKind.LPStr:
return MarshallerKind.AnsiString;
case NativeTypeKind.LPUTF8Str:
return MarshallerKind.UTF8String;
case NativeTypeKind.LPTStr:
return MarshallerKind.UnicodeString;
case NativeTypeKind.ByValTStr:
if (isAnsi)
{
elementMarshallerKind = MarshallerKind.AnsiChar;
return MarshallerKind.ByValAnsiString;
}
else
{
elementMarshallerKind = MarshallerKind.UnicodeChar;
return MarshallerKind.ByValUnicodeString;
}
case NativeTypeKind.TBStr:
case NativeTypeKind.BStr:
return MarshallerKind.BSTRString;
case NativeTypeKind.AnsiBStr:
return MarshallerKind.AnsiBSTRString;
case NativeTypeKind.CustomMarshaler:
return MarshallerKind.CustomMarshaler;
case NativeTypeKind.Default:
if (isAnsi)
return MarshallerKind.AnsiString;
else
return MarshallerKind.UnicodeString;
default:
return MarshallerKind.Invalid;
}
}
else if (type.IsObject)
{
if (nativeType == NativeTypeKind.AsAny && isField)
return MarshallerKind.FailedTypeLoad;
if (nativeType == NativeTypeKind.AsAny)
return isAnsi ? MarshallerKind.AsAnyA : MarshallerKind.AsAnyW;
else
if (context.Target.IsWindows)
{
if ((isField && nativeType == NativeTypeKind.Default)
|| nativeType == NativeTypeKind.Intf
|| nativeType == NativeTypeKind.IUnknown)
return MarshallerKind.ComInterface;
else
return MarshallerKind.Variant;
}
else
return MarshallerKind.Invalid;
}
else if (InteropTypes.IsStringBuilder(context, type))
{
switch (nativeType)
{
case NativeTypeKind.Default:
if (isAnsi)
{
return MarshallerKind.AnsiStringBuilder;
}
else
{
return MarshallerKind.UnicodeStringBuilder;
}
case NativeTypeKind.LPStr:
return MarshallerKind.AnsiStringBuilder;
case NativeTypeKind.LPWStr:
return MarshallerKind.UnicodeStringBuilder;
default:
return MarshallerKind.Invalid;
}
}
else if (InteropTypes.IsSafeHandle(context, type))
{
if (nativeType == NativeTypeKind.Default)
return MarshallerKind.SafeHandle;
else
return MarshallerKind.Invalid;
}
else if (InteropTypes.IsCriticalHandle(context, type))
{
if (nativeType == NativeTypeKind.Default)
return MarshallerKind.CriticalHandle;
else
return MarshallerKind.Invalid;
}
else if (type is MetadataType mdType && mdType.HasLayout())
{
if (type.HasInstantiation)
{
// Generic types cannot be marshaled.
return MarshallerKind.Invalid;
}
if (!isField && nativeType == NativeTypeKind.Default || nativeType == NativeTypeKind.LPStruct)
return MarshallerKind.LayoutClassPtr;
else if (isField && (nativeType == NativeTypeKind.Default || nativeType == NativeTypeKind.Struct))
return MarshallerKind.LayoutClass;
else
return MarshallerKind.Invalid;
}
else if (type.IsInterface)
{
if (context.Target.IsWindows)
return MarshallerKind.ComInterface;
else
return MarshallerKind.Invalid;
}
else
{
return MarshallerKind.Invalid;
}
}
private static MarshallerKind GetArrayElementMarshallerKind(
ArrayType arrayType,
MarshalAsDescriptor marshalAs,
bool isAnsi)
{
TypeDesc elementType = arrayType.ElementType;
NativeTypeKind nativeType = NativeTypeKind.Default;
TypeSystemContext context = arrayType.Context;
if (marshalAs != null)
nativeType = (NativeTypeKind)marshalAs.ArraySubType;
if (elementType.IsPrimitive)
{
switch (elementType.Category)
{
case TypeFlags.Char:
switch (nativeType)
{
case NativeTypeKind.I1:
case NativeTypeKind.U1:
return MarshallerKind.AnsiChar;
case NativeTypeKind.I2:
case NativeTypeKind.U2:
return MarshallerKind.UnicodeChar;
default:
if (isAnsi)
return MarshallerKind.AnsiChar;
else
return MarshallerKind.UnicodeChar;
}
case TypeFlags.Boolean:
switch (nativeType)
{
case NativeTypeKind.Boolean:
return MarshallerKind.Bool;
case NativeTypeKind.I1:
case NativeTypeKind.U1:
return MarshallerKind.CBool;
case NativeTypeKind.Default:
default:
return MarshallerKind.Bool;
}
case TypeFlags.IntPtr:
case TypeFlags.UIntPtr:
return MarshallerKind.BlittableValue;
case TypeFlags.Void:
return MarshallerKind.Invalid;
case TypeFlags.SByte:
case TypeFlags.Int16:
case TypeFlags.Int32:
case TypeFlags.Int64:
case TypeFlags.Byte:
case TypeFlags.UInt16:
case TypeFlags.UInt32:
case TypeFlags.UInt64:
case TypeFlags.Single:
case TypeFlags.Double:
return MarshallerKind.BlittableValue;
default:
return MarshallerKind.Invalid;
}
}
else if (elementType.IsValueType)
{
if (elementType.IsEnum)
return MarshallerKind.Enum;
if (InteropTypes.IsSystemDecimal(context, elementType))
{
switch (nativeType)
{
case NativeTypeKind.Default:
case NativeTypeKind.Struct:
return MarshallerKind.Decimal;
case NativeTypeKind.LPStruct:
return MarshallerKind.BlittableStructPtr;
default:
return MarshallerKind.Invalid;
}
}
else if (InteropTypes.IsSystemGuid(context, elementType))
{
switch (nativeType)
{
case NativeTypeKind.Default:
case NativeTypeKind.Struct:
return MarshallerKind.BlittableValue;
case NativeTypeKind.LPStruct:
return MarshallerKind.BlittableStructPtr;
default:
return MarshallerKind.Invalid;
}
}
else if (InteropTypes.IsSystemDateTime(context, elementType))
{
if (nativeType == NativeTypeKind.Default ||
nativeType == NativeTypeKind.Struct)
{
return MarshallerKind.OleDateTime;
}
else
{
return MarshallerKind.Invalid;
}
}
else if (InteropTypes.IsHandleRef(context, elementType))
{
if (nativeType == NativeTypeKind.Default)
return MarshallerKind.HandleRef;
else
return MarshallerKind.Invalid;
}
else
{
if (MarshalUtils.IsBlittableType(elementType))
{
switch (nativeType)
{
case NativeTypeKind.Default:
case NativeTypeKind.Struct:
return MarshallerKind.BlittableStruct;
default:
return MarshallerKind.Invalid;
}
}
else
{
// TODO: Differentiate between struct and Union, we only need to support struct not union here
return MarshallerKind.Struct;
}
}
}
else if (elementType.IsPointer || elementType.IsFunctionPointer)
{
if (nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
}
else if (elementType.IsString)
{
switch (nativeType)
{
case NativeTypeKind.Default:
if (isAnsi)
return MarshallerKind.AnsiString;
else
return MarshallerKind.UnicodeString;
case NativeTypeKind.LPStr:
return MarshallerKind.AnsiString;
case NativeTypeKind.LPWStr:
return MarshallerKind.UnicodeString;
case NativeTypeKind.LPUTF8Str:
return MarshallerKind.UTF8String;
case NativeTypeKind.BStr:
case NativeTypeKind.TBStr:
return MarshallerKind.BSTRString;
case NativeTypeKind.AnsiBStr:
return MarshallerKind.AnsiBSTRString;
case NativeTypeKind.CustomMarshaler:
return MarshallerKind.CustomMarshaler;
default:
return MarshallerKind.Invalid;
}
}
// else if (elementType.IsObject)
// {
// if (nativeType == NativeTypeKind.Invalid)
// return MarshallerKind.Variant;
// else
// return MarshallerKind.Invalid;
// }
else
{
return MarshallerKind.Invalid;
}
}
internal static MarshallerKind GetDisabledMarshallerKind(
TypeDesc type)
{
// Get the underlying type for enum types.
TypeDesc underlyingType = type.UnderlyingType;
if (underlyingType.Category == TypeFlags.Void)
{
return MarshallerKind.VoidReturn;
}
else if (underlyingType.IsByRef)
{
// Managed refs are not supported when runtime marshalling is disabled.
return MarshallerKind.Invalid;
}
else if (underlyingType.IsPrimitive)
{
return MarshallerKind.BlittableValue;
}
else if (underlyingType.IsPointer || underlyingType.IsFunctionPointer)
{
return MarshallerKind.BlittableValue;
}
else if (underlyingType.IsValueType)
{
var defType = (DefType)underlyingType;
if (!defType.ContainsGCPointers && !defType.IsAutoLayoutOrHasAutoLayoutFields)
{
return MarshallerKind.BlittableValue;
}
}
return MarshallerKind.Invalid;
}
internal static bool ShouldCheckForPendingException(TargetDetails target, PInvokeMetadata metadata)
{
if (!target.IsOSX)
return false;
const string ObjectiveCLibrary = "/usr/lib/libobjc.dylib";
const string ObjectiveCMsgSend = "objc_msgSend";
// This is for the objc_msgSend suite of functions.
// objc_msgSend
// objc_msgSend_fpret
// objc_msgSend_stret
// objc_msgSendSuper
// objc_msgSendSuper_stret
return metadata.Module.Equals(ObjectiveCLibrary)
&& metadata.Name.StartsWith(ObjectiveCMsgSend);
}
public static bool IsRuntimeMarshallingEnabled(ModuleDesc module)
{
return module.Assembly is not EcmaAssembly assembly || !assembly.HasAssemblyCustomAttribute("System.Runtime.CompilerServices", "DisableRuntimeMarshallingAttribute");
}
}
}
|
// 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.IL;
using Debug = System.Diagnostics.Debug;
using Internal.IL.Stubs;
using Internal.TypeSystem.Ecma;
namespace Internal.TypeSystem.Interop
{
public static partial class MarshalHelpers
{
internal static TypeDesc GetNativeTypeFromMarshallerKind(TypeDesc type,
MarshallerKind kind,
MarshallerKind elementMarshallerKind,
#if !READYTORUN
InteropStateManager interopStateManager,
#endif
MarshalAsDescriptor marshalAs,
bool isArrayElement = false)
{
TypeSystemContext context = type.Context;
NativeTypeKind nativeType = NativeTypeKind.Default;
if (marshalAs != null)
{
nativeType = isArrayElement ? marshalAs.ArraySubType : marshalAs.Type;
}
switch (kind)
{
case MarshallerKind.BlittableValue:
{
switch (nativeType)
{
case NativeTypeKind.I1:
return context.GetWellKnownType(WellKnownType.SByte);
case NativeTypeKind.U1:
return context.GetWellKnownType(WellKnownType.Byte);
case NativeTypeKind.I2:
return context.GetWellKnownType(WellKnownType.Int16);
case NativeTypeKind.U2:
return context.GetWellKnownType(WellKnownType.UInt16);
case NativeTypeKind.I4:
return context.GetWellKnownType(WellKnownType.Int32);
case NativeTypeKind.U4:
return context.GetWellKnownType(WellKnownType.UInt32);
case NativeTypeKind.I8:
return context.GetWellKnownType(WellKnownType.Int64);
case NativeTypeKind.U8:
return context.GetWellKnownType(WellKnownType.UInt64);
case NativeTypeKind.R4:
return context.GetWellKnownType(WellKnownType.Single);
case NativeTypeKind.R8:
return context.GetWellKnownType(WellKnownType.Double);
default:
return type.UnderlyingType;
}
}
case MarshallerKind.Bool:
return context.GetWellKnownType(WellKnownType.Int32);
case MarshallerKind.CBool:
return context.GetWellKnownType(WellKnownType.Byte);
case MarshallerKind.VariantBool:
return context.GetWellKnownType(WellKnownType.Int16);
case MarshallerKind.Enum:
case MarshallerKind.BlittableStruct:
case MarshallerKind.Decimal:
case MarshallerKind.VoidReturn:
return type;
#if !READYTORUN
case MarshallerKind.Struct:
case MarshallerKind.LayoutClass:
Debug.Assert(interopStateManager is not null, "An InteropStateManager is required to look up the native representation of a non-blittable struct or class with layout.");
return interopStateManager.GetStructMarshallingNativeType((MetadataType)type);
#endif
case MarshallerKind.BlittableStructPtr:
return type.MakePointerType();
case MarshallerKind.HandleRef:
return context.GetWellKnownType(WellKnownType.IntPtr);
case MarshallerKind.UnicodeChar:
if (nativeType == NativeTypeKind.U2)
return context.GetWellKnownType(WellKnownType.UInt16);
else
return context.GetWellKnownType(WellKnownType.Int16);
case MarshallerKind.OleDateTime:
return context.GetWellKnownType(WellKnownType.Double);
case MarshallerKind.FailedTypeLoad:
return context.GetWellKnownType(WellKnownType.IntPtr);
case MarshallerKind.SafeHandle:
case MarshallerKind.CriticalHandle:
return context.GetWellKnownType(WellKnownType.IntPtr);
case MarshallerKind.BSTRString:
case MarshallerKind.UnicodeString:
case MarshallerKind.UnicodeStringBuilder:
return context.GetWellKnownType(WellKnownType.Char).MakePointerType();
case MarshallerKind.AnsiBSTRString:
case MarshallerKind.AnsiString:
case MarshallerKind.AnsiStringBuilder:
case MarshallerKind.UTF8String:
return context.GetWellKnownType(WellKnownType.Byte).MakePointerType();
case MarshallerKind.BlittableArray:
case MarshallerKind.Array:
case MarshallerKind.AnsiCharArray:
{
ArrayType arrayType = type as ArrayType;
Debug.Assert(arrayType != null, "Expecting array");
//
// We need to construct the unsafe array from the right unsafe array element type
//
TypeDesc elementNativeType = GetNativeTypeFromMarshallerKind(
arrayType.ElementType,
elementMarshallerKind,
MarshallerKind.Unknown,
#if !READYTORUN
interopStateManager,
#endif
marshalAs,
isArrayElement: true);
return elementNativeType.MakePointerType();
}
case MarshallerKind.AnsiChar:
return context.GetWellKnownType(WellKnownType.Byte);
case MarshallerKind.FunctionPointer:
return context.GetWellKnownType(WellKnownType.IntPtr);
#if !READYTORUN
case MarshallerKind.ByValUnicodeString:
case MarshallerKind.ByValAnsiString:
{
var inlineArrayCandidate = GetInlineArrayCandidate(context.GetWellKnownType(WellKnownType.Char), elementMarshallerKind, interopStateManager, marshalAs);
return interopStateManager.GetInlineArrayType(inlineArrayCandidate);
}
case MarshallerKind.ByValAnsiCharArray:
case MarshallerKind.ByValArray:
{
ArrayType arrayType = type as ArrayType;
Debug.Assert(arrayType != null, "Expecting array");
var inlineArrayCandidate = GetInlineArrayCandidate(arrayType.ElementType, elementMarshallerKind, interopStateManager, marshalAs);
return interopStateManager.GetInlineArrayType(inlineArrayCandidate);
}
#endif
case MarshallerKind.LayoutClassPtr:
case MarshallerKind.AsAnyA:
case MarshallerKind.AsAnyW:
return context.GetWellKnownType(WellKnownType.IntPtr);
case MarshallerKind.ComInterface:
return context.GetWellKnownType(WellKnownType.IntPtr);
#if !READYTORUN
case MarshallerKind.Variant:
return InteropTypes.GetVariant(context);
case MarshallerKind.CustomMarshaler:
return context.GetWellKnownType(WellKnownType.IntPtr);
#endif
case MarshallerKind.OleCurrency:
return context.GetWellKnownType(WellKnownType.Int64);
case MarshallerKind.Unknown:
default:
throw new NotSupportedException();
}
}
private static bool HasCopyConstructorCustomModifier(int? parameterIndex,
EmbeddedSignatureData[] customModifierData)
{
if (!parameterIndex.HasValue || customModifierData == null)
return false;
string customModifierIndex = MethodSignature.GetIndexOfCustomModifierOnPointedAtTypeByParameterIndex(parameterIndex.Value);
foreach (var customModifier in customModifierData)
{
if (customModifier.kind != EmbeddedSignatureDataKind.RequiredCustomModifier)
continue;
if (customModifier.index != customModifierIndex)
continue;
var customModifierType = customModifier.type as DefType;
if (customModifierType == null)
continue;
if ((customModifierType.Namespace == "System.Runtime.CompilerServices" && customModifierType.Name == "IsCopyConstructed") ||
(customModifierType.Namespace == "Microsoft.VisualC" && customModifierType.Name == "NeedsCopyConstructorModifier"))
{
return true;
}
}
return false;
}
internal static MarshallerKind GetMarshallerKind(
TypeDesc type,
int? parameterIndex,
EmbeddedSignatureData[] customModifierData,
MarshalAsDescriptor marshalAs,
bool isReturn,
bool isAnsi,
MarshallerType marshallerType,
out MarshallerKind elementMarshallerKind)
{
elementMarshallerKind = MarshallerKind.Invalid;
bool isByRef = false;
if (type.IsByRef)
{
isByRef = true;
type = type.GetParameterType();
if (!type.IsPrimitive && type.IsValueType && marshallerType != MarshallerType.Field
&& HasCopyConstructorCustomModifier(parameterIndex, customModifierData))
{
return MarshallerKind.BlittableValueClassWithCopyCtor;
}
// Compat note: CLR allows ref returning blittable structs for IJW
if (isReturn)
return MarshallerKind.Invalid;
}
TypeSystemContext context = type.Context;
NativeTypeKind nativeType = NativeTypeKind.Default;
bool isField = marshallerType == MarshallerType.Field;
if (marshalAs != null)
nativeType = marshalAs.Type;
if (nativeType == NativeTypeKind.CustomMarshaler)
{
if (isField)
return MarshallerKind.FailedTypeLoad;
else
return MarshallerKind.CustomMarshaler;
}
//
// Determine MarshalerKind
//
if (type.IsPrimitive)
{
switch (type.Category)
{
case TypeFlags.Void:
return MarshallerKind.VoidReturn;
case TypeFlags.Boolean:
switch (nativeType)
{
case NativeTypeKind.Default:
case NativeTypeKind.Boolean:
return MarshallerKind.Bool;
case NativeTypeKind.U1:
case NativeTypeKind.I1:
return MarshallerKind.CBool;
case NativeTypeKind.VariantBool:
if (context.Target.IsWindows)
return MarshallerKind.VariantBool;
else
return MarshallerKind.Invalid;
default:
return MarshallerKind.Invalid;
}
case TypeFlags.Char:
switch (nativeType)
{
case NativeTypeKind.I1:
case NativeTypeKind.U1:
return MarshallerKind.AnsiChar;
case NativeTypeKind.I2:
case NativeTypeKind.U2:
return MarshallerKind.UnicodeChar;
case NativeTypeKind.Default:
if (isAnsi)
return MarshallerKind.AnsiChar;
else
return MarshallerKind.UnicodeChar;
default:
return MarshallerKind.Invalid;
}
case TypeFlags.SByte:
case TypeFlags.Byte:
if (nativeType == NativeTypeKind.I1 || nativeType == NativeTypeKind.U1 || nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Int16:
case TypeFlags.UInt16:
if (nativeType == NativeTypeKind.I2 || nativeType == NativeTypeKind.U2 || nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Int32:
case TypeFlags.UInt32:
if (nativeType == NativeTypeKind.I4 || nativeType == NativeTypeKind.U4 || nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Int64:
case TypeFlags.UInt64:
if (nativeType == NativeTypeKind.I8 || nativeType == NativeTypeKind.U8 || nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.IntPtr:
case TypeFlags.UIntPtr:
if (nativeType == NativeTypeKind.SysInt || nativeType == NativeTypeKind.SysUInt || nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Single:
if (nativeType == NativeTypeKind.R4 || nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
case TypeFlags.Double:
if (nativeType == NativeTypeKind.R8 || nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
default:
return MarshallerKind.Invalid;
}
}
else if (type.IsValueType)
{
if (type.IsEnum)
return MarshallerKind.Enum;
if (InteropTypes.IsSystemDateTime(context, type))
{
if (nativeType == NativeTypeKind.Default ||
nativeType == NativeTypeKind.Struct)
return MarshallerKind.OleDateTime;
else
return MarshallerKind.Invalid;
}
else if (InteropTypes.IsHandleRef(context, type))
{
if (nativeType == NativeTypeKind.Default)
return MarshallerKind.HandleRef;
else
return MarshallerKind.Invalid;
}
else if (InteropTypes.IsSystemDecimal(context, type))
{
if (nativeType == NativeTypeKind.Struct || nativeType == NativeTypeKind.Default)
return MarshallerKind.Decimal;
else if (nativeType == NativeTypeKind.LPStruct && !isField)
return MarshallerKind.BlittableStructPtr;
else if (nativeType == NativeTypeKind.Currency)
return MarshallerKind.OleCurrency;
else
return MarshallerKind.Invalid;
}
else if (InteropTypes.IsSystemGuid(context, type))
{
if (nativeType == NativeTypeKind.Struct || nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableStruct;
else if (nativeType == NativeTypeKind.LPStruct && !isField)
return MarshallerKind.BlittableStructPtr;
else
return MarshallerKind.Invalid;
}
else if (InteropTypes.IsSystemArgIterator(context, type))
{
// Don't want to fall through to the blittable/haslayout case
return MarshallerKind.Invalid;
}
bool isBlittable = MarshalUtils.IsBlittableType(type);
// Blittable generics are allowed to be marshalled with the following exceptions:
// * ByReference<T>: This represents an interior pointer and is not actually blittable
// * Nullable<T>: We don't want to be locked into the default behavior as we may want special handling later
// * Vector64<T>: Represents the __m64 ABI primitive which requires currently unimplemented handling
// * Vector128<T>: Represents the __m128 ABI primitive which requires currently unimplemented handling
// * Vector256<T>: Represents the __m256 ABI primitive which requires currently unimplemented handling
// * Vector<T>: Has a variable size (either __m128 or __m256) and isn't readily usable for interop scenarios
// We can't block these types for field scenarios for back-compat reasons.
if (type.HasInstantiation && !isField && (!isBlittable
|| InteropTypes.IsSystemByReference(context, type)
|| InteropTypes.IsSystemSpan(context, type)
|| InteropTypes.IsSystemReadOnlySpan(context, type)
|| InteropTypes.IsSystemNullable(context, type)
|| InteropTypes.IsSystemRuntimeIntrinsicsVector64T(context, type)
|| InteropTypes.IsSystemRuntimeIntrinsicsVector128T(context, type)
|| InteropTypes.IsSystemRuntimeIntrinsicsVector256T(context, type)
|| InteropTypes.IsSystemNumericsVectorT(context, type)))
{
// Generic types cannot be marshaled.
return MarshallerKind.Invalid;
}
if (isBlittable)
{
if (nativeType != NativeTypeKind.Default && nativeType != NativeTypeKind.Struct)
return MarshallerKind.Invalid;
return MarshallerKind.BlittableStruct;
}
else if (((MetadataType)type).HasLayout())
{
if (nativeType != NativeTypeKind.Default && nativeType != NativeTypeKind.Struct)
return MarshallerKind.Invalid;
return MarshallerKind.Struct;
}
else
{
return MarshallerKind.Invalid;
}
}
else if (type.IsSzArray)
{
#if READYTORUN
// We don't want the additional test/maintenance cost of this in R2R.
if (isByRef)
return MarshallerKind.Invalid;
#else
_ = isByRef;
#endif
if (nativeType == NativeTypeKind.Default)
nativeType = NativeTypeKind.Array;
switch (nativeType)
{
case NativeTypeKind.Array:
{
if (isField)
return MarshallerKind.FailedTypeLoad;
var arrayType = (ArrayType)type;
elementMarshallerKind = GetArrayElementMarshallerKind(
arrayType,
marshalAs,
isAnsi);
// If element is invalid type, the array itself is invalid
if (elementMarshallerKind == MarshallerKind.Invalid)
return MarshallerKind.Invalid;
if (elementMarshallerKind == MarshallerKind.AnsiChar)
return MarshallerKind.AnsiCharArray;
else if (elementMarshallerKind == MarshallerKind.UnicodeChar // Arrays of unicode char should be marshalled as blittable arrays
|| elementMarshallerKind == MarshallerKind.Enum
|| elementMarshallerKind == MarshallerKind.BlittableValue)
return MarshallerKind.BlittableArray;
else
return MarshallerKind.Array;
}
case NativeTypeKind.ByValArray: // fix sized array
{
var arrayType = (ArrayType)type;
elementMarshallerKind = GetArrayElementMarshallerKind(
arrayType,
marshalAs,
isAnsi);
// If element is invalid type, the array itself is invalid
if (elementMarshallerKind == MarshallerKind.Invalid)
return MarshallerKind.Invalid;
if (elementMarshallerKind == MarshallerKind.AnsiChar)
return MarshallerKind.ByValAnsiCharArray;
else
return MarshallerKind.ByValArray;
}
default:
return MarshallerKind.Invalid;
}
}
else if (type.IsPointer)
{
if (nativeType == NativeTypeKind.Default)
{
var pointedAtType = type.GetParameterType();
if (!pointedAtType.IsPrimitive && !type.IsEnum && marshallerType != MarshallerType.Field
&& HasCopyConstructorCustomModifier(parameterIndex, customModifierData))
{
return MarshallerKind.BlittableValueClassWithCopyCtor;
}
return MarshallerKind.BlittableValue;
}
else
return MarshallerKind.Invalid;
}
else if (type.IsFunctionPointer)
{
if (nativeType == NativeTypeKind.Func || nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
}
else if (type.IsDelegate || InteropTypes.IsSystemDelegate(context, type) || InteropTypes.IsSystemMulticastDelegate(context, type))
{
if (type.HasInstantiation)
{
// Generic types cannot be marshaled.
return MarshallerKind.Invalid;
}
if (nativeType == NativeTypeKind.Default || nativeType == NativeTypeKind.Func)
return MarshallerKind.FunctionPointer;
else
return MarshallerKind.Invalid;
}
else if (type.IsString)
{
switch (nativeType)
{
case NativeTypeKind.LPWStr:
return MarshallerKind.UnicodeString;
case NativeTypeKind.LPStr:
return MarshallerKind.AnsiString;
case NativeTypeKind.LPUTF8Str:
return MarshallerKind.UTF8String;
case NativeTypeKind.LPTStr:
return MarshallerKind.UnicodeString;
case NativeTypeKind.ByValTStr:
if (isAnsi)
{
elementMarshallerKind = MarshallerKind.AnsiChar;
return MarshallerKind.ByValAnsiString;
}
else
{
elementMarshallerKind = MarshallerKind.UnicodeChar;
return MarshallerKind.ByValUnicodeString;
}
case NativeTypeKind.TBStr:
case NativeTypeKind.BStr:
return MarshallerKind.BSTRString;
case NativeTypeKind.AnsiBStr:
return MarshallerKind.AnsiBSTRString;
case NativeTypeKind.CustomMarshaler:
return MarshallerKind.CustomMarshaler;
case NativeTypeKind.Default:
if (isAnsi)
return MarshallerKind.AnsiString;
else
return MarshallerKind.UnicodeString;
default:
return MarshallerKind.Invalid;
}
}
else if (type.IsObject)
{
if (nativeType == NativeTypeKind.AsAny && isField)
return MarshallerKind.FailedTypeLoad;
if (nativeType == NativeTypeKind.AsAny)
return isAnsi ? MarshallerKind.AsAnyA : MarshallerKind.AsAnyW;
else
if (context.Target.IsWindows)
{
if ((isField && nativeType == NativeTypeKind.Default)
|| nativeType == NativeTypeKind.Intf
|| nativeType == NativeTypeKind.IUnknown)
return MarshallerKind.ComInterface;
else
return MarshallerKind.Variant;
}
else
return MarshallerKind.Invalid;
}
else if (InteropTypes.IsStringBuilder(context, type))
{
switch (nativeType)
{
case NativeTypeKind.Default:
if (isAnsi)
{
return MarshallerKind.AnsiStringBuilder;
}
else
{
return MarshallerKind.UnicodeStringBuilder;
}
case NativeTypeKind.LPStr:
return MarshallerKind.AnsiStringBuilder;
case NativeTypeKind.LPWStr:
return MarshallerKind.UnicodeStringBuilder;
default:
return MarshallerKind.Invalid;
}
}
else if (InteropTypes.IsSafeHandle(context, type))
{
if (nativeType == NativeTypeKind.Default)
return MarshallerKind.SafeHandle;
else
return MarshallerKind.Invalid;
}
else if (InteropTypes.IsCriticalHandle(context, type))
{
if (nativeType == NativeTypeKind.Default)
return MarshallerKind.CriticalHandle;
else
return MarshallerKind.Invalid;
}
else if (type is MetadataType mdType && mdType.HasLayout())
{
if (type.HasInstantiation)
{
// Generic types cannot be marshaled.
return MarshallerKind.Invalid;
}
if (!isField && nativeType == NativeTypeKind.Default || nativeType == NativeTypeKind.LPStruct)
return MarshallerKind.LayoutClassPtr;
else if (isField && (nativeType == NativeTypeKind.Default || nativeType == NativeTypeKind.Struct))
return MarshallerKind.LayoutClass;
else
return MarshallerKind.Invalid;
}
else if (type.IsInterface)
{
if (context.Target.IsWindows)
return MarshallerKind.ComInterface;
else
return MarshallerKind.Invalid;
}
else
{
return MarshallerKind.Invalid;
}
}
private static MarshallerKind GetArrayElementMarshallerKind(
ArrayType arrayType,
MarshalAsDescriptor marshalAs,
bool isAnsi)
{
TypeDesc elementType = arrayType.ElementType;
NativeTypeKind nativeType = NativeTypeKind.Default;
TypeSystemContext context = arrayType.Context;
if (marshalAs != null)
nativeType = (NativeTypeKind)marshalAs.ArraySubType;
if (elementType.IsPrimitive)
{
switch (elementType.Category)
{
case TypeFlags.Char:
switch (nativeType)
{
case NativeTypeKind.I1:
case NativeTypeKind.U1:
return MarshallerKind.AnsiChar;
case NativeTypeKind.I2:
case NativeTypeKind.U2:
return MarshallerKind.UnicodeChar;
default:
if (isAnsi)
return MarshallerKind.AnsiChar;
else
return MarshallerKind.UnicodeChar;
}
case TypeFlags.Boolean:
switch (nativeType)
{
case NativeTypeKind.Boolean:
return MarshallerKind.Bool;
case NativeTypeKind.I1:
case NativeTypeKind.U1:
return MarshallerKind.CBool;
case NativeTypeKind.Default:
default:
return MarshallerKind.Bool;
}
case TypeFlags.IntPtr:
case TypeFlags.UIntPtr:
return MarshallerKind.BlittableValue;
case TypeFlags.Void:
return MarshallerKind.Invalid;
case TypeFlags.SByte:
case TypeFlags.Int16:
case TypeFlags.Int32:
case TypeFlags.Int64:
case TypeFlags.Byte:
case TypeFlags.UInt16:
case TypeFlags.UInt32:
case TypeFlags.UInt64:
case TypeFlags.Single:
case TypeFlags.Double:
return MarshallerKind.BlittableValue;
default:
return MarshallerKind.Invalid;
}
}
else if (elementType.IsValueType)
{
if (elementType.IsEnum)
return MarshallerKind.Enum;
if (InteropTypes.IsSystemDecimal(context, elementType))
{
switch (nativeType)
{
case NativeTypeKind.Default:
case NativeTypeKind.Struct:
return MarshallerKind.Decimal;
case NativeTypeKind.LPStruct:
return MarshallerKind.BlittableStructPtr;
default:
return MarshallerKind.Invalid;
}
}
else if (InteropTypes.IsSystemGuid(context, elementType))
{
switch (nativeType)
{
case NativeTypeKind.Default:
case NativeTypeKind.Struct:
return MarshallerKind.BlittableValue;
case NativeTypeKind.LPStruct:
return MarshallerKind.BlittableStructPtr;
default:
return MarshallerKind.Invalid;
}
}
else if (InteropTypes.IsSystemDateTime(context, elementType))
{
if (nativeType == NativeTypeKind.Default ||
nativeType == NativeTypeKind.Struct)
{
return MarshallerKind.OleDateTime;
}
else
{
return MarshallerKind.Invalid;
}
}
else if (InteropTypes.IsHandleRef(context, elementType))
{
if (nativeType == NativeTypeKind.Default)
return MarshallerKind.HandleRef;
else
return MarshallerKind.Invalid;
}
else
{
if (MarshalUtils.IsBlittableType(elementType))
{
switch (nativeType)
{
case NativeTypeKind.Default:
case NativeTypeKind.Struct:
return MarshallerKind.BlittableStruct;
default:
return MarshallerKind.Invalid;
}
}
else
{
// TODO: Differentiate between struct and Union, we only need to support struct not union here
return MarshallerKind.Struct;
}
}
}
else if (elementType.IsPointer || elementType.IsFunctionPointer)
{
if (nativeType == NativeTypeKind.Default)
return MarshallerKind.BlittableValue;
else
return MarshallerKind.Invalid;
}
else if (elementType.IsString)
{
switch (nativeType)
{
case NativeTypeKind.Default:
if (isAnsi)
return MarshallerKind.AnsiString;
else
return MarshallerKind.UnicodeString;
case NativeTypeKind.LPStr:
return MarshallerKind.AnsiString;
case NativeTypeKind.LPWStr:
return MarshallerKind.UnicodeString;
case NativeTypeKind.LPUTF8Str:
return MarshallerKind.UTF8String;
case NativeTypeKind.BStr:
case NativeTypeKind.TBStr:
return MarshallerKind.BSTRString;
case NativeTypeKind.AnsiBStr:
return MarshallerKind.AnsiBSTRString;
case NativeTypeKind.CustomMarshaler:
return MarshallerKind.CustomMarshaler;
default:
return MarshallerKind.Invalid;
}
}
// else if (elementType.IsObject)
// {
// if (nativeType == NativeTypeKind.Invalid)
// return MarshallerKind.Variant;
// else
// return MarshallerKind.Invalid;
// }
else
{
return MarshallerKind.Invalid;
}
}
internal static MarshallerKind GetDisabledMarshallerKind(
TypeDesc type)
{
// Get the underlying type for enum types.
TypeDesc underlyingType = type.UnderlyingType;
if (underlyingType.Category == TypeFlags.Void)
{
return MarshallerKind.VoidReturn;
}
else if (underlyingType.IsByRef)
{
// Managed refs are not supported when runtime marshalling is disabled.
return MarshallerKind.Invalid;
}
else if (underlyingType.IsPrimitive)
{
return MarshallerKind.BlittableValue;
}
else if (underlyingType.IsPointer || underlyingType.IsFunctionPointer)
{
return MarshallerKind.BlittableValue;
}
else if (underlyingType.IsValueType)
{
var defType = (DefType)underlyingType;
if (!defType.ContainsGCPointers && !defType.IsAutoLayoutOrHasAutoLayoutFields)
{
return MarshallerKind.BlittableValue;
}
}
return MarshallerKind.Invalid;
}
internal static bool ShouldCheckForPendingException(TargetDetails target, PInvokeMetadata metadata)
{
if (!target.IsOSX)
return false;
const string ObjectiveCLibrary = "/usr/lib/libobjc.dylib";
const string ObjectiveCMsgSend = "objc_msgSend";
// This is for the objc_msgSend suite of functions.
// objc_msgSend
// objc_msgSend_fpret
// objc_msgSend_stret
// objc_msgSendSuper
// objc_msgSendSuper_stret
return metadata.Module.Equals(ObjectiveCLibrary)
&& metadata.Name.StartsWith(ObjectiveCMsgSend);
}
public static bool IsRuntimeMarshallingEnabled(ModuleDesc module)
{
return module.Assembly is not EcmaAssembly assembly || !assembly.HasAssemblyCustomAttribute("System.Runtime.CompilerServices", "DisableRuntimeMarshallingAttribute");
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/Loader/classloader/regressions/dev10_398410/dev10_398410.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//Type load failed when compiling a class derived from a class that implicitly implements a generic method as a virtual method.
//The base class and the interface are in a separate module
//DDB186874: the output was:
// "Unhandled Exception: System.TypeLoadException: Method 'MyBase.Print' on type 'MyDerived' from assembly 'Test,
// Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' tried to implicitly implement an interface method with
// weaker type parameter constraints."
using System;
public class MyDerived : MyBase, I
{
}
class MyTest
{
public static int Main()
{
I I1 = new MyDerived();
System.Console.WriteLine("I1.Print<object>: " + I1.Print<object>());
return 100;
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//Type load failed when compiling a class derived from a class that implicitly implements a generic method as a virtual method.
//The base class and the interface are in a separate module
//DDB186874: the output was:
// "Unhandled Exception: System.TypeLoadException: Method 'MyBase.Print' on type 'MyDerived' from assembly 'Test,
// Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' tried to implicitly implement an interface method with
// weaker type parameter constraints."
using System;
public class MyDerived : MyBase, I
{
}
class MyTest
{
public static int Main()
{
I I1 = new MyDerived();
System.Console.WriteLine("I1.Print<object>: " + I1.Print<object>());
return 100;
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/ConvertToInt64RoundToNegativeInfinityScalar.Vector64.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 ConvertToInt64RoundToNegativeInfinityScalar_Vector64_Double()
{
var test = new SimpleUnaryOpTest__ConvertToInt64RoundToNegativeInfinityScalar_Vector64_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__ConvertToInt64RoundToNegativeInfinityScalar_Vector64_Double
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Int64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>();
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 Vector64<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<Vector64<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__ConvertToInt64RoundToNegativeInfinityScalar_Vector64_Double testClass)
{
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__ConvertToInt64RoundToNegativeInfinityScalar_Vector64_Double testClass)
{
fixed (Vector64<Double>* pFld1 = &_fld1)
{
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(
AdvSimd.LoadVector64((Double*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Vector64<Double> _clsVar1;
private Vector64<Double> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__ConvertToInt64RoundToNegativeInfinityScalar_Vector64_Double()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Double>>());
}
public SimpleUnaryOpTest__ConvertToInt64RoundToNegativeInfinityScalar_Vector64_Double()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, new Int64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.Arm64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(
Unsafe.Read<Vector64<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.ConvertToInt64RoundToNegativeInfinityScalar(
AdvSimd.LoadVector64((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.ConvertToInt64RoundToNegativeInfinityScalar), new Type[] { typeof(Vector64<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Double>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(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.ConvertToInt64RoundToNegativeInfinityScalar), new Type[] { typeof(Vector64<Double>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Double*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Double>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(
AdvSimd.LoadVector64((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<Vector64<Double>>(_dataTable.inArray1Ptr);
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Double*)(_dataTable.inArray1Ptr));
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__ConvertToInt64RoundToNegativeInfinityScalar_Vector64_Double();
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(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__ConvertToInt64RoundToNegativeInfinityScalar_Vector64_Double();
fixed (Vector64<Double>* pFld1 = &test._fld1)
{
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(
AdvSimd.LoadVector64((Double*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Double>* pFld1 = &_fld1)
{
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(
AdvSimd.LoadVector64((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.ConvertToInt64RoundToNegativeInfinityScalar(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.ConvertToInt64RoundToNegativeInfinityScalar(
AdvSimd.LoadVector64((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(Vector64<Double> op1, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Double[] firstOp, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Helpers.ConvertToInt64RoundToNegativeInfinity(firstOp[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.ConvertToInt64RoundToNegativeInfinityScalar)}<Int64>(Vector64<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 ConvertToInt64RoundToNegativeInfinityScalar_Vector64_Double()
{
var test = new SimpleUnaryOpTest__ConvertToInt64RoundToNegativeInfinityScalar_Vector64_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__ConvertToInt64RoundToNegativeInfinityScalar_Vector64_Double
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Int64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>();
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 Vector64<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<Vector64<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__ConvertToInt64RoundToNegativeInfinityScalar_Vector64_Double testClass)
{
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__ConvertToInt64RoundToNegativeInfinityScalar_Vector64_Double testClass)
{
fixed (Vector64<Double>* pFld1 = &_fld1)
{
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(
AdvSimd.LoadVector64((Double*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Vector64<Double> _clsVar1;
private Vector64<Double> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__ConvertToInt64RoundToNegativeInfinityScalar_Vector64_Double()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Double>>());
}
public SimpleUnaryOpTest__ConvertToInt64RoundToNegativeInfinityScalar_Vector64_Double()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, new Int64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.Arm64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(
Unsafe.Read<Vector64<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.ConvertToInt64RoundToNegativeInfinityScalar(
AdvSimd.LoadVector64((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.ConvertToInt64RoundToNegativeInfinityScalar), new Type[] { typeof(Vector64<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Double>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(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.ConvertToInt64RoundToNegativeInfinityScalar), new Type[] { typeof(Vector64<Double>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Double*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Double>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(
AdvSimd.LoadVector64((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<Vector64<Double>>(_dataTable.inArray1Ptr);
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Double*)(_dataTable.inArray1Ptr));
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__ConvertToInt64RoundToNegativeInfinityScalar_Vector64_Double();
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(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__ConvertToInt64RoundToNegativeInfinityScalar_Vector64_Double();
fixed (Vector64<Double>* pFld1 = &test._fld1)
{
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(
AdvSimd.LoadVector64((Double*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Double>* pFld1 = &_fld1)
{
var result = AdvSimd.Arm64.ConvertToInt64RoundToNegativeInfinityScalar(
AdvSimd.LoadVector64((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.ConvertToInt64RoundToNegativeInfinityScalar(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.ConvertToInt64RoundToNegativeInfinityScalar(
AdvSimd.LoadVector64((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(Vector64<Double> op1, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Double[] firstOp, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Helpers.ConvertToInt64RoundToNegativeInfinity(firstOp[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.ConvertToInt64RoundToNegativeInfinityScalar)}<Int64>(Vector64<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,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/Performance/CodeQuality/Span/Indexer.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<!-- Always try to use latest Roslyn compiler -->
<PropertyGroup>
<OutputType>Exe</OutputType>
<NoWarn>$(NoWarn);xUnit1013</NoWarn>
</PropertyGroup>
<PropertyGroup>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<Compile Include="Indexer.cs" />
</ItemGroup>
<PropertyGroup>
<ProjectAssetsFile>$(JitPackagesConfigFileDirectory)benchmark\obj\project.assets.json</ProjectAssetsFile>
</PropertyGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk">
<!-- Always try to use latest Roslyn compiler -->
<PropertyGroup>
<OutputType>Exe</OutputType>
<NoWarn>$(NoWarn);xUnit1013</NoWarn>
</PropertyGroup>
<PropertyGroup>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<Compile Include="Indexer.cs" />
</ItemGroup>
<PropertyGroup>
<ProjectAssetsFile>$(JitPackagesConfigFileDirectory)benchmark\obj\project.assets.json</ProjectAssetsFile>
</PropertyGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/Performance/CodeQuality/Benchstones/BenchI/BenchE/BenchE.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).cs" />
</ItemGroup>
<PropertyGroup>
<ProjectAssetsFile>$(JitPackagesConfigFileDirectory)benchmark\obj\project.assets.json</ProjectAssetsFile>
</PropertyGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).cs" />
</ItemGroup>
<PropertyGroup>
<ProjectAssetsFile>$(JitPackagesConfigFileDirectory)benchmark\obj\project.assets.json</ProjectAssetsFile>
</PropertyGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/jit64/valuetypes/nullable/box-unbox/null/box-unbox-null002.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
using System;
internal class NullableTest
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((bool?)o) == null;
}
private static int Main()
{
bool? s = null;
if (BoxUnboxToNQ(s) && BoxUnboxToQ(s) && BoxUnboxToNQGen(s) && BoxUnboxToQGen(s))
return ExitCode.Passed;
else
return ExitCode.Failed;
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
using System;
internal class NullableTest
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((bool?)o) == null;
}
private static int Main()
{
bool? s = null;
if (BoxUnboxToNQ(s) && BoxUnboxToQ(s) && BoxUnboxToNQGen(s) && BoxUnboxToQGen(s))
return ExitCode.Passed;
else
return ExitCode.Failed;
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Reflection/tests/MemberInfoTests.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.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Xunit;
#pragma warning disable 0414
#pragma warning disable 0649 // Yes, we know - test class have fields we don't assign to.
namespace System.Reflection.Tests
{
public class MemberInfoTests
{
[Fact]
public void MetadataToken()
{
Assert.Equal(GetMetadataTokens(typeof(SampleClass)), GetMetadataTokens(typeof(SampleClass)));
Assert.Equal(GetMetadataTokens(new MemberInfoTests().GetType()), GetMetadataTokens(new MemberInfoTests().GetType()));
Assert.Equal(GetMetadataTokens(new Dictionary<int, string>().GetType()), GetMetadataTokens(new Dictionary<int, int>().GetType()));
Assert.Equal(GetMetadataTokens(typeof(int)), GetMetadataTokens(typeof(int)));
Assert.Equal(GetMetadataTokens(typeof(Dictionary<,>)), GetMetadataTokens(typeof(Dictionary<,>)));
}
[Fact]
public void ReflectedType()
{
Type t = typeof(Derived);
MemberInfo[] members = t.GetMembers();
foreach (MemberInfo member in members)
{
Assert.Equal(t, member.ReflectedType);
}
}
[Fact]
public void PropertyReflectedType()
{
Type t = typeof(Base);
PropertyInfo p = t.GetProperty(nameof(Base.MyProperty1));
Assert.Equal(t, p.ReflectedType);
Assert.NotNull(p.GetMethod);
Assert.NotNull(p.SetMethod);
}
[Fact]
public void InheritedPropertiesHidePrivateAccessorMethods()
{
Type t = typeof(Derived);
PropertyInfo p = t.GetProperty(nameof(Base.MyProperty1));
Assert.Equal(t, p.ReflectedType);
Assert.NotNull(p.GetMethod);
Assert.Null(p.SetMethod);
}
[Fact]
public void GenericMethodsInheritTheReflectedTypeOfTheirTemplate()
{
Type t = typeof(Derived);
MethodInfo moo = t.GetMethod("Moo");
Assert.Equal(t, moo.ReflectedType);
MethodInfo mooInst = moo.MakeGenericMethod(typeof(int));
Assert.Equal(t, mooInst.ReflectedType);
}
[Fact]
public void DeclaringMethodOfTypeParametersOfInheritedMethods()
{
Type t = typeof(Derived);
MethodInfo moo = t.GetMethod("Moo");
Assert.Equal(t, moo.ReflectedType);
Type theM = moo.GetGenericArguments()[0];
MethodBase moo1 = theM.DeclaringMethod;
Type reflectedTypeOfMoo1 = moo1.ReflectedType;
Assert.Equal(typeof(Base), reflectedTypeOfMoo1);
}
[Fact]
public void DeclaringMethodOfTypeParametersOfInheritedMethods2()
{
Type t = typeof(GDerived<int>);
MethodInfo moo = t.GetMethod("Moo");
Assert.Equal(t, moo.ReflectedType);
Type theM = moo.GetGenericArguments()[0];
MethodBase moo1 = theM.DeclaringMethod;
Type reflectedTypeOfMoo1 = moo1.ReflectedType;
Assert.Equal(typeof(GBase<>), reflectedTypeOfMoo1);
}
[Fact]
public void InheritedPropertyAccessors()
{
Type t = typeof(Derived);
PropertyInfo p = t.GetProperty(nameof(Base.MyProperty));
MethodInfo getter = p.GetMethod;
MethodInfo setter = p.SetMethod;
Assert.Equal(t, getter.ReflectedType);
Assert.Equal(t, setter.ReflectedType);
}
[Fact]
public void InheritedEventAccessors()
{
Type t = typeof(Derived);
EventInfo e = t.GetEvent(nameof(Base.MyEvent));
MethodInfo adder = e.AddMethod;
MethodInfo remover = e.RemoveMethod;
Assert.Equal(t, adder.ReflectedType);
Assert.Equal(t, remover.ReflectedType);
}
[Fact]
public void ReflectedTypeIsPartOfIdentity()
{
Type b = typeof(Base);
Type d = typeof(Derived);
{
EventInfo e = b.GetEvent(nameof(Base.MyEvent));
EventInfo ei = d.GetEvent(nameof(Derived.MyEvent));
Assert.False(e.Equals(ei));
}
{
FieldInfo f = b.GetField(nameof(Base.MyField));
FieldInfo fi = d.GetField(nameof(Derived.MyField));
Assert.False(f.Equals(fi));
}
{
MethodInfo m = b.GetMethod(nameof(Base.Moo));
MethodInfo mi = d.GetMethod(nameof(Derived.Moo));
Assert.False(m.Equals(mi));
}
{
PropertyInfo p = b.GetProperty(nameof(Base.MyProperty));
PropertyInfo pi = d.GetProperty(nameof(Derived.MyProperty));
Assert.False(p.Equals(pi));
}
}
[Fact]
public void FieldInfoReflectedTypeDoesNotSurviveRuntimeHandles()
{
Type t = typeof(Derived);
FieldInfo f = t.GetField(nameof(Base.MyField));
Assert.Equal(typeof(Derived), f.ReflectedType);
RuntimeFieldHandle h = f.FieldHandle;
FieldInfo f2 = FieldInfo.GetFieldFromHandle(h);
Assert.Equal(typeof(Base), f2.ReflectedType);
}
[Fact]
public void MethodInfoReflectedTypeDoesNotSurviveRuntimeHandles()
{
Type t = typeof(Derived);
MethodInfo m = t.GetMethod(nameof(Base.Moo));
Assert.Equal(typeof(Derived), m.ReflectedType);
RuntimeMethodHandle h = m.MethodHandle;
MethodBase m2 = MethodBase.GetMethodFromHandle(h);
Assert.Equal(typeof(Base), m2.ReflectedType);
}
[Fact]
public void GetCustomAttributesData()
{
MemberInfo[] m = typeof(MemberInfoTests).GetMember("SampleClass");
Assert.Equal(1, m.Count());
foreach (CustomAttributeData cad in m[0].GetCustomAttributesData())
{
if (cad.AttributeType == typeof(ComVisibleAttribute))
{
ConstructorInfo c = cad.Constructor;
Assert.False(c.IsStatic);
Assert.Equal(typeof(ComVisibleAttribute), c.DeclaringType);
ParameterInfo[] p = c.GetParameters();
Assert.Equal(1, p.Length);
Assert.Equal(typeof(bool), p[0].ParameterType);
return;
}
}
Assert.True(false, "Expected to find ComVisibleAttribute");
}
public static IEnumerable<object[]> EqualityOperator_TestData()
{
yield return new object[] { typeof(SampleClass) };
yield return new object[] { new MemberInfoTests().GetType() };
yield return new object[] { typeof(int) };
yield return new object[] { typeof(Dictionary<,>) };
}
[Theory]
[MemberData(nameof(EqualityOperator_TestData))]
public void EqualityOperator_Equal_ReturnsTrue(Type type)
{
MemberInfo[] members1 = GetOrderedMembers(type);
MemberInfo[] members2 = GetOrderedMembers(type);
Assert.Equal(members1.Length, members2.Length);
for (int i = 0; i < members1.Length; i++)
{
Assert.True(members1[i] == members2[i]);
Assert.False(members1[i] != members2[i]);
}
}
[Fact]
public static void HasSameMetadataDefinitionAs_GenericClassMembers()
{
Type tGeneric = typeof(GenericTestClass<>);
IEnumerable<MethodInfo> methodsOnGeneric = tGeneric.GetTypeInfo().GetDeclaredMethods(nameof(GenericTestClass<object>.Foo));
List<Type> typeInsts = new List<Type>();
foreach (MethodInfo method in methodsOnGeneric)
{
Debug.Assert(method.GetParameters().Length == 1);
Type parameterType = method.GetParameters()[0].ParameterType;
typeInsts.Add(tGeneric.MakeGenericType(parameterType));
}
typeInsts.Add(tGeneric);
CrossTestHasSameMethodDefinitionAs(typeInsts.ToArray());
}
private static void CrossTestHasSameMethodDefinitionAs(params Type[] types)
{
Assert.All(types,
delegate (Type type1)
{
Assert.All(type1.GenerateTestMemberList(),
delegate (MemberInfo m1)
{
MarkerAttribute mark1 = m1.GetCustomAttribute<MarkerAttribute>();
if (mark1 == null)
return;
Assert.All(types,
delegate (Type type2)
{
Assert.All(type2.GenerateTestMemberList(),
delegate (MemberInfo m2)
{
MarkerAttribute mark2 = m2.GetCustomAttribute<MarkerAttribute>();
if (mark2 == null)
return;
bool hasSameMetadata = m1.HasSameMetadataDefinitionAs(m2);
Assert.Equal(hasSameMetadata, m2.HasSameMetadataDefinitionAs(m1));
if (hasSameMetadata)
{
Assert.Equal(mark1.Mark, mark2.Mark);
}
else
{
Assert.NotEqual(mark1.Mark, mark2.Mark);
}
}
);
}
);
}
);
}
);
}
[Fact]
public static void HasSameMetadataDefinitionAs_ReflectedTypeNotPartOfComparison()
{
Type tBase = typeof(GenericTestClass<>);
Type tDerived = typeof(DerivedFromGenericTestClass<int>);
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
IEnumerable<MemberInfo> baseMembers = tBase.GetMembers(bf).Where(m => m.IsDefined(typeof(MarkerAttribute)));
baseMembers = baseMembers.Where(bm => !(bm is ConstructorInfo)); // Constructors cannot be seen from derived types.
IEnumerable<MemberInfo> derivedMembers = tDerived.GetMembers(bf).Where(m => m.IsDefined(typeof(MarkerAttribute)));
Assert.All(baseMembers,
delegate (MemberInfo baseMember)
{
MemberInfo matchingDerivedMember = derivedMembers.Single(dm => dm.HasSameMarkAs(baseMember));
Assert.True(baseMember.HasSameMetadataDefinitionAs(matchingDerivedMember));
Assert.True(matchingDerivedMember.HasSameMetadataDefinitionAs(matchingDerivedMember));
}
);
}
[Fact]
public static void HasSameMetadataDefinitionAs_ConstructedGenericMethods()
{
Type t1 = typeof(TestClassWithGenericMethod<>);
Type theT = t1.GetTypeInfo().GenericTypeParameters[0];
MethodInfo mooNormal = t1.GetConfirmedMethod(nameof(TestClassWithGenericMethod<object>.Moo), theT);
MethodInfo mooGeneric = t1.GetTypeInfo().GetDeclaredMethods("Moo").Single(m => m.IsGenericMethod);
MethodInfo mooInst = mooGeneric.MakeGenericMethod(typeof(int));
Assert.True(mooGeneric.HasSameMetadataDefinitionAs(mooInst));
Assert.True(mooInst.HasSameMetadataDefinitionAs(mooGeneric));
MethodInfo mooInst2 = mooGeneric.MakeGenericMethod(typeof(double));
Assert.True(mooInst2.HasSameMetadataDefinitionAs(mooInst));
Assert.True(mooInst.HasSameMetadataDefinitionAs(mooInst2));
Type t2 = typeof(TestClassWithGenericMethod<int>);
MethodInfo mooNormalOnT2 = t2.GetConfirmedMethod(nameof(TestClassWithGenericMethod<object>.Moo), typeof(int));
Assert.False(mooInst.HasSameMetadataDefinitionAs(mooNormalOnT2));
}
[Fact]
public static void HasSameMetadataDefinitionAs_NamedAndGenericTypes()
{
Type tnong = typeof(TestClass);
Type tnong2 = typeof(TestClass2);
Type tg = typeof(GenericTestClass<>);
Type tginst1 = typeof(GenericTestClass<int>);
Type tginst2 = typeof(GenericTestClass<string>);
Assert.True(tnong.HasSameMetadataDefinitionAs(tnong));
Assert.True(tnong2.HasSameMetadataDefinitionAs(tnong2));
Assert.True(tg.HasSameMetadataDefinitionAs(tg));
Assert.True(tginst1.HasSameMetadataDefinitionAs(tginst1));
Assert.True(tginst2.HasSameMetadataDefinitionAs(tginst2));
Assert.True(tg.HasSameMetadataDefinitionAs(tginst1));
Assert.True(tginst1.HasSameMetadataDefinitionAs(tginst1));
Assert.True(tginst1.HasSameMetadataDefinitionAs(tginst2));
Assert.False(tnong.HasSameMetadataDefinitionAs(tnong2));
Assert.False(tnong.HasSameMetadataDefinitionAs(tg));
Assert.False(tg.HasSameMetadataDefinitionAs(tnong));
Assert.False(tnong.HasSameMetadataDefinitionAs(tginst1));
Assert.False(tginst1.HasSameMetadataDefinitionAs(tnong));
}
[Fact]
[ActiveIssue("https://github.com/mono/mono/issues/15069", TestRuntimes.Mono)]
public static void HasSameMetadataDefinitionAs_GenericTypeParameters()
{
Type theT = typeof(GenericTestClass<>).GetTypeInfo().GenericTypeParameters[0];
Type theT2 = typeof(TestClassWithGenericMethod<>).GetTypeInfo().GenericTypeParameters[0];
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding;
MethodInfo mooNong = theT2.GetMethod("Moo", bf, null, new Type[] { theT2 }, null);
MethodInfo mooGeneric = typeof(TestClassWithGenericMethod<>).GetTypeInfo().GetDeclaredMethods("Moo").Single(m => m.IsGenericMethod);
Type theM = mooGeneric.GetGenericArguments()[0];
Assert.True(theT.HasSameMetadataDefinitionAs(theT));
Assert.False(theT2.HasSameMetadataDefinitionAs(theT));
Assert.False(theT.HasSameMetadataDefinitionAs(theT2));
Assert.False(theM.HasSameMetadataDefinitionAs(theT));
Assert.False(theM.HasSameMetadataDefinitionAs(theT2));
Assert.False(theT2.HasSameMetadataDefinitionAs(theM));
Assert.False(theT.HasSameMetadataDefinitionAs(theM));
}
[Fact]
public static void HasSameMetadataDefinitionAs_Twins()
{
// This situation is particularly treacherous for CoreRT as the .NET Native toolchain can and does assign
// the same native metadata tokens to identically structured members in unrelated types.
Type twin1 = typeof(Twin1);
Type twin2 = typeof(Twin2);
Assert.All(twin1.GenerateTestMemberList(),
delegate (MemberInfo m1)
{
Assert.All(twin2.GenerateTestMemberList(),
delegate (MemberInfo m2)
{
Assert.False(m1.HasSameMetadataDefinitionAs(m2));
}
);
}
);
}
private class Twin1
{
public Twin1() { }
public int Field1;
public Action Event1;
public void Method1() { }
public int Property1 { get; set; }
}
private class Twin2
{
public Twin2() { }
public int Field1;
public Action Event1;
public void Method1() { }
public int Property1 { get; set; }
}
[Fact]
[OuterLoop] // Time-consuming.
public static void HasSameMetadataDefinitionAs_CrossAssembly()
{
// Make sure that identical tokens in different assemblies don't confuse the api.
foreach (Type t1 in typeof(object).Assembly.DefinedTypes)
{
foreach (Type t2 in typeof(MemberInfoTests).Assembly.DefinedTypes)
{
Assert.False(t1.HasSameMetadataDefinitionAs(t2));
}
}
}
[Theory]
[MemberData(nameof(NegativeTypeData))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34328", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
public static void HasSameMetadataDefinitionAs_Negative_NonRuntimeType(Type type)
{
Type mockType = new MockType();
Assert.False(type.HasSameMetadataDefinitionAs(mockType));
Assert.All(type.GenerateTestMemberList(),
delegate (MemberInfo member)
{
Assert.False(member.HasSameMetadataDefinitionAs(mockType));
}
);
}
[Theory]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34328", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[MemberData(nameof(NegativeTypeData))]
public static void HasSameMetadataDefinitionAs_Negative_Null(Type type)
{
AssertExtensions.Throws<ArgumentNullException>("other", () => type.HasSameMetadataDefinitionAs(null));
Assert.All(type.GenerateTestMemberList(),
delegate (MemberInfo member)
{
AssertExtensions.Throws<ArgumentNullException>("other", () => member.HasSameMetadataDefinitionAs(null));
}
);
}
public static IEnumerable<object[]> NegativeTypeData => NegativeTypeDataRaw.Select(t => new object[] { t });
private static IEnumerable<Type> NegativeTypeDataRaw
{
get
{
yield return typeof(TestClass);
yield return typeof(GenericTestClass<>);
yield return typeof(GenericTestClass<int>);
yield return typeof(int[]);
yield return typeof(int).MakeArrayType(1);
yield return typeof(int[,]);
yield return typeof(int).MakeByRefType();
yield return typeof(int).MakePointerType();
yield return typeof(GenericTestClass<>).GetTypeInfo().GenericTypeParameters[0];
if (PlatformDetection.IsWindows)
yield return Type.GetTypeFromCLSID(new Guid("DCA66D18-E253-4695-9E08-35B54420AFA2"));
}
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/31648", TestRuntimes.Mono)]
public static void HasSameMetadataDefinitionAs__CornerCase_HasElementTypes()
{
// HasSameMetadataDefinitionAs on an array/byref/pointer type is uninteresting (they'll never be an actual member of a type)
// but for future compat, we'll establish their known behavior here. Since these types all return a MetadataToken of 0x02000000,
// they'll all "match" each other.
Type[] types =
{
typeof(int[]),
typeof(double[]),
typeof(int).MakeArrayType(1),
typeof(double).MakeArrayType(1),
typeof(int[,]),
typeof(double[,]),
typeof(int).MakeByRefType(),
typeof(double).MakeByRefType(),
typeof(int).MakePointerType(),
typeof(double).MakePointerType(),
};
Assert.All(types,
delegate (Type t1)
{
Assert.All(types, t2 => Assert.True(t1.HasSameMetadataDefinitionAs(t2)));
}
);
}
[Fact]
public static void HasSameMetadataDefinitionAs_CornerCase_ArrayMethods()
{
// The magic methods and constructors exposed on array types do not have metadata backing and report a MetadataToken of 0x06000000
// and hence compare identically with each other. This may be surprising but this test records that fact for future compat.
//
Type[] arrayTypes =
{
typeof(int[]),
typeof(double[]),
typeof(int).MakeArrayType(1),
typeof(double).MakeArrayType(1),
typeof(int[,]),
typeof(double[,]),
};
List<MemberInfo> members = new List<MemberInfo>();
foreach (Type arrayType in arrayTypes)
{
foreach (MemberInfo member in arrayType.GetMembers(BindingFlags.Public|BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
if (member is MethodBase)
{
members.Add(member);
}
}
}
Assert.All(members,
delegate (MemberInfo member1)
{
Assert.All(members,
delegate (MemberInfo member2)
{
if (member1.MemberType == member2.MemberType)
Assert.True(member1.HasSameMetadataDefinitionAs(member2));
else
Assert.False(member1.HasSameMetadataDefinitionAs(member2));
}
);
}
);
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34328", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[PlatformSpecific(TestPlatforms.Windows)]
public static void HasSameMetadataDefinitionAs_CornerCase_CLSIDConstructor()
{
// HasSameMetadataDefinitionAs on a GetTypeFromCLSID type is uninteresting (they'll never be an actual member of a type)
// but for future compat, we'll establish their known behavior here. Since these types and their constructors all return the same
// MetadataToken, they'll all "match" each other.
Type t1 = Type.GetTypeFromCLSID(new Guid("23A54889-7738-4F16-8AB2-CB23F8E756BE"));
Type t2 = Type.GetTypeFromCLSID(new Guid("DCA66D18-E253-4695-9E08-35B54420AFA2"));
Assert.True(t1.HasSameMetadataDefinitionAs(t2));
ConstructorInfo c1 = t1.GetConfirmedConstructor();
ConstructorInfo c2 = t2.GetConfirmedConstructor();
Assert.True(c1.HasSameMetadataDefinitionAs(c2));
}
private class TestClassWithGenericMethod<T>
{
public void Moo(T t) { }
public void Moo<M>(M m) { }
}
private class TestClass
{
public void Foo() { }
public void Foo(object o) { }
public void Foo(string s) { }
public void Bar() { }
}
private class TestClass2 { }
private class GenericTestClass<T>
{
[Marker(1)]
public void Foo(object o) { }
[Marker(2)]
public void Foo(int i) { }
[Marker(3)]
public void Foo(T t) { }
[Marker(4)]
public void Foo(double d) { }
[Marker(5)]
public void Foo(string s) { }
[Marker(6)]
public void Foo(int[] s) { }
[Marker(7)]
public void Foo<U>(U t) { }
[Marker(8)]
public void Foo<U>(T t) { }
[Marker(9)]
public void Foo<U, V>(T t) { }
[Marker(101)]
public GenericTestClass() { }
[Marker(102)]
public GenericTestClass(T t) { }
[Marker(103)]
public GenericTestClass(int t) { }
[Marker(201)]
public int Field1;
[Marker(202)]
public int Field2;
[Marker(203)]
public T Field3;
[Marker(301)]
public int Property1 { get { throw null; } set { throw null; } }
[Marker(302)]
public int Property2 { get { throw null; } set { throw null; } }
[Marker(303)]
public T Property3 { get { throw null; } set { throw null; } }
[Marker(401)]
public event Action Event1 { add { } remove { } }
[Marker(402)]
public event Action<int> Event2 { add { } remove { } }
[Marker(403)]
public event Action<T> Event3 { add { } remove { } }
}
private class DerivedFromGenericTestClass<T> : GenericTestClass<T> { }
private MemberInfo[] GetMembers(Type type)
{
return type.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
}
private IEnumerable<int> GetMetadataTokens(Type type)
{
return type.GetTypeInfo().GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Select(m => m.HasMetadataToken() ? m.MetadataToken : 0);
}
private MemberInfo[] GetOrderedMembers(Type type) => GetMembers(type).OrderBy(member => member.Name).ToArray();
private class Base
{
public event Action MyEvent { add { } remove { } }
#pragma warning disable 0649
public int MyField;
#pragma warning restore 0649
public int MyProperty { get; set; }
public int MyProperty1 { get; private set; }
public int MyProperty2 { private get; set; }
public void Moo<M>() { }
}
private class Derived : Base
{
}
private class GBase<T>
{
public void Moo<M>() { }
}
private class GDerived<T> : GBase<T>
{
}
#pragma warning disable 0067, 0169
[ComVisible(false)]
public class SampleClass
{
public int PublicField;
private int PrivateField;
public SampleClass(bool y) { }
private SampleClass(int x) { }
public void PublicMethod() { }
private void PrivateMethod() { }
public int PublicProp { get; set; }
private int PrivateProp { get; set; }
public event EventHandler PublicEvent;
private event EventHandler PrivateEvent;
}
#pragma warning restore 0067, 0169
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)]
public class MarkerAttribute : Attribute
{
public MarkerAttribute(int mark)
{
Mark = mark;
}
public readonly int Mark;
}
internal static class Extensions
{
internal static bool HasSameMarkAs(this MemberInfo m1, MemberInfo m2)
{
MarkerAttribute marker1 = m1.GetCustomAttribute<MarkerAttribute>();
Assert.NotNull(marker1);
MarkerAttribute marker2 = m2.GetCustomAttribute<MarkerAttribute>();
Assert.NotNull(marker2);
return marker1.Mark == marker2.Mark;
}
internal static MethodInfo GetConfirmedMethod(this Type t, string name, params Type[] parameterTypes)
{
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.ExactBinding;
MethodInfo method = t.GetMethod(name, bf, null, parameterTypes, null);
Assert.NotNull(method);
return method;
}
internal static ConstructorInfo GetConfirmedConstructor(this Type t, params Type[] parameterTypes)
{
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.ExactBinding;
ConstructorInfo ctor = t.GetConstructor(bf, null, parameterTypes, null);
Assert.NotNull(ctor);
return ctor;
}
internal static IEnumerable<MemberInfo> GenerateTestMemberList(this Type t)
{
if (t.IsGenericTypeDefinition)
{
foreach (Type gp in t.GetTypeInfo().GenericTypeParameters)
{
yield return gp;
}
}
foreach (MemberInfo m in t.GetTypeInfo().DeclaredMembers)
{
yield return m;
MethodInfo method = m as MethodInfo;
if (method != null && method.IsGenericMethodDefinition)
{
foreach (Type mgp in method.GetGenericArguments())
{
yield return mgp;
}
yield return method.MakeGenericMethod(method.GetGenericArguments().Select(ga => typeof(object)).ToArray());
}
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Xunit;
#pragma warning disable 0414
#pragma warning disable 0649 // Yes, we know - test class have fields we don't assign to.
namespace System.Reflection.Tests
{
public class MemberInfoTests
{
[Fact]
public void MetadataToken()
{
Assert.Equal(GetMetadataTokens(typeof(SampleClass)), GetMetadataTokens(typeof(SampleClass)));
Assert.Equal(GetMetadataTokens(new MemberInfoTests().GetType()), GetMetadataTokens(new MemberInfoTests().GetType()));
Assert.Equal(GetMetadataTokens(new Dictionary<int, string>().GetType()), GetMetadataTokens(new Dictionary<int, int>().GetType()));
Assert.Equal(GetMetadataTokens(typeof(int)), GetMetadataTokens(typeof(int)));
Assert.Equal(GetMetadataTokens(typeof(Dictionary<,>)), GetMetadataTokens(typeof(Dictionary<,>)));
}
[Fact]
public void ReflectedType()
{
Type t = typeof(Derived);
MemberInfo[] members = t.GetMembers();
foreach (MemberInfo member in members)
{
Assert.Equal(t, member.ReflectedType);
}
}
[Fact]
public void PropertyReflectedType()
{
Type t = typeof(Base);
PropertyInfo p = t.GetProperty(nameof(Base.MyProperty1));
Assert.Equal(t, p.ReflectedType);
Assert.NotNull(p.GetMethod);
Assert.NotNull(p.SetMethod);
}
[Fact]
public void InheritedPropertiesHidePrivateAccessorMethods()
{
Type t = typeof(Derived);
PropertyInfo p = t.GetProperty(nameof(Base.MyProperty1));
Assert.Equal(t, p.ReflectedType);
Assert.NotNull(p.GetMethod);
Assert.Null(p.SetMethod);
}
[Fact]
public void GenericMethodsInheritTheReflectedTypeOfTheirTemplate()
{
Type t = typeof(Derived);
MethodInfo moo = t.GetMethod("Moo");
Assert.Equal(t, moo.ReflectedType);
MethodInfo mooInst = moo.MakeGenericMethod(typeof(int));
Assert.Equal(t, mooInst.ReflectedType);
}
[Fact]
public void DeclaringMethodOfTypeParametersOfInheritedMethods()
{
Type t = typeof(Derived);
MethodInfo moo = t.GetMethod("Moo");
Assert.Equal(t, moo.ReflectedType);
Type theM = moo.GetGenericArguments()[0];
MethodBase moo1 = theM.DeclaringMethod;
Type reflectedTypeOfMoo1 = moo1.ReflectedType;
Assert.Equal(typeof(Base), reflectedTypeOfMoo1);
}
[Fact]
public void DeclaringMethodOfTypeParametersOfInheritedMethods2()
{
Type t = typeof(GDerived<int>);
MethodInfo moo = t.GetMethod("Moo");
Assert.Equal(t, moo.ReflectedType);
Type theM = moo.GetGenericArguments()[0];
MethodBase moo1 = theM.DeclaringMethod;
Type reflectedTypeOfMoo1 = moo1.ReflectedType;
Assert.Equal(typeof(GBase<>), reflectedTypeOfMoo1);
}
[Fact]
public void InheritedPropertyAccessors()
{
Type t = typeof(Derived);
PropertyInfo p = t.GetProperty(nameof(Base.MyProperty));
MethodInfo getter = p.GetMethod;
MethodInfo setter = p.SetMethod;
Assert.Equal(t, getter.ReflectedType);
Assert.Equal(t, setter.ReflectedType);
}
[Fact]
public void InheritedEventAccessors()
{
Type t = typeof(Derived);
EventInfo e = t.GetEvent(nameof(Base.MyEvent));
MethodInfo adder = e.AddMethod;
MethodInfo remover = e.RemoveMethod;
Assert.Equal(t, adder.ReflectedType);
Assert.Equal(t, remover.ReflectedType);
}
[Fact]
public void ReflectedTypeIsPartOfIdentity()
{
Type b = typeof(Base);
Type d = typeof(Derived);
{
EventInfo e = b.GetEvent(nameof(Base.MyEvent));
EventInfo ei = d.GetEvent(nameof(Derived.MyEvent));
Assert.False(e.Equals(ei));
}
{
FieldInfo f = b.GetField(nameof(Base.MyField));
FieldInfo fi = d.GetField(nameof(Derived.MyField));
Assert.False(f.Equals(fi));
}
{
MethodInfo m = b.GetMethod(nameof(Base.Moo));
MethodInfo mi = d.GetMethod(nameof(Derived.Moo));
Assert.False(m.Equals(mi));
}
{
PropertyInfo p = b.GetProperty(nameof(Base.MyProperty));
PropertyInfo pi = d.GetProperty(nameof(Derived.MyProperty));
Assert.False(p.Equals(pi));
}
}
[Fact]
public void FieldInfoReflectedTypeDoesNotSurviveRuntimeHandles()
{
Type t = typeof(Derived);
FieldInfo f = t.GetField(nameof(Base.MyField));
Assert.Equal(typeof(Derived), f.ReflectedType);
RuntimeFieldHandle h = f.FieldHandle;
FieldInfo f2 = FieldInfo.GetFieldFromHandle(h);
Assert.Equal(typeof(Base), f2.ReflectedType);
}
[Fact]
public void MethodInfoReflectedTypeDoesNotSurviveRuntimeHandles()
{
Type t = typeof(Derived);
MethodInfo m = t.GetMethod(nameof(Base.Moo));
Assert.Equal(typeof(Derived), m.ReflectedType);
RuntimeMethodHandle h = m.MethodHandle;
MethodBase m2 = MethodBase.GetMethodFromHandle(h);
Assert.Equal(typeof(Base), m2.ReflectedType);
}
[Fact]
public void GetCustomAttributesData()
{
MemberInfo[] m = typeof(MemberInfoTests).GetMember("SampleClass");
Assert.Equal(1, m.Count());
foreach (CustomAttributeData cad in m[0].GetCustomAttributesData())
{
if (cad.AttributeType == typeof(ComVisibleAttribute))
{
ConstructorInfo c = cad.Constructor;
Assert.False(c.IsStatic);
Assert.Equal(typeof(ComVisibleAttribute), c.DeclaringType);
ParameterInfo[] p = c.GetParameters();
Assert.Equal(1, p.Length);
Assert.Equal(typeof(bool), p[0].ParameterType);
return;
}
}
Assert.True(false, "Expected to find ComVisibleAttribute");
}
public static IEnumerable<object[]> EqualityOperator_TestData()
{
yield return new object[] { typeof(SampleClass) };
yield return new object[] { new MemberInfoTests().GetType() };
yield return new object[] { typeof(int) };
yield return new object[] { typeof(Dictionary<,>) };
}
[Theory]
[MemberData(nameof(EqualityOperator_TestData))]
public void EqualityOperator_Equal_ReturnsTrue(Type type)
{
MemberInfo[] members1 = GetOrderedMembers(type);
MemberInfo[] members2 = GetOrderedMembers(type);
Assert.Equal(members1.Length, members2.Length);
for (int i = 0; i < members1.Length; i++)
{
Assert.True(members1[i] == members2[i]);
Assert.False(members1[i] != members2[i]);
}
}
[Fact]
public static void HasSameMetadataDefinitionAs_GenericClassMembers()
{
Type tGeneric = typeof(GenericTestClass<>);
IEnumerable<MethodInfo> methodsOnGeneric = tGeneric.GetTypeInfo().GetDeclaredMethods(nameof(GenericTestClass<object>.Foo));
List<Type> typeInsts = new List<Type>();
foreach (MethodInfo method in methodsOnGeneric)
{
Debug.Assert(method.GetParameters().Length == 1);
Type parameterType = method.GetParameters()[0].ParameterType;
typeInsts.Add(tGeneric.MakeGenericType(parameterType));
}
typeInsts.Add(tGeneric);
CrossTestHasSameMethodDefinitionAs(typeInsts.ToArray());
}
private static void CrossTestHasSameMethodDefinitionAs(params Type[] types)
{
Assert.All(types,
delegate (Type type1)
{
Assert.All(type1.GenerateTestMemberList(),
delegate (MemberInfo m1)
{
MarkerAttribute mark1 = m1.GetCustomAttribute<MarkerAttribute>();
if (mark1 == null)
return;
Assert.All(types,
delegate (Type type2)
{
Assert.All(type2.GenerateTestMemberList(),
delegate (MemberInfo m2)
{
MarkerAttribute mark2 = m2.GetCustomAttribute<MarkerAttribute>();
if (mark2 == null)
return;
bool hasSameMetadata = m1.HasSameMetadataDefinitionAs(m2);
Assert.Equal(hasSameMetadata, m2.HasSameMetadataDefinitionAs(m1));
if (hasSameMetadata)
{
Assert.Equal(mark1.Mark, mark2.Mark);
}
else
{
Assert.NotEqual(mark1.Mark, mark2.Mark);
}
}
);
}
);
}
);
}
);
}
[Fact]
public static void HasSameMetadataDefinitionAs_ReflectedTypeNotPartOfComparison()
{
Type tBase = typeof(GenericTestClass<>);
Type tDerived = typeof(DerivedFromGenericTestClass<int>);
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
IEnumerable<MemberInfo> baseMembers = tBase.GetMembers(bf).Where(m => m.IsDefined(typeof(MarkerAttribute)));
baseMembers = baseMembers.Where(bm => !(bm is ConstructorInfo)); // Constructors cannot be seen from derived types.
IEnumerable<MemberInfo> derivedMembers = tDerived.GetMembers(bf).Where(m => m.IsDefined(typeof(MarkerAttribute)));
Assert.All(baseMembers,
delegate (MemberInfo baseMember)
{
MemberInfo matchingDerivedMember = derivedMembers.Single(dm => dm.HasSameMarkAs(baseMember));
Assert.True(baseMember.HasSameMetadataDefinitionAs(matchingDerivedMember));
Assert.True(matchingDerivedMember.HasSameMetadataDefinitionAs(matchingDerivedMember));
}
);
}
[Fact]
public static void HasSameMetadataDefinitionAs_ConstructedGenericMethods()
{
Type t1 = typeof(TestClassWithGenericMethod<>);
Type theT = t1.GetTypeInfo().GenericTypeParameters[0];
MethodInfo mooNormal = t1.GetConfirmedMethod(nameof(TestClassWithGenericMethod<object>.Moo), theT);
MethodInfo mooGeneric = t1.GetTypeInfo().GetDeclaredMethods("Moo").Single(m => m.IsGenericMethod);
MethodInfo mooInst = mooGeneric.MakeGenericMethod(typeof(int));
Assert.True(mooGeneric.HasSameMetadataDefinitionAs(mooInst));
Assert.True(mooInst.HasSameMetadataDefinitionAs(mooGeneric));
MethodInfo mooInst2 = mooGeneric.MakeGenericMethod(typeof(double));
Assert.True(mooInst2.HasSameMetadataDefinitionAs(mooInst));
Assert.True(mooInst.HasSameMetadataDefinitionAs(mooInst2));
Type t2 = typeof(TestClassWithGenericMethod<int>);
MethodInfo mooNormalOnT2 = t2.GetConfirmedMethod(nameof(TestClassWithGenericMethod<object>.Moo), typeof(int));
Assert.False(mooInst.HasSameMetadataDefinitionAs(mooNormalOnT2));
}
[Fact]
public static void HasSameMetadataDefinitionAs_NamedAndGenericTypes()
{
Type tnong = typeof(TestClass);
Type tnong2 = typeof(TestClass2);
Type tg = typeof(GenericTestClass<>);
Type tginst1 = typeof(GenericTestClass<int>);
Type tginst2 = typeof(GenericTestClass<string>);
Assert.True(tnong.HasSameMetadataDefinitionAs(tnong));
Assert.True(tnong2.HasSameMetadataDefinitionAs(tnong2));
Assert.True(tg.HasSameMetadataDefinitionAs(tg));
Assert.True(tginst1.HasSameMetadataDefinitionAs(tginst1));
Assert.True(tginst2.HasSameMetadataDefinitionAs(tginst2));
Assert.True(tg.HasSameMetadataDefinitionAs(tginst1));
Assert.True(tginst1.HasSameMetadataDefinitionAs(tginst1));
Assert.True(tginst1.HasSameMetadataDefinitionAs(tginst2));
Assert.False(tnong.HasSameMetadataDefinitionAs(tnong2));
Assert.False(tnong.HasSameMetadataDefinitionAs(tg));
Assert.False(tg.HasSameMetadataDefinitionAs(tnong));
Assert.False(tnong.HasSameMetadataDefinitionAs(tginst1));
Assert.False(tginst1.HasSameMetadataDefinitionAs(tnong));
}
[Fact]
[ActiveIssue("https://github.com/mono/mono/issues/15069", TestRuntimes.Mono)]
public static void HasSameMetadataDefinitionAs_GenericTypeParameters()
{
Type theT = typeof(GenericTestClass<>).GetTypeInfo().GenericTypeParameters[0];
Type theT2 = typeof(TestClassWithGenericMethod<>).GetTypeInfo().GenericTypeParameters[0];
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding;
MethodInfo mooNong = theT2.GetMethod("Moo", bf, null, new Type[] { theT2 }, null);
MethodInfo mooGeneric = typeof(TestClassWithGenericMethod<>).GetTypeInfo().GetDeclaredMethods("Moo").Single(m => m.IsGenericMethod);
Type theM = mooGeneric.GetGenericArguments()[0];
Assert.True(theT.HasSameMetadataDefinitionAs(theT));
Assert.False(theT2.HasSameMetadataDefinitionAs(theT));
Assert.False(theT.HasSameMetadataDefinitionAs(theT2));
Assert.False(theM.HasSameMetadataDefinitionAs(theT));
Assert.False(theM.HasSameMetadataDefinitionAs(theT2));
Assert.False(theT2.HasSameMetadataDefinitionAs(theM));
Assert.False(theT.HasSameMetadataDefinitionAs(theM));
}
[Fact]
public static void HasSameMetadataDefinitionAs_Twins()
{
// This situation is particularly treacherous for CoreRT as the .NET Native toolchain can and does assign
// the same native metadata tokens to identically structured members in unrelated types.
Type twin1 = typeof(Twin1);
Type twin2 = typeof(Twin2);
Assert.All(twin1.GenerateTestMemberList(),
delegate (MemberInfo m1)
{
Assert.All(twin2.GenerateTestMemberList(),
delegate (MemberInfo m2)
{
Assert.False(m1.HasSameMetadataDefinitionAs(m2));
}
);
}
);
}
private class Twin1
{
public Twin1() { }
public int Field1;
public Action Event1;
public void Method1() { }
public int Property1 { get; set; }
}
private class Twin2
{
public Twin2() { }
public int Field1;
public Action Event1;
public void Method1() { }
public int Property1 { get; set; }
}
[Fact]
[OuterLoop] // Time-consuming.
public static void HasSameMetadataDefinitionAs_CrossAssembly()
{
// Make sure that identical tokens in different assemblies don't confuse the api.
foreach (Type t1 in typeof(object).Assembly.DefinedTypes)
{
foreach (Type t2 in typeof(MemberInfoTests).Assembly.DefinedTypes)
{
Assert.False(t1.HasSameMetadataDefinitionAs(t2));
}
}
}
[Theory]
[MemberData(nameof(NegativeTypeData))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34328", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
public static void HasSameMetadataDefinitionAs_Negative_NonRuntimeType(Type type)
{
Type mockType = new MockType();
Assert.False(type.HasSameMetadataDefinitionAs(mockType));
Assert.All(type.GenerateTestMemberList(),
delegate (MemberInfo member)
{
Assert.False(member.HasSameMetadataDefinitionAs(mockType));
}
);
}
[Theory]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34328", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[MemberData(nameof(NegativeTypeData))]
public static void HasSameMetadataDefinitionAs_Negative_Null(Type type)
{
AssertExtensions.Throws<ArgumentNullException>("other", () => type.HasSameMetadataDefinitionAs(null));
Assert.All(type.GenerateTestMemberList(),
delegate (MemberInfo member)
{
AssertExtensions.Throws<ArgumentNullException>("other", () => member.HasSameMetadataDefinitionAs(null));
}
);
}
public static IEnumerable<object[]> NegativeTypeData => NegativeTypeDataRaw.Select(t => new object[] { t });
private static IEnumerable<Type> NegativeTypeDataRaw
{
get
{
yield return typeof(TestClass);
yield return typeof(GenericTestClass<>);
yield return typeof(GenericTestClass<int>);
yield return typeof(int[]);
yield return typeof(int).MakeArrayType(1);
yield return typeof(int[,]);
yield return typeof(int).MakeByRefType();
yield return typeof(int).MakePointerType();
yield return typeof(GenericTestClass<>).GetTypeInfo().GenericTypeParameters[0];
if (PlatformDetection.IsWindows)
yield return Type.GetTypeFromCLSID(new Guid("DCA66D18-E253-4695-9E08-35B54420AFA2"));
}
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/31648", TestRuntimes.Mono)]
public static void HasSameMetadataDefinitionAs__CornerCase_HasElementTypes()
{
// HasSameMetadataDefinitionAs on an array/byref/pointer type is uninteresting (they'll never be an actual member of a type)
// but for future compat, we'll establish their known behavior here. Since these types all return a MetadataToken of 0x02000000,
// they'll all "match" each other.
Type[] types =
{
typeof(int[]),
typeof(double[]),
typeof(int).MakeArrayType(1),
typeof(double).MakeArrayType(1),
typeof(int[,]),
typeof(double[,]),
typeof(int).MakeByRefType(),
typeof(double).MakeByRefType(),
typeof(int).MakePointerType(),
typeof(double).MakePointerType(),
};
Assert.All(types,
delegate (Type t1)
{
Assert.All(types, t2 => Assert.True(t1.HasSameMetadataDefinitionAs(t2)));
}
);
}
[Fact]
public static void HasSameMetadataDefinitionAs_CornerCase_ArrayMethods()
{
// The magic methods and constructors exposed on array types do not have metadata backing and report a MetadataToken of 0x06000000
// and hence compare identically with each other. This may be surprising but this test records that fact for future compat.
//
Type[] arrayTypes =
{
typeof(int[]),
typeof(double[]),
typeof(int).MakeArrayType(1),
typeof(double).MakeArrayType(1),
typeof(int[,]),
typeof(double[,]),
};
List<MemberInfo> members = new List<MemberInfo>();
foreach (Type arrayType in arrayTypes)
{
foreach (MemberInfo member in arrayType.GetMembers(BindingFlags.Public|BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
if (member is MethodBase)
{
members.Add(member);
}
}
}
Assert.All(members,
delegate (MemberInfo member1)
{
Assert.All(members,
delegate (MemberInfo member2)
{
if (member1.MemberType == member2.MemberType)
Assert.True(member1.HasSameMetadataDefinitionAs(member2));
else
Assert.False(member1.HasSameMetadataDefinitionAs(member2));
}
);
}
);
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34328", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[PlatformSpecific(TestPlatforms.Windows)]
public static void HasSameMetadataDefinitionAs_CornerCase_CLSIDConstructor()
{
// HasSameMetadataDefinitionAs on a GetTypeFromCLSID type is uninteresting (they'll never be an actual member of a type)
// but for future compat, we'll establish their known behavior here. Since these types and their constructors all return the same
// MetadataToken, they'll all "match" each other.
Type t1 = Type.GetTypeFromCLSID(new Guid("23A54889-7738-4F16-8AB2-CB23F8E756BE"));
Type t2 = Type.GetTypeFromCLSID(new Guid("DCA66D18-E253-4695-9E08-35B54420AFA2"));
Assert.True(t1.HasSameMetadataDefinitionAs(t2));
ConstructorInfo c1 = t1.GetConfirmedConstructor();
ConstructorInfo c2 = t2.GetConfirmedConstructor();
Assert.True(c1.HasSameMetadataDefinitionAs(c2));
}
private class TestClassWithGenericMethod<T>
{
public void Moo(T t) { }
public void Moo<M>(M m) { }
}
private class TestClass
{
public void Foo() { }
public void Foo(object o) { }
public void Foo(string s) { }
public void Bar() { }
}
private class TestClass2 { }
private class GenericTestClass<T>
{
[Marker(1)]
public void Foo(object o) { }
[Marker(2)]
public void Foo(int i) { }
[Marker(3)]
public void Foo(T t) { }
[Marker(4)]
public void Foo(double d) { }
[Marker(5)]
public void Foo(string s) { }
[Marker(6)]
public void Foo(int[] s) { }
[Marker(7)]
public void Foo<U>(U t) { }
[Marker(8)]
public void Foo<U>(T t) { }
[Marker(9)]
public void Foo<U, V>(T t) { }
[Marker(101)]
public GenericTestClass() { }
[Marker(102)]
public GenericTestClass(T t) { }
[Marker(103)]
public GenericTestClass(int t) { }
[Marker(201)]
public int Field1;
[Marker(202)]
public int Field2;
[Marker(203)]
public T Field3;
[Marker(301)]
public int Property1 { get { throw null; } set { throw null; } }
[Marker(302)]
public int Property2 { get { throw null; } set { throw null; } }
[Marker(303)]
public T Property3 { get { throw null; } set { throw null; } }
[Marker(401)]
public event Action Event1 { add { } remove { } }
[Marker(402)]
public event Action<int> Event2 { add { } remove { } }
[Marker(403)]
public event Action<T> Event3 { add { } remove { } }
}
private class DerivedFromGenericTestClass<T> : GenericTestClass<T> { }
private MemberInfo[] GetMembers(Type type)
{
return type.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
}
private IEnumerable<int> GetMetadataTokens(Type type)
{
return type.GetTypeInfo().GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Select(m => m.HasMetadataToken() ? m.MetadataToken : 0);
}
private MemberInfo[] GetOrderedMembers(Type type) => GetMembers(type).OrderBy(member => member.Name).ToArray();
private class Base
{
public event Action MyEvent { add { } remove { } }
#pragma warning disable 0649
public int MyField;
#pragma warning restore 0649
public int MyProperty { get; set; }
public int MyProperty1 { get; private set; }
public int MyProperty2 { private get; set; }
public void Moo<M>() { }
}
private class Derived : Base
{
}
private class GBase<T>
{
public void Moo<M>() { }
}
private class GDerived<T> : GBase<T>
{
}
#pragma warning disable 0067, 0169
[ComVisible(false)]
public class SampleClass
{
public int PublicField;
private int PrivateField;
public SampleClass(bool y) { }
private SampleClass(int x) { }
public void PublicMethod() { }
private void PrivateMethod() { }
public int PublicProp { get; set; }
private int PrivateProp { get; set; }
public event EventHandler PublicEvent;
private event EventHandler PrivateEvent;
}
#pragma warning restore 0067, 0169
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)]
public class MarkerAttribute : Attribute
{
public MarkerAttribute(int mark)
{
Mark = mark;
}
public readonly int Mark;
}
internal static class Extensions
{
internal static bool HasSameMarkAs(this MemberInfo m1, MemberInfo m2)
{
MarkerAttribute marker1 = m1.GetCustomAttribute<MarkerAttribute>();
Assert.NotNull(marker1);
MarkerAttribute marker2 = m2.GetCustomAttribute<MarkerAttribute>();
Assert.NotNull(marker2);
return marker1.Mark == marker2.Mark;
}
internal static MethodInfo GetConfirmedMethod(this Type t, string name, params Type[] parameterTypes)
{
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.ExactBinding;
MethodInfo method = t.GetMethod(name, bf, null, parameterTypes, null);
Assert.NotNull(method);
return method;
}
internal static ConstructorInfo GetConfirmedConstructor(this Type t, params Type[] parameterTypes)
{
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.ExactBinding;
ConstructorInfo ctor = t.GetConstructor(bf, null, parameterTypes, null);
Assert.NotNull(ctor);
return ctor;
}
internal static IEnumerable<MemberInfo> GenerateTestMemberList(this Type t)
{
if (t.IsGenericTypeDefinition)
{
foreach (Type gp in t.GetTypeInfo().GenericTypeParameters)
{
yield return gp;
}
}
foreach (MemberInfo m in t.GetTypeInfo().DeclaredMembers)
{
yield return m;
MethodInfo method = m as MethodInfo;
if (method != null && method.IsGenericMethodDefinition)
{
foreach (Type mgp in method.GetGenericArguments())
{
yield return mgp;
}
yield return method.MakeGenericMethod(method.GetGenericArguments().Select(ga => typeof(object)).ToArray());
}
}
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/SerializationHeaderRecord.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.Binary;
using System.IO;
namespace System.Runtime.Serialization.Formatters.Binary
{
// The Following classes read and write the binary records
internal sealed class SerializationHeaderRecord : IStreamable
{
internal const int BinaryFormatterMajorVersion = 1;
internal const int BinaryFormatterMinorVersion = 0;
internal BinaryHeaderEnum _binaryHeaderEnum;
internal int _topId;
internal int _headerId;
internal int _majorVersion;
internal int _minorVersion;
internal SerializationHeaderRecord() { }
internal SerializationHeaderRecord(BinaryHeaderEnum binaryHeaderEnum, int topId, int headerId, int majorVersion, int minorVersion)
{
_binaryHeaderEnum = binaryHeaderEnum;
_topId = topId;
_headerId = headerId;
_majorVersion = majorVersion;
_minorVersion = minorVersion;
}
public void Write(BinaryFormatterWriter output)
{
_majorVersion = BinaryFormatterMajorVersion;
_minorVersion = BinaryFormatterMinorVersion;
output.WriteByte((byte)_binaryHeaderEnum);
output.WriteInt32(_topId);
output.WriteInt32(_headerId);
output.WriteInt32(BinaryFormatterMajorVersion);
output.WriteInt32(BinaryFormatterMinorVersion);
}
private static int GetInt32(byte[] buffer, int index) =>
BinaryPrimitives.ReadInt32LittleEndian(buffer.AsSpan(index));
public void Read(BinaryParser input)
{
byte[] headerBytes = input.ReadBytes(17);
// Throw if we couldnt read header bytes
if (headerBytes.Length < 17)
{
throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF);
}
_majorVersion = GetInt32(headerBytes, 9);
if (_majorVersion > BinaryFormatterMajorVersion)
{
throw new SerializationException(SR.Format(SR.Serialization_InvalidFormat, BitConverter.ToString(headerBytes)));
}
// binaryHeaderEnum has already been read
_binaryHeaderEnum = (BinaryHeaderEnum)headerBytes[0];
_topId = GetInt32(headerBytes, 1);
_headerId = GetInt32(headerBytes, 5);
_minorVersion = GetInt32(headerBytes, 13);
}
}
}
|
// 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.Binary;
using System.IO;
namespace System.Runtime.Serialization.Formatters.Binary
{
// The Following classes read and write the binary records
internal sealed class SerializationHeaderRecord : IStreamable
{
internal const int BinaryFormatterMajorVersion = 1;
internal const int BinaryFormatterMinorVersion = 0;
internal BinaryHeaderEnum _binaryHeaderEnum;
internal int _topId;
internal int _headerId;
internal int _majorVersion;
internal int _minorVersion;
internal SerializationHeaderRecord() { }
internal SerializationHeaderRecord(BinaryHeaderEnum binaryHeaderEnum, int topId, int headerId, int majorVersion, int minorVersion)
{
_binaryHeaderEnum = binaryHeaderEnum;
_topId = topId;
_headerId = headerId;
_majorVersion = majorVersion;
_minorVersion = minorVersion;
}
public void Write(BinaryFormatterWriter output)
{
_majorVersion = BinaryFormatterMajorVersion;
_minorVersion = BinaryFormatterMinorVersion;
output.WriteByte((byte)_binaryHeaderEnum);
output.WriteInt32(_topId);
output.WriteInt32(_headerId);
output.WriteInt32(BinaryFormatterMajorVersion);
output.WriteInt32(BinaryFormatterMinorVersion);
}
private static int GetInt32(byte[] buffer, int index) =>
BinaryPrimitives.ReadInt32LittleEndian(buffer.AsSpan(index));
public void Read(BinaryParser input)
{
byte[] headerBytes = input.ReadBytes(17);
// Throw if we couldnt read header bytes
if (headerBytes.Length < 17)
{
throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF);
}
_majorVersion = GetInt32(headerBytes, 9);
if (_majorVersion > BinaryFormatterMajorVersion)
{
throw new SerializationException(SR.Format(SR.Serialization_InvalidFormat, BitConverter.ToString(headerBytes)));
}
// binaryHeaderEnum has already been read
_binaryHeaderEnum = (BinaryHeaderEnum)headerBytes[0];
_topId = GetInt32(headerBytes, 1);
_headerId = GetInt32(headerBytes, 5);
_minorVersion = GetInt32(headerBytes, 13);
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Reflection.Metadata/src/System/Reflection/Throw.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
namespace System.Reflection
{
// This file defines an internal class used to throw exceptions. The main purpose is to reduce code size.
// Also it improves the likelihood that callers will be inlined.
internal static class Throw
{
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidCast()
{
throw new InvalidCastException();
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidArgument(string message, string parameterName)
{
throw new ArgumentException(message, parameterName);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidArgument_OffsetForVirtualHeapHandle()
{
throw new ArgumentException(SR.CantGetOffsetForVirtualHeapHandle, "handle");
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static Exception InvalidArgument_UnexpectedHandleKind(HandleKind kind)
{
throw new ArgumentException(SR.Format(SR.UnexpectedHandleKind, kind));
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static Exception InvalidArgument_Handle(string parameterName)
{
throw new ArgumentException(SR.InvalidHandle, parameterName);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void SignatureNotVarArg()
{
throw new InvalidOperationException(SR.SignatureNotVarArg);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ControlFlowBuilderNotAvailable()
{
throw new InvalidOperationException(SR.ControlFlowBuilderNotAvailable);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperationBuilderAlreadyLinked()
{
throw new InvalidOperationException(SR.BuilderAlreadyLinked);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperation(string message)
{
throw new InvalidOperationException(message);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperation_LabelNotMarked(int id)
{
throw new InvalidOperationException(SR.Format(SR.LabelNotMarked, id));
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void LabelDoesntBelongToBuilder(string parameterName)
{
throw new ArgumentException(SR.LabelDoesntBelongToBuilder, parameterName);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void HeapHandleRequired()
{
throw new ArgumentException(SR.NotMetadataHeapHandle, "handle");
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void EntityOrUserStringHandleRequired()
{
throw new ArgumentException(SR.NotMetadataTableOrUserStringHandle, "handle");
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidToken()
{
throw new ArgumentException(SR.InvalidToken, "token");
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentNull(string parameterName)
{
throw new ArgumentNullException(parameterName);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentEmptyString(string parameterName)
{
throw new ArgumentException(SR.ExpectedNonEmptyString, parameterName);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentEmptyArray(string parameterName)
{
throw new ArgumentException(SR.ExpectedNonEmptyArray, parameterName);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ValueArgumentNull()
{
throw new ArgumentNullException("value");
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void BuilderArgumentNull()
{
throw new ArgumentNullException("builder");
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentOutOfRange(string parameterName)
{
throw new ArgumentOutOfRangeException(parameterName);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentOutOfRange(string parameterName, string message)
{
throw new ArgumentOutOfRangeException(parameterName, message);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void BlobTooLarge(string parameterName)
{
throw new ArgumentOutOfRangeException(parameterName, SR.BlobTooLarge);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void IndexOutOfRange()
{
throw new ArgumentOutOfRangeException("index");
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TableIndexOutOfRange()
{
throw new ArgumentOutOfRangeException("tableIndex");
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ValueArgumentOutOfRange()
{
throw new ArgumentOutOfRangeException("value");
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void OutOfBounds()
{
throw new BadImageFormatException(SR.OutOfBoundsRead);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void WriteOutOfBounds()
{
throw new InvalidOperationException(SR.OutOfBoundsWrite);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidCodedIndex()
{
throw new BadImageFormatException(SR.InvalidCodedIndex);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidHandle()
{
throw new BadImageFormatException(SR.InvalidHandle);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidCompressedInteger()
{
throw new BadImageFormatException(SR.InvalidCompressedInteger);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidSerializedString()
{
throw new BadImageFormatException(SR.InvalidSerializedString);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ImageTooSmall()
{
throw new BadImageFormatException(SR.ImageTooSmall);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ImageTooSmallOrContainsInvalidOffsetOrCount()
{
throw new BadImageFormatException(SR.ImageTooSmallOrContainsInvalidOffsetOrCount);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ReferenceOverflow()
{
throw new BadImageFormatException(SR.RowIdOrHeapOffsetTooLarge);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TableNotSorted(TableIndex tableIndex)
{
throw new BadImageFormatException(SR.Format(SR.MetadataTableNotSorted, tableIndex));
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperation_TableNotSorted(TableIndex tableIndex)
{
throw new InvalidOperationException(SR.Format(SR.MetadataTableNotSorted, tableIndex));
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperation_PEImageNotAvailable()
{
throw new InvalidOperationException(SR.PEImageNotAvailable);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TooManySubnamespaces()
{
throw new BadImageFormatException(SR.TooManySubnamespaces);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ValueOverflow()
{
throw new BadImageFormatException(SR.ValueTooLarge);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void SequencePointValueOutOfRange()
{
throw new BadImageFormatException(SR.SequencePointValueOutOfRange);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void HeapSizeLimitExceeded(HeapIndex heap)
{
throw new ImageFormatLimitationException(SR.Format(SR.HeapSizeLimitExceeded, heap));
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void PEReaderDisposed()
{
throw new ObjectDisposedException(nameof(PortableExecutable.PEReader));
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
namespace System.Reflection
{
// This file defines an internal class used to throw exceptions. The main purpose is to reduce code size.
// Also it improves the likelihood that callers will be inlined.
internal static class Throw
{
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidCast()
{
throw new InvalidCastException();
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidArgument(string message, string parameterName)
{
throw new ArgumentException(message, parameterName);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidArgument_OffsetForVirtualHeapHandle()
{
throw new ArgumentException(SR.CantGetOffsetForVirtualHeapHandle, "handle");
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static Exception InvalidArgument_UnexpectedHandleKind(HandleKind kind)
{
throw new ArgumentException(SR.Format(SR.UnexpectedHandleKind, kind));
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static Exception InvalidArgument_Handle(string parameterName)
{
throw new ArgumentException(SR.InvalidHandle, parameterName);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void SignatureNotVarArg()
{
throw new InvalidOperationException(SR.SignatureNotVarArg);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ControlFlowBuilderNotAvailable()
{
throw new InvalidOperationException(SR.ControlFlowBuilderNotAvailable);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperationBuilderAlreadyLinked()
{
throw new InvalidOperationException(SR.BuilderAlreadyLinked);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperation(string message)
{
throw new InvalidOperationException(message);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperation_LabelNotMarked(int id)
{
throw new InvalidOperationException(SR.Format(SR.LabelNotMarked, id));
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void LabelDoesntBelongToBuilder(string parameterName)
{
throw new ArgumentException(SR.LabelDoesntBelongToBuilder, parameterName);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void HeapHandleRequired()
{
throw new ArgumentException(SR.NotMetadataHeapHandle, "handle");
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void EntityOrUserStringHandleRequired()
{
throw new ArgumentException(SR.NotMetadataTableOrUserStringHandle, "handle");
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidToken()
{
throw new ArgumentException(SR.InvalidToken, "token");
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentNull(string parameterName)
{
throw new ArgumentNullException(parameterName);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentEmptyString(string parameterName)
{
throw new ArgumentException(SR.ExpectedNonEmptyString, parameterName);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentEmptyArray(string parameterName)
{
throw new ArgumentException(SR.ExpectedNonEmptyArray, parameterName);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ValueArgumentNull()
{
throw new ArgumentNullException("value");
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void BuilderArgumentNull()
{
throw new ArgumentNullException("builder");
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentOutOfRange(string parameterName)
{
throw new ArgumentOutOfRangeException(parameterName);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentOutOfRange(string parameterName, string message)
{
throw new ArgumentOutOfRangeException(parameterName, message);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void BlobTooLarge(string parameterName)
{
throw new ArgumentOutOfRangeException(parameterName, SR.BlobTooLarge);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void IndexOutOfRange()
{
throw new ArgumentOutOfRangeException("index");
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TableIndexOutOfRange()
{
throw new ArgumentOutOfRangeException("tableIndex");
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ValueArgumentOutOfRange()
{
throw new ArgumentOutOfRangeException("value");
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void OutOfBounds()
{
throw new BadImageFormatException(SR.OutOfBoundsRead);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void WriteOutOfBounds()
{
throw new InvalidOperationException(SR.OutOfBoundsWrite);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidCodedIndex()
{
throw new BadImageFormatException(SR.InvalidCodedIndex);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidHandle()
{
throw new BadImageFormatException(SR.InvalidHandle);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidCompressedInteger()
{
throw new BadImageFormatException(SR.InvalidCompressedInteger);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidSerializedString()
{
throw new BadImageFormatException(SR.InvalidSerializedString);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ImageTooSmall()
{
throw new BadImageFormatException(SR.ImageTooSmall);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ImageTooSmallOrContainsInvalidOffsetOrCount()
{
throw new BadImageFormatException(SR.ImageTooSmallOrContainsInvalidOffsetOrCount);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ReferenceOverflow()
{
throw new BadImageFormatException(SR.RowIdOrHeapOffsetTooLarge);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TableNotSorted(TableIndex tableIndex)
{
throw new BadImageFormatException(SR.Format(SR.MetadataTableNotSorted, tableIndex));
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperation_TableNotSorted(TableIndex tableIndex)
{
throw new InvalidOperationException(SR.Format(SR.MetadataTableNotSorted, tableIndex));
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperation_PEImageNotAvailable()
{
throw new InvalidOperationException(SR.PEImageNotAvailable);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TooManySubnamespaces()
{
throw new BadImageFormatException(SR.TooManySubnamespaces);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ValueOverflow()
{
throw new BadImageFormatException(SR.ValueTooLarge);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void SequencePointValueOutOfRange()
{
throw new BadImageFormatException(SR.SequencePointValueOutOfRange);
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void HeapSizeLimitExceeded(HeapIndex heap)
{
throw new ImageFormatLimitationException(SR.Format(SR.HeapSizeLimitExceeded, heap));
}
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void PEReaderDisposed()
{
throw new ObjectDisposedException(nameof(PortableExecutable.PEReader));
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/Methodical/Arrays/misc/arrres_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="arrres.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="arrres.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/Common/src/Microsoft/Win32/SafeHandles/Asn1SafeHandles.Unix.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
namespace Microsoft.Win32.SafeHandles
{
internal sealed class SafeAsn1ObjectHandle : SafeHandle
{
public SafeAsn1ObjectHandle() :
base(IntPtr.Zero, ownsHandle: true)
{
}
protected override bool ReleaseHandle()
{
Interop.Crypto.Asn1ObjectFree(handle);
SetHandle(IntPtr.Zero);
return true;
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
}
internal sealed class SafeAsn1BitStringHandle : SafeHandle
{
public SafeAsn1BitStringHandle() :
base(IntPtr.Zero, ownsHandle: true)
{
}
protected override bool ReleaseHandle()
{
Interop.Crypto.Asn1BitStringFree(handle);
SetHandle(IntPtr.Zero);
return true;
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
}
internal sealed class SafeAsn1OctetStringHandle : SafeHandle
{
public SafeAsn1OctetStringHandle() :
base(IntPtr.Zero, ownsHandle: true)
{
}
protected override bool ReleaseHandle()
{
Interop.Crypto.Asn1OctetStringFree(handle);
SetHandle(IntPtr.Zero);
return true;
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
}
internal sealed class SafeSharedAsn1IntegerHandle : SafeInteriorHandle
{
public SafeSharedAsn1IntegerHandle() :
base(IntPtr.Zero, ownsHandle: true)
{
}
}
internal sealed class SafeSharedAsn1OctetStringHandle : SafeInteriorHandle
{
public SafeSharedAsn1OctetStringHandle() :
base(IntPtr.Zero, ownsHandle: 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;
using System.Runtime.InteropServices;
namespace Microsoft.Win32.SafeHandles
{
internal sealed class SafeAsn1ObjectHandle : SafeHandle
{
public SafeAsn1ObjectHandle() :
base(IntPtr.Zero, ownsHandle: true)
{
}
protected override bool ReleaseHandle()
{
Interop.Crypto.Asn1ObjectFree(handle);
SetHandle(IntPtr.Zero);
return true;
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
}
internal sealed class SafeAsn1BitStringHandle : SafeHandle
{
public SafeAsn1BitStringHandle() :
base(IntPtr.Zero, ownsHandle: true)
{
}
protected override bool ReleaseHandle()
{
Interop.Crypto.Asn1BitStringFree(handle);
SetHandle(IntPtr.Zero);
return true;
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
}
internal sealed class SafeAsn1OctetStringHandle : SafeHandle
{
public SafeAsn1OctetStringHandle() :
base(IntPtr.Zero, ownsHandle: true)
{
}
protected override bool ReleaseHandle()
{
Interop.Crypto.Asn1OctetStringFree(handle);
SetHandle(IntPtr.Zero);
return true;
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
}
internal sealed class SafeSharedAsn1IntegerHandle : SafeInteriorHandle
{
public SafeSharedAsn1IntegerHandle() :
base(IntPtr.Zero, ownsHandle: true)
{
}
}
internal sealed class SafeSharedAsn1OctetStringHandle : SafeInteriorHandle
{
public SafeSharedAsn1OctetStringHandle() :
base(IntPtr.Zero, ownsHandle: true)
{
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Net.Http/tests/UnitTests/Headers/CacheControlHeaderValueTest.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Net.Http.Tests
{
public class CacheControlHeaderValueTest
{
[Fact]
public void Properties_SetAndGetAllProperties_SetValueReturnedInGetter()
{
CacheControlHeaderValue cacheControl = new CacheControlHeaderValue();
// Bool properties
cacheControl.NoCache = true;
Assert.True(cacheControl.NoCache);
cacheControl.NoStore = true;
Assert.True(cacheControl.NoStore);
cacheControl.MaxStale = true;
Assert.True(cacheControl.MaxStale);
cacheControl.NoTransform = true;
Assert.True(cacheControl.NoTransform);
cacheControl.OnlyIfCached = true;
Assert.True(cacheControl.OnlyIfCached);
cacheControl.Public = true;
Assert.True(cacheControl.Public);
cacheControl.Private = true;
Assert.True(cacheControl.Private);
cacheControl.MustRevalidate = true;
Assert.True(cacheControl.MustRevalidate);
cacheControl.ProxyRevalidate = true;
Assert.True(cacheControl.ProxyRevalidate);
// TimeSpan properties
TimeSpan timeSpan = new TimeSpan(1, 2, 3);
cacheControl.MaxAge = timeSpan;
Assert.Equal(timeSpan, cacheControl.MaxAge);
cacheControl.SharedMaxAge = timeSpan;
Assert.Equal(timeSpan, cacheControl.SharedMaxAge);
cacheControl.MaxStaleLimit = timeSpan;
Assert.Equal(timeSpan, cacheControl.MaxStaleLimit);
cacheControl.MinFresh = timeSpan;
Assert.Equal(timeSpan, cacheControl.MinFresh);
// String collection properties
Assert.NotNull(cacheControl.NoCacheHeaders);
AssertExtensions.Throws<ArgumentException>("item", () => { cacheControl.NoCacheHeaders.Add(null); });
Assert.Throws<FormatException>(() => { cacheControl.NoCacheHeaders.Add("invalid token"); });
cacheControl.NoCacheHeaders.Add("token");
Assert.Equal(1, cacheControl.NoCacheHeaders.Count);
Assert.Equal("token", cacheControl.NoCacheHeaders.First());
Assert.NotNull(cacheControl.PrivateHeaders);
AssertExtensions.Throws<ArgumentException>("item", () => { cacheControl.PrivateHeaders.Add(null); });
Assert.Throws<FormatException>(() => { cacheControl.PrivateHeaders.Add("invalid token"); });
cacheControl.PrivateHeaders.Add("token");
Assert.Equal(1, cacheControl.PrivateHeaders.Count);
Assert.Equal("token", cacheControl.PrivateHeaders.First());
// NameValueHeaderValue collection property
Assert.NotNull(cacheControl.Extensions);
Assert.Throws<ArgumentNullException>(() => { cacheControl.Extensions.Add(null); });
cacheControl.Extensions.Add(new NameValueHeaderValue("name", "value"));
Assert.Equal(1, cacheControl.Extensions.Count);
Assert.Equal(new NameValueHeaderValue("name", "value"), cacheControl.Extensions.First());
}
[Fact]
public void ToString_UseRequestDirectiveValues_AllSerializedCorrectly()
{
CacheControlHeaderValue cacheControl = new CacheControlHeaderValue();
Assert.Equal("", cacheControl.ToString());
// Note that we allow all combinations of all properties even though the RFC specifies rules what value
// can be used together.
// Also for property pairs (bool property + collection property) like 'NoCache' and 'NoCacheHeaders' the
// caller needs to set the bool property in order for the collection to be populated as string.
// Cache Request Directive sample
cacheControl.NoStore = true;
Assert.Equal("no-store", cacheControl.ToString());
cacheControl.NoCache = true;
Assert.Equal("no-store, no-cache", cacheControl.ToString());
cacheControl.MaxAge = new TimeSpan(0, 1, 10);
Assert.Equal("no-store, no-cache, max-age=70", cacheControl.ToString());
cacheControl.MaxStale = true;
Assert.Equal("no-store, no-cache, max-age=70, max-stale", cacheControl.ToString());
cacheControl.MaxStaleLimit = new TimeSpan(0, 2, 5);
Assert.Equal("no-store, no-cache, max-age=70, max-stale=125", cacheControl.ToString());
cacheControl.MinFresh = new TimeSpan(0, 3, 0);
Assert.Equal("no-store, no-cache, max-age=70, max-stale=125, min-fresh=180", cacheControl.ToString());
cacheControl = new CacheControlHeaderValue();
cacheControl.NoTransform = true;
Assert.Equal("no-transform", cacheControl.ToString());
cacheControl.OnlyIfCached = true;
Assert.Equal("no-transform, only-if-cached", cacheControl.ToString());
cacheControl.Extensions.Add(new NameValueHeaderValue("custom"));
cacheControl.Extensions.Add(new NameValueHeaderValue("customName", "customValue"));
Assert.Equal("no-transform, only-if-cached, custom, customName=customValue", cacheControl.ToString());
cacheControl = new CacheControlHeaderValue();
cacheControl.Extensions.Add(new NameValueHeaderValue("custom"));
Assert.Equal("custom", cacheControl.ToString());
}
[Fact]
public void ToString_UseResponseDirectiveValues_AllSerializedCorrectly()
{
CacheControlHeaderValue cacheControl = new CacheControlHeaderValue();
Assert.Equal("", cacheControl.ToString());
cacheControl.NoCache = true;
Assert.Equal("no-cache", cacheControl.ToString());
cacheControl.NoCacheHeaders.Add("token1");
Assert.Equal("no-cache=\"token1\"", cacheControl.ToString());
cacheControl.Public = true;
Assert.Equal("public, no-cache=\"token1\"", cacheControl.ToString());
cacheControl = new CacheControlHeaderValue();
cacheControl.Private = true;
Assert.Equal("private", cacheControl.ToString());
cacheControl.PrivateHeaders.Add("token2");
cacheControl.PrivateHeaders.Add("token3");
Assert.Equal("private=\"token2, token3\"", cacheControl.ToString());
cacheControl.MustRevalidate = true;
Assert.Equal("must-revalidate, private=\"token2, token3\"", cacheControl.ToString());
cacheControl.ProxyRevalidate = true;
Assert.Equal("must-revalidate, proxy-revalidate, private=\"token2, token3\"", cacheControl.ToString());
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void ToString_NegativeValues_UsesMinusSignRegardlessOfCurrentCulture()
{
RemoteExecutor.Invoke(() =>
{
var cacheControl = new CacheControlHeaderValue()
{
MaxAge = new TimeSpan(0, 0, -1),
MaxStale = true,
MaxStaleLimit = new TimeSpan(0, 0, -2),
MinFresh = new TimeSpan(0, 0, -3),
SharedMaxAge = new TimeSpan(0, 0, -4)
};
var ci = (CultureInfo)CultureInfo.CurrentCulture.Clone();
ci.NumberFormat.NegativeSign = "n";
CultureInfo.CurrentCulture = ci;
Assert.Equal("max-age=-1, s-maxage=-4, max-stale=-2, min-fresh=-3", cacheControl.ToString());
}).Dispose();
}
[Fact]
public void GetHashCode_CompareValuesWithBoolFieldsSet_MatchExpectation()
{
// Verify that different bool fields return different hash values.
CacheControlHeaderValue[] values = new CacheControlHeaderValue[9];
for (int i = 0; i < values.Length; i++)
{
values[i] = new CacheControlHeaderValue();
}
values[0].ProxyRevalidate = true;
values[1].NoCache = true;
values[2].NoStore = true;
values[3].MaxStale = true;
values[4].NoTransform = true;
values[5].OnlyIfCached = true;
values[6].Public = true;
values[7].Private = true;
values[8].MustRevalidate = true;
// Only one bool field set. All hash codes should differ
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
if (i != j)
{
CompareHashCodes(values[i], values[j], false);
}
}
}
// Validate that two instances with the same bool fields set are equal.
values[0].NoCache = true;
CompareHashCodes(values[0], values[1], false);
values[1].ProxyRevalidate = true;
CompareHashCodes(values[0], values[1], true);
}
[Fact]
public void GetHashCode_CompareValuesWithTimeSpanFieldsSet_MatchExpectation()
{
// Verify that different timespan fields return different hash values.
CacheControlHeaderValue[] values = new CacheControlHeaderValue[4];
for (int i = 0; i < values.Length; i++)
{
values[i] = new CacheControlHeaderValue();
}
values[0].MaxAge = new TimeSpan(0, 1, 1);
values[1].MaxStaleLimit = new TimeSpan(0, 1, 1);
values[2].MinFresh = new TimeSpan(0, 1, 1);
values[3].SharedMaxAge = new TimeSpan(0, 1, 1);
// Only one timespan field set. All hash codes should differ
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
if (i != j)
{
CompareHashCodes(values[i], values[j], false);
}
}
}
values[0].MaxStaleLimit = new TimeSpan(0, 1, 2);
CompareHashCodes(values[0], values[1], false);
values[1].MaxAge = new TimeSpan(0, 1, 1);
values[1].MaxStaleLimit = new TimeSpan(0, 1, 2);
CompareHashCodes(values[0], values[1], true);
}
[Fact]
public void GetHashCode_CompareCollectionFieldsSet_MatchExpectation()
{
CacheControlHeaderValue cacheControl1 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl2 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl3 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl4 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl5 = new CacheControlHeaderValue();
cacheControl1.NoCache = true;
cacheControl1.NoCacheHeaders.Add("token2");
cacheControl2.NoCache = true;
cacheControl2.NoCacheHeaders.Add("token1");
cacheControl2.NoCacheHeaders.Add("token2");
CompareHashCodes(cacheControl1, cacheControl2, false);
cacheControl1.NoCacheHeaders.Add("token1");
CompareHashCodes(cacheControl1, cacheControl2, true);
// Since NoCache and Private generate different hash codes, even if NoCacheHeaders and PrivateHeaders
// have the same values, the hash code will be different.
cacheControl3.Private = true;
cacheControl3.PrivateHeaders.Add("token2");
CompareHashCodes(cacheControl1, cacheControl3, false);
cacheControl4.Extensions.Add(new NameValueHeaderValue("custom"));
CompareHashCodes(cacheControl1, cacheControl4, false);
cacheControl5.Extensions.Add(new NameValueHeaderValue("customN", "customV"));
cacheControl5.Extensions.Add(new NameValueHeaderValue("custom"));
CompareHashCodes(cacheControl4, cacheControl5, false);
cacheControl4.Extensions.Add(new NameValueHeaderValue("customN", "customV"));
CompareHashCodes(cacheControl4, cacheControl5, true);
}
[Fact]
public void Equals_CompareValuesWithBoolFieldsSet_MatchExpectation()
{
// Verify that different bool fields return different hash values.
CacheControlHeaderValue[] values = new CacheControlHeaderValue[9];
for (int i = 0; i < values.Length; i++)
{
values[i] = new CacheControlHeaderValue();
}
values[0].ProxyRevalidate = true;
values[1].NoCache = true;
values[2].NoStore = true;
values[3].MaxStale = true;
values[4].NoTransform = true;
values[5].OnlyIfCached = true;
values[6].Public = true;
values[7].Private = true;
values[8].MustRevalidate = true;
// Only one bool field set. All hash codes should differ
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
if (i != j)
{
CompareValues(values[i], values[j], false);
}
}
}
// Validate that two instances with the same bool fields set are equal.
values[0].NoCache = true;
CompareValues(values[0], values[1], false);
values[1].ProxyRevalidate = true;
CompareValues(values[0], values[1], true);
}
[Fact]
public void Equals_CompareValuesWithTimeSpanFieldsSet_MatchExpectation()
{
// Verify that different timespan fields return different hash values.
CacheControlHeaderValue[] values = new CacheControlHeaderValue[4];
for (int i = 0; i < values.Length; i++)
{
values[i] = new CacheControlHeaderValue();
}
values[0].MaxAge = new TimeSpan(0, 1, 1);
values[1].MaxStaleLimit = new TimeSpan(0, 1, 1);
values[2].MinFresh = new TimeSpan(0, 1, 1);
values[3].SharedMaxAge = new TimeSpan(0, 1, 1);
// Only one timespan field set. All hash codes should differ
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
if (i != j)
{
CompareValues(values[i], values[j], false);
}
}
}
values[0].MaxStaleLimit = new TimeSpan(0, 1, 2);
CompareValues(values[0], values[1], false);
values[1].MaxAge = new TimeSpan(0, 1, 1);
values[1].MaxStaleLimit = new TimeSpan(0, 1, 2);
CompareValues(values[0], values[1], true);
CacheControlHeaderValue value1 = new CacheControlHeaderValue();
value1.MaxStale = true;
CacheControlHeaderValue value2 = new CacheControlHeaderValue();
value2.MaxStale = true;
CompareValues(value1, value2, true);
value2.MaxStaleLimit = new TimeSpan(1, 2, 3);
CompareValues(value1, value2, false);
}
[Fact]
public void Equals_CompareCollectionFieldsSet_MatchExpectation()
{
CacheControlHeaderValue cacheControl1 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl2 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl3 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl4 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl5 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl6 = new CacheControlHeaderValue();
cacheControl1.NoCache = true;
cacheControl1.NoCacheHeaders.Add("token2");
Assert.False(cacheControl1.Equals(null), "Compare with 'null'");
cacheControl2.NoCache = true;
cacheControl2.NoCacheHeaders.Add("token1");
cacheControl2.NoCacheHeaders.Add("token2");
CompareValues(cacheControl1, cacheControl2, false);
cacheControl1.NoCacheHeaders.Add("token1");
CompareValues(cacheControl1, cacheControl2, true);
// Since NoCache and Private generate different hash codes, even if NoCacheHeaders and PrivateHeaders
// have the same values, the hash code will be different.
cacheControl3.Private = true;
cacheControl3.PrivateHeaders.Add("token2");
CompareValues(cacheControl1, cacheControl3, false);
cacheControl4.Private = true;
cacheControl4.PrivateHeaders.Add("token3");
CompareValues(cacheControl3, cacheControl4, false);
cacheControl5.Extensions.Add(new NameValueHeaderValue("custom"));
CompareValues(cacheControl1, cacheControl5, false);
cacheControl6.Extensions.Add(new NameValueHeaderValue("customN", "customV"));
cacheControl6.Extensions.Add(new NameValueHeaderValue("custom"));
CompareValues(cacheControl5, cacheControl6, false);
cacheControl5.Extensions.Add(new NameValueHeaderValue("customN", "customV"));
CompareValues(cacheControl5, cacheControl6, true);
}
[Fact]
public void Clone_Call_CloneFieldsMatchSourceFields()
{
CacheControlHeaderValue source = new CacheControlHeaderValue();
source.Extensions.Add(new NameValueHeaderValue("custom"));
source.Extensions.Add(new NameValueHeaderValue("customN", "customV"));
source.MaxAge = new TimeSpan(1, 1, 1);
source.MaxStale = true;
source.MaxStaleLimit = new TimeSpan(1, 1, 2);
source.MinFresh = new TimeSpan(1, 1, 3);
source.MustRevalidate = true;
source.NoCache = true;
source.NoCacheHeaders.Add("token1");
source.NoStore = true;
source.NoTransform = true;
source.OnlyIfCached = true;
source.Private = true;
source.PrivateHeaders.Add("token2");
source.ProxyRevalidate = true;
source.Public = true;
source.SharedMaxAge = new TimeSpan(1, 1, 4);
CacheControlHeaderValue clone = (CacheControlHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source, clone);
}
[Fact]
public void GetCacheControlLength_DifferentValidScenariosAndNoExistingCacheControl_AllReturnNonZero()
{
CacheControlHeaderValue expected = new CacheControlHeaderValue();
expected.NoCache = true;
CheckGetCacheControlLength("X , , no-cache ,,", 1, null, 16, expected);
expected = new CacheControlHeaderValue();
expected.NoCache = true;
expected.NoCacheHeaders.Add("token1");
expected.NoCacheHeaders.Add("token2");
CheckGetCacheControlLength("no-cache=\"token1, token2\"", 0, null, 25, expected);
expected = new CacheControlHeaderValue();
expected.NoStore = true;
expected.MaxAge = new TimeSpan(0, 0, 125);
expected.MaxStale = true;
CheckGetCacheControlLength("X no-store , max-age = 125, max-stale,", 1, null, 37, expected);
expected = new CacheControlHeaderValue();
expected.MinFresh = new TimeSpan(0, 0, 123);
expected.NoTransform = true;
expected.OnlyIfCached = true;
expected.Extensions.Add(new NameValueHeaderValue("custom"));
CheckGetCacheControlLength("min-fresh=123, no-transform, only-if-cached, custom", 0, null, 51, expected);
expected = new CacheControlHeaderValue();
expected.Public = true;
expected.Private = true;
expected.PrivateHeaders.Add("PLACEHOLDER");
expected.MustRevalidate = true;
expected.ProxyRevalidate = true;
expected.Extensions.Add(new NameValueHeaderValue("c", "d"));
expected.Extensions.Add(new NameValueHeaderValue("a", "b"));
CheckGetCacheControlLength(",public, , private=\"PLACEHOLDER\", must-revalidate, c=d, proxy-revalidate, a=b", 0,
null, 77, expected);
expected = new CacheControlHeaderValue();
expected.Private = true;
expected.SharedMaxAge = new TimeSpan(0, 0, 1234567890);
expected.MaxAge = new TimeSpan(0, 0, 987654321);
CheckGetCacheControlLength("s-maxage=1234567890, private, max-age = 987654321,", 0, null, 50, expected);
}
[Fact]
public void GetCacheControlLength_DifferentValidScenariosAndExistingCacheControl_AllReturnNonZero()
{
CacheControlHeaderValue storeValue = new CacheControlHeaderValue();
storeValue.NoStore = true;
CacheControlHeaderValue expected = new CacheControlHeaderValue();
expected.NoCache = true;
expected.NoStore = true;
CheckGetCacheControlLength("X no-cache", 1, storeValue, 9, expected);
storeValue = new CacheControlHeaderValue();
storeValue.Private = true;
storeValue.PrivateHeaders.Add("token1");
storeValue.NoCache = true;
expected.NoCacheHeaders.Add("token1");
expected.NoCacheHeaders.Clear(); // just make sure we have an assigned (empty) collection.
expected = new CacheControlHeaderValue();
expected.Private = true;
expected.PrivateHeaders.Add("token1");
expected.PrivateHeaders.Add("PLACEHOLDER");
expected.NoCache = true;
expected.NoCacheHeaders.Add("token1");
expected.NoCacheHeaders.Add("token2");
CheckGetCacheControlLength("private=\"PLACEHOLDER\", no-cache=\"token1, , token2,\"", 0, storeValue, 51,
expected);
storeValue = new CacheControlHeaderValue();
storeValue.Extensions.Add(new NameValueHeaderValue("x", "y"));
storeValue.NoTransform = true;
storeValue.OnlyIfCached = true;
expected = new CacheControlHeaderValue();
expected.Public = true;
expected.Private = true;
expected.PrivateHeaders.Add("PLACEHOLDER");
expected.MustRevalidate = true;
expected.ProxyRevalidate = true;
expected.NoTransform = true;
expected.OnlyIfCached = true;
expected.Extensions.Add(new NameValueHeaderValue("a", "\"b\""));
expected.Extensions.Add(new NameValueHeaderValue("c", "d"));
expected.Extensions.Add(new NameValueHeaderValue("x", "y")); // from store result
CheckGetCacheControlLength(",public, , private=\"PLACEHOLDER\", must-revalidate, c=d, proxy-revalidate, a=\"b\"",
0, storeValue, 79, expected);
storeValue = new CacheControlHeaderValue();
storeValue.MaxStale = true;
storeValue.MinFresh = new TimeSpan(1, 2, 3);
expected = new CacheControlHeaderValue();
expected.MaxStale = true;
expected.MaxStaleLimit = new TimeSpan(0, 0, 5);
expected.MinFresh = new TimeSpan(0, 0, 10); // note that the last header value overwrites existing ones
CheckGetCacheControlLength(" ,,max-stale=5,,min-fresh = 10,,", 0, storeValue, 33, expected);
storeValue = new CacheControlHeaderValue();
storeValue.SharedMaxAge = new TimeSpan(1, 2, 3);
storeValue.NoTransform = true;
expected = new CacheControlHeaderValue();
expected.SharedMaxAge = new TimeSpan(1, 2, 3);
expected.NoTransform = true;
}
[Fact]
public void GetCacheControlLength_DifferentInvalidScenarios_AllReturnZero()
{
// Token-only values
CheckInvalidCacheControlLength("no-store=15", 0);
CheckInvalidCacheControlLength("no-store=", 0);
CheckInvalidCacheControlLength("no-transform=a", 0);
CheckInvalidCacheControlLength("no-transform=", 0);
CheckInvalidCacheControlLength("only-if-cached=\"x\"", 0);
CheckInvalidCacheControlLength("only-if-cached=", 0);
CheckInvalidCacheControlLength("public=\"x\"", 0);
CheckInvalidCacheControlLength("public=", 0);
CheckInvalidCacheControlLength("must-revalidate=\"1\"", 0);
CheckInvalidCacheControlLength("must-revalidate=", 0);
CheckInvalidCacheControlLength("proxy-revalidate=x", 0);
CheckInvalidCacheControlLength("proxy-revalidate=", 0);
// Token with optional field-name list
CheckInvalidCacheControlLength("no-cache=", 0);
CheckInvalidCacheControlLength("no-cache=token", 0);
CheckInvalidCacheControlLength("no-cache=\"token", 0);
CheckInvalidCacheControlLength("no-cache=\"\"", 0); // at least one token expected as value
CheckInvalidCacheControlLength("private=", 0);
CheckInvalidCacheControlLength("private=token", 0);
CheckInvalidCacheControlLength("private=\"token", 0);
CheckInvalidCacheControlLength("private=\",\"", 0); // at least one token expected as value
CheckInvalidCacheControlLength("private=\"=\"", 0);
// Token with delta-seconds value
CheckInvalidCacheControlLength("max-age", 0);
CheckInvalidCacheControlLength("max-age=", 0);
CheckInvalidCacheControlLength("max-age=a", 0);
CheckInvalidCacheControlLength("max-age=\"1\"", 0);
CheckInvalidCacheControlLength("max-age=1.5", 0);
CheckInvalidCacheControlLength("max-stale=", 0);
CheckInvalidCacheControlLength("max-stale=a", 0);
CheckInvalidCacheControlLength("max-stale=\"1\"", 0);
CheckInvalidCacheControlLength("max-stale=1.5", 0);
CheckInvalidCacheControlLength("min-fresh", 0);
CheckInvalidCacheControlLength("min-fresh=", 0);
CheckInvalidCacheControlLength("min-fresh=a", 0);
CheckInvalidCacheControlLength("min-fresh=\"1\"", 0);
CheckInvalidCacheControlLength("min-fresh=1.5", 0);
CheckInvalidCacheControlLength("s-maxage", 0);
CheckInvalidCacheControlLength("s-maxage=", 0);
CheckInvalidCacheControlLength("s-maxage=a", 0);
CheckInvalidCacheControlLength("s-maxage=\"1\"", 0);
CheckInvalidCacheControlLength("s-maxage=1.5", 0);
// Invalid Extension values
CheckInvalidCacheControlLength("custom=", 0);
CheckInvalidCacheControlLength("custom value", 0);
CheckInvalidCacheControlLength(null, 0);
CheckInvalidCacheControlLength("", 0);
CheckInvalidCacheControlLength("", 1);
}
[Fact]
public void Parse_SetOfValidValueStrings_ParsedCorrectly()
{
// Just verify parser is implemented correctly. Don't try to test syntax parsed by CacheControlHeaderValue.
CacheControlHeaderValue expected = new CacheControlHeaderValue();
expected.NoStore = true;
expected.MinFresh = new TimeSpan(0, 2, 3);
CheckValidParse(" , no-store, min-fresh=123", expected);
expected = new CacheControlHeaderValue();
expected.MaxStale = true;
expected.NoCache = true;
expected.NoCacheHeaders.Add("t");
CheckValidParse("max-stale, no-cache=\"t\", ,,", expected);
}
[Fact]
public void Parse_SetOfInvalidValueStrings_Throws()
{
CheckInvalidParse("no-cache,=", 0);
CheckInvalidParse("max-age=123x", 0);
CheckInvalidParse("=no-cache", 0);
CheckInvalidParse("no-cache no-store", 0);
CheckInvalidParse("invalid =", 0);
CheckInvalidParse("\u4F1A", 0);
}
[Fact]
public void TryParse_SetOfValidValueStrings_ParsedCorrectly()
{
// Just verify parser is implemented correctly. Don't try to test syntax parsed by CacheControlHeaderValue.
CacheControlHeaderValue expected = new CacheControlHeaderValue();
expected.NoStore = true;
expected.MinFresh = new TimeSpan(0, 2, 3);
CheckValidTryParse(" , no-store, min-fresh=123", expected);
expected = new CacheControlHeaderValue();
expected.MaxStale = true;
expected.NoCache = true;
expected.NoCacheHeaders.Add("t");
CheckValidTryParse("max-stale, no-cache=\"t\", ,,", expected);
}
[Fact]
public void TryParse_SetOfInvalidValueStrings_ReturnsFalse()
{
CheckInvalidTryParse("no-cache,=", 0);
CheckInvalidTryParse("max-age=123x", 0);
CheckInvalidTryParse("=no-cache", 0);
CheckInvalidTryParse("no-cache no-store", 0);
CheckInvalidTryParse("invalid =", 0);
CheckInvalidTryParse("\u4F1A", 0);
}
#region Helper methods
private void CompareHashCodes(CacheControlHeaderValue x, CacheControlHeaderValue y, bool areEqual)
{
if (areEqual)
{
Assert.Equal(x.GetHashCode(), y.GetHashCode());
}
else
{
Assert.NotEqual(x.GetHashCode(), y.GetHashCode());
}
}
private void CompareValues(CacheControlHeaderValue x, CacheControlHeaderValue y, bool areEqual)
{
Assert.Equal(areEqual, x.Equals(y));
Assert.Equal(areEqual, y.Equals(x));
}
private static void CheckGetCacheControlLength(string input, int startIndex, CacheControlHeaderValue storeValue,
int expectedLength, CacheControlHeaderValue expectedResult)
{
CacheControlHeaderValue result = null;
Assert.Equal(expectedLength, CacheControlHeaderValue.GetCacheControlLength(input, startIndex, storeValue, out result));
if (storeValue == null)
{
Assert.Equal(expectedResult, result);
}
else
{
// If we provide a 'storeValue', then that instance will be updated and result will be 'null'
Assert.Null(result);
Assert.Equal(expectedResult, storeValue);
}
}
private static void CheckInvalidCacheControlLength(string input, int startIndex)
{
CacheControlHeaderValue result = null;
Assert.Equal(0, CacheControlHeaderValue.GetCacheControlLength(input, startIndex, null, out result));
Assert.Null(result);
}
private void CheckValidParse(string input, CacheControlHeaderValue expectedResult)
{
CacheControlHeaderValue result = CacheControlHeaderValue.Parse(input);
Assert.Equal(expectedResult, result);
}
private void CheckInvalidParse(string input, int startIndex)
{
Assert.Throws<FormatException>(() => { CacheControlHeaderValue.Parse(input); });
}
private void CheckValidTryParse(string input, CacheControlHeaderValue expectedResult)
{
CacheControlHeaderValue result = null;
Assert.True(CacheControlHeaderValue.TryParse(input, out result));
Assert.Equal(expectedResult, result);
}
private void CheckInvalidTryParse(string input, int startIndex)
{
CacheControlHeaderValue result = null;
Assert.False(CacheControlHeaderValue.TryParse(input, out result));
Assert.Null(result);
}
#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.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Net.Http.Tests
{
public class CacheControlHeaderValueTest
{
[Fact]
public void Properties_SetAndGetAllProperties_SetValueReturnedInGetter()
{
CacheControlHeaderValue cacheControl = new CacheControlHeaderValue();
// Bool properties
cacheControl.NoCache = true;
Assert.True(cacheControl.NoCache);
cacheControl.NoStore = true;
Assert.True(cacheControl.NoStore);
cacheControl.MaxStale = true;
Assert.True(cacheControl.MaxStale);
cacheControl.NoTransform = true;
Assert.True(cacheControl.NoTransform);
cacheControl.OnlyIfCached = true;
Assert.True(cacheControl.OnlyIfCached);
cacheControl.Public = true;
Assert.True(cacheControl.Public);
cacheControl.Private = true;
Assert.True(cacheControl.Private);
cacheControl.MustRevalidate = true;
Assert.True(cacheControl.MustRevalidate);
cacheControl.ProxyRevalidate = true;
Assert.True(cacheControl.ProxyRevalidate);
// TimeSpan properties
TimeSpan timeSpan = new TimeSpan(1, 2, 3);
cacheControl.MaxAge = timeSpan;
Assert.Equal(timeSpan, cacheControl.MaxAge);
cacheControl.SharedMaxAge = timeSpan;
Assert.Equal(timeSpan, cacheControl.SharedMaxAge);
cacheControl.MaxStaleLimit = timeSpan;
Assert.Equal(timeSpan, cacheControl.MaxStaleLimit);
cacheControl.MinFresh = timeSpan;
Assert.Equal(timeSpan, cacheControl.MinFresh);
// String collection properties
Assert.NotNull(cacheControl.NoCacheHeaders);
AssertExtensions.Throws<ArgumentException>("item", () => { cacheControl.NoCacheHeaders.Add(null); });
Assert.Throws<FormatException>(() => { cacheControl.NoCacheHeaders.Add("invalid token"); });
cacheControl.NoCacheHeaders.Add("token");
Assert.Equal(1, cacheControl.NoCacheHeaders.Count);
Assert.Equal("token", cacheControl.NoCacheHeaders.First());
Assert.NotNull(cacheControl.PrivateHeaders);
AssertExtensions.Throws<ArgumentException>("item", () => { cacheControl.PrivateHeaders.Add(null); });
Assert.Throws<FormatException>(() => { cacheControl.PrivateHeaders.Add("invalid token"); });
cacheControl.PrivateHeaders.Add("token");
Assert.Equal(1, cacheControl.PrivateHeaders.Count);
Assert.Equal("token", cacheControl.PrivateHeaders.First());
// NameValueHeaderValue collection property
Assert.NotNull(cacheControl.Extensions);
Assert.Throws<ArgumentNullException>(() => { cacheControl.Extensions.Add(null); });
cacheControl.Extensions.Add(new NameValueHeaderValue("name", "value"));
Assert.Equal(1, cacheControl.Extensions.Count);
Assert.Equal(new NameValueHeaderValue("name", "value"), cacheControl.Extensions.First());
}
[Fact]
public void ToString_UseRequestDirectiveValues_AllSerializedCorrectly()
{
CacheControlHeaderValue cacheControl = new CacheControlHeaderValue();
Assert.Equal("", cacheControl.ToString());
// Note that we allow all combinations of all properties even though the RFC specifies rules what value
// can be used together.
// Also for property pairs (bool property + collection property) like 'NoCache' and 'NoCacheHeaders' the
// caller needs to set the bool property in order for the collection to be populated as string.
// Cache Request Directive sample
cacheControl.NoStore = true;
Assert.Equal("no-store", cacheControl.ToString());
cacheControl.NoCache = true;
Assert.Equal("no-store, no-cache", cacheControl.ToString());
cacheControl.MaxAge = new TimeSpan(0, 1, 10);
Assert.Equal("no-store, no-cache, max-age=70", cacheControl.ToString());
cacheControl.MaxStale = true;
Assert.Equal("no-store, no-cache, max-age=70, max-stale", cacheControl.ToString());
cacheControl.MaxStaleLimit = new TimeSpan(0, 2, 5);
Assert.Equal("no-store, no-cache, max-age=70, max-stale=125", cacheControl.ToString());
cacheControl.MinFresh = new TimeSpan(0, 3, 0);
Assert.Equal("no-store, no-cache, max-age=70, max-stale=125, min-fresh=180", cacheControl.ToString());
cacheControl = new CacheControlHeaderValue();
cacheControl.NoTransform = true;
Assert.Equal("no-transform", cacheControl.ToString());
cacheControl.OnlyIfCached = true;
Assert.Equal("no-transform, only-if-cached", cacheControl.ToString());
cacheControl.Extensions.Add(new NameValueHeaderValue("custom"));
cacheControl.Extensions.Add(new NameValueHeaderValue("customName", "customValue"));
Assert.Equal("no-transform, only-if-cached, custom, customName=customValue", cacheControl.ToString());
cacheControl = new CacheControlHeaderValue();
cacheControl.Extensions.Add(new NameValueHeaderValue("custom"));
Assert.Equal("custom", cacheControl.ToString());
}
[Fact]
public void ToString_UseResponseDirectiveValues_AllSerializedCorrectly()
{
CacheControlHeaderValue cacheControl = new CacheControlHeaderValue();
Assert.Equal("", cacheControl.ToString());
cacheControl.NoCache = true;
Assert.Equal("no-cache", cacheControl.ToString());
cacheControl.NoCacheHeaders.Add("token1");
Assert.Equal("no-cache=\"token1\"", cacheControl.ToString());
cacheControl.Public = true;
Assert.Equal("public, no-cache=\"token1\"", cacheControl.ToString());
cacheControl = new CacheControlHeaderValue();
cacheControl.Private = true;
Assert.Equal("private", cacheControl.ToString());
cacheControl.PrivateHeaders.Add("token2");
cacheControl.PrivateHeaders.Add("token3");
Assert.Equal("private=\"token2, token3\"", cacheControl.ToString());
cacheControl.MustRevalidate = true;
Assert.Equal("must-revalidate, private=\"token2, token3\"", cacheControl.ToString());
cacheControl.ProxyRevalidate = true;
Assert.Equal("must-revalidate, proxy-revalidate, private=\"token2, token3\"", cacheControl.ToString());
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void ToString_NegativeValues_UsesMinusSignRegardlessOfCurrentCulture()
{
RemoteExecutor.Invoke(() =>
{
var cacheControl = new CacheControlHeaderValue()
{
MaxAge = new TimeSpan(0, 0, -1),
MaxStale = true,
MaxStaleLimit = new TimeSpan(0, 0, -2),
MinFresh = new TimeSpan(0, 0, -3),
SharedMaxAge = new TimeSpan(0, 0, -4)
};
var ci = (CultureInfo)CultureInfo.CurrentCulture.Clone();
ci.NumberFormat.NegativeSign = "n";
CultureInfo.CurrentCulture = ci;
Assert.Equal("max-age=-1, s-maxage=-4, max-stale=-2, min-fresh=-3", cacheControl.ToString());
}).Dispose();
}
[Fact]
public void GetHashCode_CompareValuesWithBoolFieldsSet_MatchExpectation()
{
// Verify that different bool fields return different hash values.
CacheControlHeaderValue[] values = new CacheControlHeaderValue[9];
for (int i = 0; i < values.Length; i++)
{
values[i] = new CacheControlHeaderValue();
}
values[0].ProxyRevalidate = true;
values[1].NoCache = true;
values[2].NoStore = true;
values[3].MaxStale = true;
values[4].NoTransform = true;
values[5].OnlyIfCached = true;
values[6].Public = true;
values[7].Private = true;
values[8].MustRevalidate = true;
// Only one bool field set. All hash codes should differ
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
if (i != j)
{
CompareHashCodes(values[i], values[j], false);
}
}
}
// Validate that two instances with the same bool fields set are equal.
values[0].NoCache = true;
CompareHashCodes(values[0], values[1], false);
values[1].ProxyRevalidate = true;
CompareHashCodes(values[0], values[1], true);
}
[Fact]
public void GetHashCode_CompareValuesWithTimeSpanFieldsSet_MatchExpectation()
{
// Verify that different timespan fields return different hash values.
CacheControlHeaderValue[] values = new CacheControlHeaderValue[4];
for (int i = 0; i < values.Length; i++)
{
values[i] = new CacheControlHeaderValue();
}
values[0].MaxAge = new TimeSpan(0, 1, 1);
values[1].MaxStaleLimit = new TimeSpan(0, 1, 1);
values[2].MinFresh = new TimeSpan(0, 1, 1);
values[3].SharedMaxAge = new TimeSpan(0, 1, 1);
// Only one timespan field set. All hash codes should differ
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
if (i != j)
{
CompareHashCodes(values[i], values[j], false);
}
}
}
values[0].MaxStaleLimit = new TimeSpan(0, 1, 2);
CompareHashCodes(values[0], values[1], false);
values[1].MaxAge = new TimeSpan(0, 1, 1);
values[1].MaxStaleLimit = new TimeSpan(0, 1, 2);
CompareHashCodes(values[0], values[1], true);
}
[Fact]
public void GetHashCode_CompareCollectionFieldsSet_MatchExpectation()
{
CacheControlHeaderValue cacheControl1 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl2 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl3 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl4 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl5 = new CacheControlHeaderValue();
cacheControl1.NoCache = true;
cacheControl1.NoCacheHeaders.Add("token2");
cacheControl2.NoCache = true;
cacheControl2.NoCacheHeaders.Add("token1");
cacheControl2.NoCacheHeaders.Add("token2");
CompareHashCodes(cacheControl1, cacheControl2, false);
cacheControl1.NoCacheHeaders.Add("token1");
CompareHashCodes(cacheControl1, cacheControl2, true);
// Since NoCache and Private generate different hash codes, even if NoCacheHeaders and PrivateHeaders
// have the same values, the hash code will be different.
cacheControl3.Private = true;
cacheControl3.PrivateHeaders.Add("token2");
CompareHashCodes(cacheControl1, cacheControl3, false);
cacheControl4.Extensions.Add(new NameValueHeaderValue("custom"));
CompareHashCodes(cacheControl1, cacheControl4, false);
cacheControl5.Extensions.Add(new NameValueHeaderValue("customN", "customV"));
cacheControl5.Extensions.Add(new NameValueHeaderValue("custom"));
CompareHashCodes(cacheControl4, cacheControl5, false);
cacheControl4.Extensions.Add(new NameValueHeaderValue("customN", "customV"));
CompareHashCodes(cacheControl4, cacheControl5, true);
}
[Fact]
public void Equals_CompareValuesWithBoolFieldsSet_MatchExpectation()
{
// Verify that different bool fields return different hash values.
CacheControlHeaderValue[] values = new CacheControlHeaderValue[9];
for (int i = 0; i < values.Length; i++)
{
values[i] = new CacheControlHeaderValue();
}
values[0].ProxyRevalidate = true;
values[1].NoCache = true;
values[2].NoStore = true;
values[3].MaxStale = true;
values[4].NoTransform = true;
values[5].OnlyIfCached = true;
values[6].Public = true;
values[7].Private = true;
values[8].MustRevalidate = true;
// Only one bool field set. All hash codes should differ
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
if (i != j)
{
CompareValues(values[i], values[j], false);
}
}
}
// Validate that two instances with the same bool fields set are equal.
values[0].NoCache = true;
CompareValues(values[0], values[1], false);
values[1].ProxyRevalidate = true;
CompareValues(values[0], values[1], true);
}
[Fact]
public void Equals_CompareValuesWithTimeSpanFieldsSet_MatchExpectation()
{
// Verify that different timespan fields return different hash values.
CacheControlHeaderValue[] values = new CacheControlHeaderValue[4];
for (int i = 0; i < values.Length; i++)
{
values[i] = new CacheControlHeaderValue();
}
values[0].MaxAge = new TimeSpan(0, 1, 1);
values[1].MaxStaleLimit = new TimeSpan(0, 1, 1);
values[2].MinFresh = new TimeSpan(0, 1, 1);
values[3].SharedMaxAge = new TimeSpan(0, 1, 1);
// Only one timespan field set. All hash codes should differ
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
if (i != j)
{
CompareValues(values[i], values[j], false);
}
}
}
values[0].MaxStaleLimit = new TimeSpan(0, 1, 2);
CompareValues(values[0], values[1], false);
values[1].MaxAge = new TimeSpan(0, 1, 1);
values[1].MaxStaleLimit = new TimeSpan(0, 1, 2);
CompareValues(values[0], values[1], true);
CacheControlHeaderValue value1 = new CacheControlHeaderValue();
value1.MaxStale = true;
CacheControlHeaderValue value2 = new CacheControlHeaderValue();
value2.MaxStale = true;
CompareValues(value1, value2, true);
value2.MaxStaleLimit = new TimeSpan(1, 2, 3);
CompareValues(value1, value2, false);
}
[Fact]
public void Equals_CompareCollectionFieldsSet_MatchExpectation()
{
CacheControlHeaderValue cacheControl1 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl2 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl3 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl4 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl5 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl6 = new CacheControlHeaderValue();
cacheControl1.NoCache = true;
cacheControl1.NoCacheHeaders.Add("token2");
Assert.False(cacheControl1.Equals(null), "Compare with 'null'");
cacheControl2.NoCache = true;
cacheControl2.NoCacheHeaders.Add("token1");
cacheControl2.NoCacheHeaders.Add("token2");
CompareValues(cacheControl1, cacheControl2, false);
cacheControl1.NoCacheHeaders.Add("token1");
CompareValues(cacheControl1, cacheControl2, true);
// Since NoCache and Private generate different hash codes, even if NoCacheHeaders and PrivateHeaders
// have the same values, the hash code will be different.
cacheControl3.Private = true;
cacheControl3.PrivateHeaders.Add("token2");
CompareValues(cacheControl1, cacheControl3, false);
cacheControl4.Private = true;
cacheControl4.PrivateHeaders.Add("token3");
CompareValues(cacheControl3, cacheControl4, false);
cacheControl5.Extensions.Add(new NameValueHeaderValue("custom"));
CompareValues(cacheControl1, cacheControl5, false);
cacheControl6.Extensions.Add(new NameValueHeaderValue("customN", "customV"));
cacheControl6.Extensions.Add(new NameValueHeaderValue("custom"));
CompareValues(cacheControl5, cacheControl6, false);
cacheControl5.Extensions.Add(new NameValueHeaderValue("customN", "customV"));
CompareValues(cacheControl5, cacheControl6, true);
}
[Fact]
public void Clone_Call_CloneFieldsMatchSourceFields()
{
CacheControlHeaderValue source = new CacheControlHeaderValue();
source.Extensions.Add(new NameValueHeaderValue("custom"));
source.Extensions.Add(new NameValueHeaderValue("customN", "customV"));
source.MaxAge = new TimeSpan(1, 1, 1);
source.MaxStale = true;
source.MaxStaleLimit = new TimeSpan(1, 1, 2);
source.MinFresh = new TimeSpan(1, 1, 3);
source.MustRevalidate = true;
source.NoCache = true;
source.NoCacheHeaders.Add("token1");
source.NoStore = true;
source.NoTransform = true;
source.OnlyIfCached = true;
source.Private = true;
source.PrivateHeaders.Add("token2");
source.ProxyRevalidate = true;
source.Public = true;
source.SharedMaxAge = new TimeSpan(1, 1, 4);
CacheControlHeaderValue clone = (CacheControlHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source, clone);
}
[Fact]
public void GetCacheControlLength_DifferentValidScenariosAndNoExistingCacheControl_AllReturnNonZero()
{
CacheControlHeaderValue expected = new CacheControlHeaderValue();
expected.NoCache = true;
CheckGetCacheControlLength("X , , no-cache ,,", 1, null, 16, expected);
expected = new CacheControlHeaderValue();
expected.NoCache = true;
expected.NoCacheHeaders.Add("token1");
expected.NoCacheHeaders.Add("token2");
CheckGetCacheControlLength("no-cache=\"token1, token2\"", 0, null, 25, expected);
expected = new CacheControlHeaderValue();
expected.NoStore = true;
expected.MaxAge = new TimeSpan(0, 0, 125);
expected.MaxStale = true;
CheckGetCacheControlLength("X no-store , max-age = 125, max-stale,", 1, null, 37, expected);
expected = new CacheControlHeaderValue();
expected.MinFresh = new TimeSpan(0, 0, 123);
expected.NoTransform = true;
expected.OnlyIfCached = true;
expected.Extensions.Add(new NameValueHeaderValue("custom"));
CheckGetCacheControlLength("min-fresh=123, no-transform, only-if-cached, custom", 0, null, 51, expected);
expected = new CacheControlHeaderValue();
expected.Public = true;
expected.Private = true;
expected.PrivateHeaders.Add("PLACEHOLDER");
expected.MustRevalidate = true;
expected.ProxyRevalidate = true;
expected.Extensions.Add(new NameValueHeaderValue("c", "d"));
expected.Extensions.Add(new NameValueHeaderValue("a", "b"));
CheckGetCacheControlLength(",public, , private=\"PLACEHOLDER\", must-revalidate, c=d, proxy-revalidate, a=b", 0,
null, 77, expected);
expected = new CacheControlHeaderValue();
expected.Private = true;
expected.SharedMaxAge = new TimeSpan(0, 0, 1234567890);
expected.MaxAge = new TimeSpan(0, 0, 987654321);
CheckGetCacheControlLength("s-maxage=1234567890, private, max-age = 987654321,", 0, null, 50, expected);
}
[Fact]
public void GetCacheControlLength_DifferentValidScenariosAndExistingCacheControl_AllReturnNonZero()
{
CacheControlHeaderValue storeValue = new CacheControlHeaderValue();
storeValue.NoStore = true;
CacheControlHeaderValue expected = new CacheControlHeaderValue();
expected.NoCache = true;
expected.NoStore = true;
CheckGetCacheControlLength("X no-cache", 1, storeValue, 9, expected);
storeValue = new CacheControlHeaderValue();
storeValue.Private = true;
storeValue.PrivateHeaders.Add("token1");
storeValue.NoCache = true;
expected.NoCacheHeaders.Add("token1");
expected.NoCacheHeaders.Clear(); // just make sure we have an assigned (empty) collection.
expected = new CacheControlHeaderValue();
expected.Private = true;
expected.PrivateHeaders.Add("token1");
expected.PrivateHeaders.Add("PLACEHOLDER");
expected.NoCache = true;
expected.NoCacheHeaders.Add("token1");
expected.NoCacheHeaders.Add("token2");
CheckGetCacheControlLength("private=\"PLACEHOLDER\", no-cache=\"token1, , token2,\"", 0, storeValue, 51,
expected);
storeValue = new CacheControlHeaderValue();
storeValue.Extensions.Add(new NameValueHeaderValue("x", "y"));
storeValue.NoTransform = true;
storeValue.OnlyIfCached = true;
expected = new CacheControlHeaderValue();
expected.Public = true;
expected.Private = true;
expected.PrivateHeaders.Add("PLACEHOLDER");
expected.MustRevalidate = true;
expected.ProxyRevalidate = true;
expected.NoTransform = true;
expected.OnlyIfCached = true;
expected.Extensions.Add(new NameValueHeaderValue("a", "\"b\""));
expected.Extensions.Add(new NameValueHeaderValue("c", "d"));
expected.Extensions.Add(new NameValueHeaderValue("x", "y")); // from store result
CheckGetCacheControlLength(",public, , private=\"PLACEHOLDER\", must-revalidate, c=d, proxy-revalidate, a=\"b\"",
0, storeValue, 79, expected);
storeValue = new CacheControlHeaderValue();
storeValue.MaxStale = true;
storeValue.MinFresh = new TimeSpan(1, 2, 3);
expected = new CacheControlHeaderValue();
expected.MaxStale = true;
expected.MaxStaleLimit = new TimeSpan(0, 0, 5);
expected.MinFresh = new TimeSpan(0, 0, 10); // note that the last header value overwrites existing ones
CheckGetCacheControlLength(" ,,max-stale=5,,min-fresh = 10,,", 0, storeValue, 33, expected);
storeValue = new CacheControlHeaderValue();
storeValue.SharedMaxAge = new TimeSpan(1, 2, 3);
storeValue.NoTransform = true;
expected = new CacheControlHeaderValue();
expected.SharedMaxAge = new TimeSpan(1, 2, 3);
expected.NoTransform = true;
}
[Fact]
public void GetCacheControlLength_DifferentInvalidScenarios_AllReturnZero()
{
// Token-only values
CheckInvalidCacheControlLength("no-store=15", 0);
CheckInvalidCacheControlLength("no-store=", 0);
CheckInvalidCacheControlLength("no-transform=a", 0);
CheckInvalidCacheControlLength("no-transform=", 0);
CheckInvalidCacheControlLength("only-if-cached=\"x\"", 0);
CheckInvalidCacheControlLength("only-if-cached=", 0);
CheckInvalidCacheControlLength("public=\"x\"", 0);
CheckInvalidCacheControlLength("public=", 0);
CheckInvalidCacheControlLength("must-revalidate=\"1\"", 0);
CheckInvalidCacheControlLength("must-revalidate=", 0);
CheckInvalidCacheControlLength("proxy-revalidate=x", 0);
CheckInvalidCacheControlLength("proxy-revalidate=", 0);
// Token with optional field-name list
CheckInvalidCacheControlLength("no-cache=", 0);
CheckInvalidCacheControlLength("no-cache=token", 0);
CheckInvalidCacheControlLength("no-cache=\"token", 0);
CheckInvalidCacheControlLength("no-cache=\"\"", 0); // at least one token expected as value
CheckInvalidCacheControlLength("private=", 0);
CheckInvalidCacheControlLength("private=token", 0);
CheckInvalidCacheControlLength("private=\"token", 0);
CheckInvalidCacheControlLength("private=\",\"", 0); // at least one token expected as value
CheckInvalidCacheControlLength("private=\"=\"", 0);
// Token with delta-seconds value
CheckInvalidCacheControlLength("max-age", 0);
CheckInvalidCacheControlLength("max-age=", 0);
CheckInvalidCacheControlLength("max-age=a", 0);
CheckInvalidCacheControlLength("max-age=\"1\"", 0);
CheckInvalidCacheControlLength("max-age=1.5", 0);
CheckInvalidCacheControlLength("max-stale=", 0);
CheckInvalidCacheControlLength("max-stale=a", 0);
CheckInvalidCacheControlLength("max-stale=\"1\"", 0);
CheckInvalidCacheControlLength("max-stale=1.5", 0);
CheckInvalidCacheControlLength("min-fresh", 0);
CheckInvalidCacheControlLength("min-fresh=", 0);
CheckInvalidCacheControlLength("min-fresh=a", 0);
CheckInvalidCacheControlLength("min-fresh=\"1\"", 0);
CheckInvalidCacheControlLength("min-fresh=1.5", 0);
CheckInvalidCacheControlLength("s-maxage", 0);
CheckInvalidCacheControlLength("s-maxage=", 0);
CheckInvalidCacheControlLength("s-maxage=a", 0);
CheckInvalidCacheControlLength("s-maxage=\"1\"", 0);
CheckInvalidCacheControlLength("s-maxage=1.5", 0);
// Invalid Extension values
CheckInvalidCacheControlLength("custom=", 0);
CheckInvalidCacheControlLength("custom value", 0);
CheckInvalidCacheControlLength(null, 0);
CheckInvalidCacheControlLength("", 0);
CheckInvalidCacheControlLength("", 1);
}
[Fact]
public void Parse_SetOfValidValueStrings_ParsedCorrectly()
{
// Just verify parser is implemented correctly. Don't try to test syntax parsed by CacheControlHeaderValue.
CacheControlHeaderValue expected = new CacheControlHeaderValue();
expected.NoStore = true;
expected.MinFresh = new TimeSpan(0, 2, 3);
CheckValidParse(" , no-store, min-fresh=123", expected);
expected = new CacheControlHeaderValue();
expected.MaxStale = true;
expected.NoCache = true;
expected.NoCacheHeaders.Add("t");
CheckValidParse("max-stale, no-cache=\"t\", ,,", expected);
}
[Fact]
public void Parse_SetOfInvalidValueStrings_Throws()
{
CheckInvalidParse("no-cache,=", 0);
CheckInvalidParse("max-age=123x", 0);
CheckInvalidParse("=no-cache", 0);
CheckInvalidParse("no-cache no-store", 0);
CheckInvalidParse("invalid =", 0);
CheckInvalidParse("\u4F1A", 0);
}
[Fact]
public void TryParse_SetOfValidValueStrings_ParsedCorrectly()
{
// Just verify parser is implemented correctly. Don't try to test syntax parsed by CacheControlHeaderValue.
CacheControlHeaderValue expected = new CacheControlHeaderValue();
expected.NoStore = true;
expected.MinFresh = new TimeSpan(0, 2, 3);
CheckValidTryParse(" , no-store, min-fresh=123", expected);
expected = new CacheControlHeaderValue();
expected.MaxStale = true;
expected.NoCache = true;
expected.NoCacheHeaders.Add("t");
CheckValidTryParse("max-stale, no-cache=\"t\", ,,", expected);
}
[Fact]
public void TryParse_SetOfInvalidValueStrings_ReturnsFalse()
{
CheckInvalidTryParse("no-cache,=", 0);
CheckInvalidTryParse("max-age=123x", 0);
CheckInvalidTryParse("=no-cache", 0);
CheckInvalidTryParse("no-cache no-store", 0);
CheckInvalidTryParse("invalid =", 0);
CheckInvalidTryParse("\u4F1A", 0);
}
#region Helper methods
private void CompareHashCodes(CacheControlHeaderValue x, CacheControlHeaderValue y, bool areEqual)
{
if (areEqual)
{
Assert.Equal(x.GetHashCode(), y.GetHashCode());
}
else
{
Assert.NotEqual(x.GetHashCode(), y.GetHashCode());
}
}
private void CompareValues(CacheControlHeaderValue x, CacheControlHeaderValue y, bool areEqual)
{
Assert.Equal(areEqual, x.Equals(y));
Assert.Equal(areEqual, y.Equals(x));
}
private static void CheckGetCacheControlLength(string input, int startIndex, CacheControlHeaderValue storeValue,
int expectedLength, CacheControlHeaderValue expectedResult)
{
CacheControlHeaderValue result = null;
Assert.Equal(expectedLength, CacheControlHeaderValue.GetCacheControlLength(input, startIndex, storeValue, out result));
if (storeValue == null)
{
Assert.Equal(expectedResult, result);
}
else
{
// If we provide a 'storeValue', then that instance will be updated and result will be 'null'
Assert.Null(result);
Assert.Equal(expectedResult, storeValue);
}
}
private static void CheckInvalidCacheControlLength(string input, int startIndex)
{
CacheControlHeaderValue result = null;
Assert.Equal(0, CacheControlHeaderValue.GetCacheControlLength(input, startIndex, null, out result));
Assert.Null(result);
}
private void CheckValidParse(string input, CacheControlHeaderValue expectedResult)
{
CacheControlHeaderValue result = CacheControlHeaderValue.Parse(input);
Assert.Equal(expectedResult, result);
}
private void CheckInvalidParse(string input, int startIndex)
{
Assert.Throws<FormatException>(() => { CacheControlHeaderValue.Parse(input); });
}
private void CheckValidTryParse(string input, CacheControlHeaderValue expectedResult)
{
CacheControlHeaderValue result = null;
Assert.True(CacheControlHeaderValue.TryParse(input, out result));
Assert.Equal(expectedResult, result);
}
private void CheckInvalidTryParse(string input, int startIndex)
{
CacheControlHeaderValue result = null;
Assert.False(CacheControlHeaderValue.TryParse(input, out result));
Assert.Null(result);
}
#endregion
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriter.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.Text;
using System.Xml.XPath;
using System.Xml.Schema;
using System.Diagnostics;
using System.Globalization;
namespace System.Xml
{
// Specifies the state of the XmlWriter.
public enum WriteState
{
// Nothing has been written yet.
Start,
// Writing the prolog.
Prolog,
// Writing a the start tag for an element.
Element,
// Writing an attribute value.
Attribute,
// Writing element content.
Content,
// XmlWriter is closed; Close has been called.
Closed,
// Writer is in error state.
Error
};
// Represents a writer that provides fast non-cached forward-only way of generating XML streams containing XML documents
// that conform to the W3C Extensible Markup Language (XML) 1.0 specification and the Namespaces in XML specification.
public abstract partial class XmlWriter : IDisposable
{
// Helper buffer for WriteNode(XmlReader, bool)
private char[]? _writeNodeBuffer;
// Constants
private const int WriteNodeBufferSize = 1024;
// Returns the settings describing the features of the writer. Returns null for V1 XmlWriters (XmlTextWriter).
public virtual XmlWriterSettings? Settings => null;
// Write methods
// Writes out the XML declaration with the version "1.0".
public abstract void WriteStartDocument();
//Writes out the XML declaration with the version "1.0" and the specified standalone attribute.
public abstract void WriteStartDocument(bool standalone);
//Closes any open elements or attributes and puts the writer back in the Start state.
public abstract void WriteEndDocument();
// Writes out the DOCTYPE declaration with the specified name and optional attributes.
public abstract void WriteDocType(string name, string? pubid, string? sysid, string? subset);
// Writes out the specified start tag and associates it with the given namespace.
public void WriteStartElement(string localName, string? ns)
{
WriteStartElement(null, localName, ns);
}
// Writes out the specified start tag and associates it with the given namespace and prefix.
public abstract void WriteStartElement(string? prefix, string localName, string? ns);
// Writes out a start tag with the specified local name with no namespace.
public void WriteStartElement(string localName)
{
WriteStartElement(null, localName, null);
}
// Closes one element and pops the corresponding namespace scope.
public abstract void WriteEndElement();
// Closes one element and pops the corresponding namespace scope. Writes out a full end element tag, e.g. </element>.
public abstract void WriteFullEndElement();
// Writes out the attribute with the specified LocalName, value, and NamespaceURI.
public void WriteAttributeString(string localName, string? ns, string? value)
{
WriteStartAttribute(null, localName, ns);
WriteString(value);
WriteEndAttribute();
}
// Writes out the attribute with the specified LocalName and value.
public void WriteAttributeString(string localName, string? value)
{
WriteStartAttribute(null, localName, null);
WriteString(value);
WriteEndAttribute();
}
// Writes out the attribute with the specified prefix, LocalName, NamespaceURI and value.
public void WriteAttributeString(string? prefix, string localName, string? ns, string? value)
{
WriteStartAttribute(prefix, localName, ns);
WriteString(value);
WriteEndAttribute();
}
// Writes the start of an attribute.
public void WriteStartAttribute(string localName, string? ns)
{
WriteStartAttribute(null, localName, ns);
}
// Writes the start of an attribute.
public abstract void WriteStartAttribute(string? prefix, string localName, string? ns);
// Writes the start of an attribute.
public void WriteStartAttribute(string localName)
{
WriteStartAttribute(null, localName, null);
}
// Closes the attribute opened by WriteStartAttribute call.
public abstract void WriteEndAttribute();
// Writes out a <![CDATA[...]]>; block containing the specified text.
public abstract void WriteCData(string? text);
// Writes out a comment <!--...-->; containing the specified text.
public abstract void WriteComment(string? text);
// Writes out a processing instruction with a space between the name and text as follows: <?name text?>
public abstract void WriteProcessingInstruction(string name, string? text);
// Writes out an entity reference as follows: "&"+name+";".
public abstract void WriteEntityRef(string name);
// Forces the generation of a character entity for the specified Unicode character value.
public abstract void WriteCharEntity(char ch);
// Writes out the given whitespace.
public abstract void WriteWhitespace(string? ws);
// Writes out the specified text content.
public abstract void WriteString(string? text);
// Write out the given surrogate pair as an entity reference.
public abstract void WriteSurrogateCharEntity(char lowChar, char highChar);
// Writes out the specified text content.
public abstract void WriteChars(char[] buffer, int index, int count);
// Writes raw markup from the given character buffer.
public abstract void WriteRaw(char[] buffer, int index, int count);
// Writes raw markup from the given string.
public abstract void WriteRaw(string data);
// Encodes the specified binary bytes as base64 and writes out the resulting text.
public abstract void WriteBase64(byte[] buffer, int index, int count);
// Encodes the specified binary bytes as bin hex and writes out the resulting text.
public virtual void WriteBinHex(byte[] buffer, int index, int count)
{
BinHexEncoder.Encode(buffer, index, count, this);
}
// Returns the state of the XmlWriter.
public abstract WriteState WriteState { get; }
// Closes the XmlWriter and the underlying stream/TextReader (if Settings.CloseOutput is true).
public virtual void Close() { }
// Flushes data that is in the internal buffers into the underlying streams/TextReader and flushes the stream/TextReader.
public abstract void Flush();
// Returns the closest prefix defined in the current namespace scope for the specified namespace URI.
public abstract string? LookupPrefix(string ns);
// Gets an XmlSpace representing the current xml:space scope.
public virtual XmlSpace XmlSpace => XmlSpace.Default;
// Gets the current xml:lang scope.
public virtual string? XmlLang => string.Empty;
// Scalar Value Methods
// Writes out the specified name, ensuring it is a valid NmToken according to the XML specification
// (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).
public virtual void WriteNmToken(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException(SR.Xml_EmptyName);
}
WriteString(XmlConvert.VerifyNMTOKEN(name, ExceptionType.ArgumentException));
}
// Writes out the specified name, ensuring it is a valid Name according to the XML specification
// (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).
public virtual void WriteName(string name)
{
WriteString(XmlConvert.VerifyQName(name, ExceptionType.ArgumentException));
}
// Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace.
public virtual void WriteQualifiedName(string localName, string? ns)
{
if (!string.IsNullOrEmpty(ns))
{
string? prefix = LookupPrefix(ns);
if (prefix == null)
{
throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns));
}
WriteString(prefix);
WriteString(":");
}
WriteString(localName);
}
// Writes out the specified value.
public virtual void WriteValue(object value!!)
{
WriteString(XmlUntypedConverter.Untyped.ToString(value, null));
}
// Writes out the specified value.
public virtual void WriteValue(string? value)
{
if (value != null)
{
WriteString(value);
}
}
// Writes out the specified value.
public virtual void WriteValue(bool value)
{
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
public virtual void WriteValue(DateTime value)
{
WriteString(XmlConvert.ToString(value, XmlDateTimeSerializationMode.RoundtripKind));
}
// Writes out the specified value.
public virtual void WriteValue(DateTimeOffset value)
{
// Under Win8P, WriteValue(DateTime) will invoke this overload, but custom writers
// might not have implemented it. This base implementation should call WriteValue(DateTime).
// The following conversion results in the same string as calling ToString with DateTimeOffset.
WriteValue(value.Offset != TimeSpan.Zero ? value.LocalDateTime : value.UtcDateTime);
}
// Writes out the specified value.
public virtual void WriteValue(double value)
{
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
public virtual void WriteValue(float value)
{
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
public virtual void WriteValue(decimal value)
{
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
public virtual void WriteValue(int value)
{
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
public virtual void WriteValue(long value)
{
WriteString(XmlConvert.ToString(value));
}
// XmlReader Helper Methods
// Writes out all the attributes found at the current position in the specified XmlReader.
public virtual void WriteAttributes(XmlReader reader!!, bool defattr)
{
if (reader.NodeType is XmlNodeType.Element or XmlNodeType.XmlDeclaration)
{
if (reader.MoveToFirstAttribute())
{
WriteAttributes(reader, defattr);
reader.MoveToElement();
}
}
else if (reader.NodeType != XmlNodeType.Attribute)
{
throw new XmlException(SR.Xml_InvalidPosition, string.Empty);
}
else
{
do
{
// we need to check both XmlReader.IsDefault and XmlReader.SchemaInfo.IsDefault.
// If either of these is true and defattr=false, we should not write the attribute out
if (defattr || !reader.IsDefaultInternal)
{
WriteStartAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI);
while (reader.ReadAttributeValue())
{
if (reader.NodeType == XmlNodeType.EntityReference)
{
WriteEntityRef(reader.Name);
}
else
{
WriteString(reader.Value);
}
}
WriteEndAttribute();
}
}
while (reader.MoveToNextAttribute());
}
}
// Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader
// to the corresponding end element.
public virtual void WriteNode(XmlReader reader!!, bool defattr)
{
bool canReadChunk = reader.CanReadValueChunk;
int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth;
do
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
WriteAttributes(reader, defattr);
if (reader.IsEmptyElement)
{
WriteEndElement();
}
break;
case XmlNodeType.Text:
if (canReadChunk)
{
_writeNodeBuffer ??= new char[WriteNodeBufferSize];
int read;
while ((read = reader.ReadValueChunk(_writeNodeBuffer, 0, WriteNodeBufferSize)) > 0)
{
WriteChars(_writeNodeBuffer, 0, read);
}
}
else
{
WriteString(reader.Value);
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
WriteWhitespace(reader.Value);
break;
case XmlNodeType.CDATA:
WriteCData(reader.Value);
break;
case XmlNodeType.EntityReference:
WriteEntityRef(reader.Name);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
WriteProcessingInstruction(reader.Name, reader.Value);
break;
case XmlNodeType.DocumentType:
WriteDocType(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value);
break;
case XmlNodeType.Comment:
WriteComment(reader.Value);
break;
case XmlNodeType.EndElement:
WriteFullEndElement();
break;
}
} while (reader.Read() && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement)));
}
// Copies the current node from the given XPathNavigator to the writer (including child nodes).
public virtual void WriteNode(XPathNavigator navigator!!, bool defattr)
{
int iLevel = 0;
navigator = navigator.Clone();
while (true)
{
bool mayHaveChildren = false;
XPathNodeType nodeType = navigator.NodeType;
switch (nodeType)
{
case XPathNodeType.Element:
WriteStartElement(navigator.Prefix, navigator.LocalName, navigator.NamespaceURI);
// Copy attributes
if (navigator.MoveToFirstAttribute())
{
do
{
IXmlSchemaInfo? schemaInfo = navigator.SchemaInfo;
if (defattr || (schemaInfo == null || !schemaInfo.IsDefault))
{
WriteStartAttribute(navigator.Prefix, navigator.LocalName, navigator.NamespaceURI);
// copy string value to writer
WriteString(navigator.Value);
WriteEndAttribute();
}
} while (navigator.MoveToNextAttribute());
navigator.MoveToParent();
}
// Copy namespaces
if (navigator.MoveToFirstNamespace(XPathNamespaceScope.Local))
{
WriteLocalNamespaces(navigator);
navigator.MoveToParent();
}
mayHaveChildren = true;
break;
case XPathNodeType.Attribute:
// do nothing on root level attribute
break;
case XPathNodeType.Text:
WriteString(navigator.Value);
break;
case XPathNodeType.SignificantWhitespace:
case XPathNodeType.Whitespace:
WriteWhitespace(navigator.Value);
break;
case XPathNodeType.Root:
mayHaveChildren = true;
break;
case XPathNodeType.Comment:
WriteComment(navigator.Value);
break;
case XPathNodeType.ProcessingInstruction:
WriteProcessingInstruction(navigator.LocalName, navigator.Value);
break;
case XPathNodeType.Namespace:
// do nothing on root level namespace
break;
default:
Debug.Fail($"Unexpected node type {nodeType}");
break;
}
if (mayHaveChildren)
{
// If children exist, move down to next level
if (navigator.MoveToFirstChild())
{
iLevel++;
continue;
}
// EndElement
if (navigator.NodeType == XPathNodeType.Element)
{
if (navigator.IsEmptyElement)
{
WriteEndElement();
}
else
{
WriteFullEndElement();
}
}
}
// No children
while (true)
{
if (iLevel == 0)
{
// The entire subtree has been copied
return;
}
if (navigator.MoveToNext())
{
// Found a sibling, so break to outer loop
break;
}
// No siblings, so move up to previous level
iLevel--;
navigator.MoveToParent();
// EndElement
if (navigator.NodeType == XPathNodeType.Element)
WriteFullEndElement();
}
}
}
// Element Helper Methods
// Writes out an element with the specified name containing the specified string value.
public void WriteElementString(string localName, string? value)
{
WriteElementString(localName, null, value);
}
// Writes out an attribute with the specified name, namespace URI and string value.
public void WriteElementString(string localName, string? ns, string? value)
{
WriteStartElement(localName, ns);
if (!string.IsNullOrEmpty(value))
{
WriteString(value);
}
WriteEndElement();
}
// Writes out an attribute with the specified name, namespace URI, and string value.
public void WriteElementString(string? prefix, string localName, string? ns, string? value)
{
WriteStartElement(prefix, localName, ns);
if (!string.IsNullOrEmpty(value))
{
WriteString(value);
}
WriteEndElement();
}
public void Dispose()
{
Dispose(true);
}
// Dispose the underline stream objects (calls Close on the XmlWriter)
protected virtual void Dispose(bool disposing)
{
if (disposing && WriteState != WriteState.Closed)
{
Close();
}
}
// Copy local namespaces on the navigator's current node to the raw writer. The namespaces are returned by the navigator in reversed order.
// The recursive call reverses them back.
private void WriteLocalNamespaces(XPathNavigator nsNav)
{
string prefix = nsNav.LocalName;
string ns = nsNav.Value;
if (nsNav.MoveToNextNamespace(XPathNamespaceScope.Local))
{
WriteLocalNamespaces(nsNav);
}
if (prefix.Length == 0)
{
WriteAttributeString(string.Empty, "xmlns", XmlReservedNs.NsXmlNs, ns);
}
else
{
WriteAttributeString("xmlns", prefix, XmlReservedNs.NsXmlNs, ns);
}
}
//
// Static methods for creating writers
//
// Creates an XmlWriter for writing into the provided file.
public static XmlWriter Create(string outputFileName!!)
{
// Avoid using XmlWriter.Create(string, XmlReaderSettings), as it references a lot of types
// that then can't be trimmed away.
var fs = new FileStream(outputFileName, FileMode.Create, FileAccess.Write, FileShare.Read);
try
{
var settings = new XmlWriterSettings { CloseOutput = true };
XmlWriter writer = new XmlEncodedRawTextWriter(fs, settings);
return new XmlWellFormedWriter(writer, settings);
}
catch
{
fs.Dispose();
throw;
}
}
// Creates an XmlWriter for writing into the provided file with the specified settings.
public static XmlWriter Create(string outputFileName, XmlWriterSettings? settings)
{
settings ??= XmlWriterSettings.s_defaultWriterSettings;
return settings.CreateWriter(outputFileName);
}
// Creates an XmlWriter for writing into the provided stream.
public static XmlWriter Create(Stream output!!)
{
// Avoid using XmlWriter.Create(Stream, XmlReaderSettings), as it references a lot of types
// that then can't be trimmed away.
XmlWriterSettings settings = XmlWriterSettings.s_defaultWriterSettings;
XmlWriter writer = new XmlUtf8RawTextWriter(output, settings);
return new XmlWellFormedWriter(writer, settings);
}
// Creates an XmlWriter for writing into the provided stream with the specified settings.
public static XmlWriter Create(Stream output, XmlWriterSettings? settings)
{
settings ??= XmlWriterSettings.s_defaultWriterSettings;
return settings.CreateWriter(output);
}
// Creates an XmlWriter for writing into the provided TextWriter.
public static XmlWriter Create(TextWriter output!!)
{
// Avoid using XmlWriter.Create(TextWriter, XmlReaderSettings), as it references a lot of types
// that then can't be trimmed away.
XmlWriterSettings settings = XmlWriterSettings.s_defaultWriterSettings;
XmlWriter writer = new XmlEncodedRawTextWriter(output, settings);
return new XmlWellFormedWriter(writer, settings);
}
// Creates an XmlWriter for writing into the provided TextWriter with the specified settings.
public static XmlWriter Create(TextWriter output, XmlWriterSettings? settings)
{
settings ??= XmlWriterSettings.s_defaultWriterSettings;
return settings.CreateWriter(output);
}
// Creates an XmlWriter for writing into the provided StringBuilder.
public static XmlWriter Create(StringBuilder output!!)
{
// Avoid using XmlWriter.Create(StringBuilder, XmlReaderSettings), as it references a lot of types
// that then can't be trimmed away.
return Create(new StringWriter(output, CultureInfo.InvariantCulture));
}
// Creates an XmlWriter for writing into the provided StringBuilder with the specified settings.
public static XmlWriter Create(StringBuilder output!!, XmlWriterSettings? settings)
{
settings ??= XmlWriterSettings.s_defaultWriterSettings;
return settings.CreateWriter(new StringWriter(output, CultureInfo.InvariantCulture));
}
// Creates an XmlWriter wrapped around the provided XmlWriter with the default settings.
public static XmlWriter Create(XmlWriter output)
{
return Create(output, null);
}
// Creates an XmlWriter wrapped around the provided XmlWriter with the specified settings.
public static XmlWriter Create(XmlWriter output, XmlWriterSettings? settings)
{
settings ??= XmlWriterSettings.s_defaultWriterSettings;
return settings.CreateWriter(output);
}
}
}
|
// 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.Text;
using System.Xml.XPath;
using System.Xml.Schema;
using System.Diagnostics;
using System.Globalization;
namespace System.Xml
{
// Specifies the state of the XmlWriter.
public enum WriteState
{
// Nothing has been written yet.
Start,
// Writing the prolog.
Prolog,
// Writing a the start tag for an element.
Element,
// Writing an attribute value.
Attribute,
// Writing element content.
Content,
// XmlWriter is closed; Close has been called.
Closed,
// Writer is in error state.
Error
};
// Represents a writer that provides fast non-cached forward-only way of generating XML streams containing XML documents
// that conform to the W3C Extensible Markup Language (XML) 1.0 specification and the Namespaces in XML specification.
public abstract partial class XmlWriter : IDisposable
{
// Helper buffer for WriteNode(XmlReader, bool)
private char[]? _writeNodeBuffer;
// Constants
private const int WriteNodeBufferSize = 1024;
// Returns the settings describing the features of the writer. Returns null for V1 XmlWriters (XmlTextWriter).
public virtual XmlWriterSettings? Settings => null;
// Write methods
// Writes out the XML declaration with the version "1.0".
public abstract void WriteStartDocument();
//Writes out the XML declaration with the version "1.0" and the specified standalone attribute.
public abstract void WriteStartDocument(bool standalone);
//Closes any open elements or attributes and puts the writer back in the Start state.
public abstract void WriteEndDocument();
// Writes out the DOCTYPE declaration with the specified name and optional attributes.
public abstract void WriteDocType(string name, string? pubid, string? sysid, string? subset);
// Writes out the specified start tag and associates it with the given namespace.
public void WriteStartElement(string localName, string? ns)
{
WriteStartElement(null, localName, ns);
}
// Writes out the specified start tag and associates it with the given namespace and prefix.
public abstract void WriteStartElement(string? prefix, string localName, string? ns);
// Writes out a start tag with the specified local name with no namespace.
public void WriteStartElement(string localName)
{
WriteStartElement(null, localName, null);
}
// Closes one element and pops the corresponding namespace scope.
public abstract void WriteEndElement();
// Closes one element and pops the corresponding namespace scope. Writes out a full end element tag, e.g. </element>.
public abstract void WriteFullEndElement();
// Writes out the attribute with the specified LocalName, value, and NamespaceURI.
public void WriteAttributeString(string localName, string? ns, string? value)
{
WriteStartAttribute(null, localName, ns);
WriteString(value);
WriteEndAttribute();
}
// Writes out the attribute with the specified LocalName and value.
public void WriteAttributeString(string localName, string? value)
{
WriteStartAttribute(null, localName, null);
WriteString(value);
WriteEndAttribute();
}
// Writes out the attribute with the specified prefix, LocalName, NamespaceURI and value.
public void WriteAttributeString(string? prefix, string localName, string? ns, string? value)
{
WriteStartAttribute(prefix, localName, ns);
WriteString(value);
WriteEndAttribute();
}
// Writes the start of an attribute.
public void WriteStartAttribute(string localName, string? ns)
{
WriteStartAttribute(null, localName, ns);
}
// Writes the start of an attribute.
public abstract void WriteStartAttribute(string? prefix, string localName, string? ns);
// Writes the start of an attribute.
public void WriteStartAttribute(string localName)
{
WriteStartAttribute(null, localName, null);
}
// Closes the attribute opened by WriteStartAttribute call.
public abstract void WriteEndAttribute();
// Writes out a <![CDATA[...]]>; block containing the specified text.
public abstract void WriteCData(string? text);
// Writes out a comment <!--...-->; containing the specified text.
public abstract void WriteComment(string? text);
// Writes out a processing instruction with a space between the name and text as follows: <?name text?>
public abstract void WriteProcessingInstruction(string name, string? text);
// Writes out an entity reference as follows: "&"+name+";".
public abstract void WriteEntityRef(string name);
// Forces the generation of a character entity for the specified Unicode character value.
public abstract void WriteCharEntity(char ch);
// Writes out the given whitespace.
public abstract void WriteWhitespace(string? ws);
// Writes out the specified text content.
public abstract void WriteString(string? text);
// Write out the given surrogate pair as an entity reference.
public abstract void WriteSurrogateCharEntity(char lowChar, char highChar);
// Writes out the specified text content.
public abstract void WriteChars(char[] buffer, int index, int count);
// Writes raw markup from the given character buffer.
public abstract void WriteRaw(char[] buffer, int index, int count);
// Writes raw markup from the given string.
public abstract void WriteRaw(string data);
// Encodes the specified binary bytes as base64 and writes out the resulting text.
public abstract void WriteBase64(byte[] buffer, int index, int count);
// Encodes the specified binary bytes as bin hex and writes out the resulting text.
public virtual void WriteBinHex(byte[] buffer, int index, int count)
{
BinHexEncoder.Encode(buffer, index, count, this);
}
// Returns the state of the XmlWriter.
public abstract WriteState WriteState { get; }
// Closes the XmlWriter and the underlying stream/TextReader (if Settings.CloseOutput is true).
public virtual void Close() { }
// Flushes data that is in the internal buffers into the underlying streams/TextReader and flushes the stream/TextReader.
public abstract void Flush();
// Returns the closest prefix defined in the current namespace scope for the specified namespace URI.
public abstract string? LookupPrefix(string ns);
// Gets an XmlSpace representing the current xml:space scope.
public virtual XmlSpace XmlSpace => XmlSpace.Default;
// Gets the current xml:lang scope.
public virtual string? XmlLang => string.Empty;
// Scalar Value Methods
// Writes out the specified name, ensuring it is a valid NmToken according to the XML specification
// (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).
public virtual void WriteNmToken(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException(SR.Xml_EmptyName);
}
WriteString(XmlConvert.VerifyNMTOKEN(name, ExceptionType.ArgumentException));
}
// Writes out the specified name, ensuring it is a valid Name according to the XML specification
// (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).
public virtual void WriteName(string name)
{
WriteString(XmlConvert.VerifyQName(name, ExceptionType.ArgumentException));
}
// Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace.
public virtual void WriteQualifiedName(string localName, string? ns)
{
if (!string.IsNullOrEmpty(ns))
{
string? prefix = LookupPrefix(ns);
if (prefix == null)
{
throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns));
}
WriteString(prefix);
WriteString(":");
}
WriteString(localName);
}
// Writes out the specified value.
public virtual void WriteValue(object value!!)
{
WriteString(XmlUntypedConverter.Untyped.ToString(value, null));
}
// Writes out the specified value.
public virtual void WriteValue(string? value)
{
if (value != null)
{
WriteString(value);
}
}
// Writes out the specified value.
public virtual void WriteValue(bool value)
{
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
public virtual void WriteValue(DateTime value)
{
WriteString(XmlConvert.ToString(value, XmlDateTimeSerializationMode.RoundtripKind));
}
// Writes out the specified value.
public virtual void WriteValue(DateTimeOffset value)
{
// Under Win8P, WriteValue(DateTime) will invoke this overload, but custom writers
// might not have implemented it. This base implementation should call WriteValue(DateTime).
// The following conversion results in the same string as calling ToString with DateTimeOffset.
WriteValue(value.Offset != TimeSpan.Zero ? value.LocalDateTime : value.UtcDateTime);
}
// Writes out the specified value.
public virtual void WriteValue(double value)
{
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
public virtual void WriteValue(float value)
{
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
public virtual void WriteValue(decimal value)
{
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
public virtual void WriteValue(int value)
{
WriteString(XmlConvert.ToString(value));
}
// Writes out the specified value.
public virtual void WriteValue(long value)
{
WriteString(XmlConvert.ToString(value));
}
// XmlReader Helper Methods
// Writes out all the attributes found at the current position in the specified XmlReader.
public virtual void WriteAttributes(XmlReader reader!!, bool defattr)
{
if (reader.NodeType is XmlNodeType.Element or XmlNodeType.XmlDeclaration)
{
if (reader.MoveToFirstAttribute())
{
WriteAttributes(reader, defattr);
reader.MoveToElement();
}
}
else if (reader.NodeType != XmlNodeType.Attribute)
{
throw new XmlException(SR.Xml_InvalidPosition, string.Empty);
}
else
{
do
{
// we need to check both XmlReader.IsDefault and XmlReader.SchemaInfo.IsDefault.
// If either of these is true and defattr=false, we should not write the attribute out
if (defattr || !reader.IsDefaultInternal)
{
WriteStartAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI);
while (reader.ReadAttributeValue())
{
if (reader.NodeType == XmlNodeType.EntityReference)
{
WriteEntityRef(reader.Name);
}
else
{
WriteString(reader.Value);
}
}
WriteEndAttribute();
}
}
while (reader.MoveToNextAttribute());
}
}
// Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader
// to the corresponding end element.
public virtual void WriteNode(XmlReader reader!!, bool defattr)
{
bool canReadChunk = reader.CanReadValueChunk;
int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth;
do
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
WriteAttributes(reader, defattr);
if (reader.IsEmptyElement)
{
WriteEndElement();
}
break;
case XmlNodeType.Text:
if (canReadChunk)
{
_writeNodeBuffer ??= new char[WriteNodeBufferSize];
int read;
while ((read = reader.ReadValueChunk(_writeNodeBuffer, 0, WriteNodeBufferSize)) > 0)
{
WriteChars(_writeNodeBuffer, 0, read);
}
}
else
{
WriteString(reader.Value);
}
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
WriteWhitespace(reader.Value);
break;
case XmlNodeType.CDATA:
WriteCData(reader.Value);
break;
case XmlNodeType.EntityReference:
WriteEntityRef(reader.Name);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
WriteProcessingInstruction(reader.Name, reader.Value);
break;
case XmlNodeType.DocumentType:
WriteDocType(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value);
break;
case XmlNodeType.Comment:
WriteComment(reader.Value);
break;
case XmlNodeType.EndElement:
WriteFullEndElement();
break;
}
} while (reader.Read() && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement)));
}
// Copies the current node from the given XPathNavigator to the writer (including child nodes).
public virtual void WriteNode(XPathNavigator navigator!!, bool defattr)
{
int iLevel = 0;
navigator = navigator.Clone();
while (true)
{
bool mayHaveChildren = false;
XPathNodeType nodeType = navigator.NodeType;
switch (nodeType)
{
case XPathNodeType.Element:
WriteStartElement(navigator.Prefix, navigator.LocalName, navigator.NamespaceURI);
// Copy attributes
if (navigator.MoveToFirstAttribute())
{
do
{
IXmlSchemaInfo? schemaInfo = navigator.SchemaInfo;
if (defattr || (schemaInfo == null || !schemaInfo.IsDefault))
{
WriteStartAttribute(navigator.Prefix, navigator.LocalName, navigator.NamespaceURI);
// copy string value to writer
WriteString(navigator.Value);
WriteEndAttribute();
}
} while (navigator.MoveToNextAttribute());
navigator.MoveToParent();
}
// Copy namespaces
if (navigator.MoveToFirstNamespace(XPathNamespaceScope.Local))
{
WriteLocalNamespaces(navigator);
navigator.MoveToParent();
}
mayHaveChildren = true;
break;
case XPathNodeType.Attribute:
// do nothing on root level attribute
break;
case XPathNodeType.Text:
WriteString(navigator.Value);
break;
case XPathNodeType.SignificantWhitespace:
case XPathNodeType.Whitespace:
WriteWhitespace(navigator.Value);
break;
case XPathNodeType.Root:
mayHaveChildren = true;
break;
case XPathNodeType.Comment:
WriteComment(navigator.Value);
break;
case XPathNodeType.ProcessingInstruction:
WriteProcessingInstruction(navigator.LocalName, navigator.Value);
break;
case XPathNodeType.Namespace:
// do nothing on root level namespace
break;
default:
Debug.Fail($"Unexpected node type {nodeType}");
break;
}
if (mayHaveChildren)
{
// If children exist, move down to next level
if (navigator.MoveToFirstChild())
{
iLevel++;
continue;
}
// EndElement
if (navigator.NodeType == XPathNodeType.Element)
{
if (navigator.IsEmptyElement)
{
WriteEndElement();
}
else
{
WriteFullEndElement();
}
}
}
// No children
while (true)
{
if (iLevel == 0)
{
// The entire subtree has been copied
return;
}
if (navigator.MoveToNext())
{
// Found a sibling, so break to outer loop
break;
}
// No siblings, so move up to previous level
iLevel--;
navigator.MoveToParent();
// EndElement
if (navigator.NodeType == XPathNodeType.Element)
WriteFullEndElement();
}
}
}
// Element Helper Methods
// Writes out an element with the specified name containing the specified string value.
public void WriteElementString(string localName, string? value)
{
WriteElementString(localName, null, value);
}
// Writes out an attribute with the specified name, namespace URI and string value.
public void WriteElementString(string localName, string? ns, string? value)
{
WriteStartElement(localName, ns);
if (!string.IsNullOrEmpty(value))
{
WriteString(value);
}
WriteEndElement();
}
// Writes out an attribute with the specified name, namespace URI, and string value.
public void WriteElementString(string? prefix, string localName, string? ns, string? value)
{
WriteStartElement(prefix, localName, ns);
if (!string.IsNullOrEmpty(value))
{
WriteString(value);
}
WriteEndElement();
}
public void Dispose()
{
Dispose(true);
}
// Dispose the underline stream objects (calls Close on the XmlWriter)
protected virtual void Dispose(bool disposing)
{
if (disposing && WriteState != WriteState.Closed)
{
Close();
}
}
// Copy local namespaces on the navigator's current node to the raw writer. The namespaces are returned by the navigator in reversed order.
// The recursive call reverses them back.
private void WriteLocalNamespaces(XPathNavigator nsNav)
{
string prefix = nsNav.LocalName;
string ns = nsNav.Value;
if (nsNav.MoveToNextNamespace(XPathNamespaceScope.Local))
{
WriteLocalNamespaces(nsNav);
}
if (prefix.Length == 0)
{
WriteAttributeString(string.Empty, "xmlns", XmlReservedNs.NsXmlNs, ns);
}
else
{
WriteAttributeString("xmlns", prefix, XmlReservedNs.NsXmlNs, ns);
}
}
//
// Static methods for creating writers
//
// Creates an XmlWriter for writing into the provided file.
public static XmlWriter Create(string outputFileName!!)
{
// Avoid using XmlWriter.Create(string, XmlReaderSettings), as it references a lot of types
// that then can't be trimmed away.
var fs = new FileStream(outputFileName, FileMode.Create, FileAccess.Write, FileShare.Read);
try
{
var settings = new XmlWriterSettings { CloseOutput = true };
XmlWriter writer = new XmlEncodedRawTextWriter(fs, settings);
return new XmlWellFormedWriter(writer, settings);
}
catch
{
fs.Dispose();
throw;
}
}
// Creates an XmlWriter for writing into the provided file with the specified settings.
public static XmlWriter Create(string outputFileName, XmlWriterSettings? settings)
{
settings ??= XmlWriterSettings.s_defaultWriterSettings;
return settings.CreateWriter(outputFileName);
}
// Creates an XmlWriter for writing into the provided stream.
public static XmlWriter Create(Stream output!!)
{
// Avoid using XmlWriter.Create(Stream, XmlReaderSettings), as it references a lot of types
// that then can't be trimmed away.
XmlWriterSettings settings = XmlWriterSettings.s_defaultWriterSettings;
XmlWriter writer = new XmlUtf8RawTextWriter(output, settings);
return new XmlWellFormedWriter(writer, settings);
}
// Creates an XmlWriter for writing into the provided stream with the specified settings.
public static XmlWriter Create(Stream output, XmlWriterSettings? settings)
{
settings ??= XmlWriterSettings.s_defaultWriterSettings;
return settings.CreateWriter(output);
}
// Creates an XmlWriter for writing into the provided TextWriter.
public static XmlWriter Create(TextWriter output!!)
{
// Avoid using XmlWriter.Create(TextWriter, XmlReaderSettings), as it references a lot of types
// that then can't be trimmed away.
XmlWriterSettings settings = XmlWriterSettings.s_defaultWriterSettings;
XmlWriter writer = new XmlEncodedRawTextWriter(output, settings);
return new XmlWellFormedWriter(writer, settings);
}
// Creates an XmlWriter for writing into the provided TextWriter with the specified settings.
public static XmlWriter Create(TextWriter output, XmlWriterSettings? settings)
{
settings ??= XmlWriterSettings.s_defaultWriterSettings;
return settings.CreateWriter(output);
}
// Creates an XmlWriter for writing into the provided StringBuilder.
public static XmlWriter Create(StringBuilder output!!)
{
// Avoid using XmlWriter.Create(StringBuilder, XmlReaderSettings), as it references a lot of types
// that then can't be trimmed away.
return Create(new StringWriter(output, CultureInfo.InvariantCulture));
}
// Creates an XmlWriter for writing into the provided StringBuilder with the specified settings.
public static XmlWriter Create(StringBuilder output!!, XmlWriterSettings? settings)
{
settings ??= XmlWriterSettings.s_defaultWriterSettings;
return settings.CreateWriter(new StringWriter(output, CultureInfo.InvariantCulture));
}
// Creates an XmlWriter wrapped around the provided XmlWriter with the default settings.
public static XmlWriter Create(XmlWriter output)
{
return Create(output, null);
}
// Creates an XmlWriter wrapped around the provided XmlWriter with the specified settings.
public static XmlWriter Create(XmlWriter output, XmlWriterSettings? settings)
{
settings ??= XmlWriterSettings.s_defaultWriterSettings;
return settings.CreateWriter(output);
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/Microsoft.Extensions.Hosting/tests/FunctionalTests/ShutdownTests.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.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting.IntegrationTesting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Test;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Hosting.FunctionalTests
{
public class ShutdownTests
{
private static readonly string StartedMessage = "Started";
private static readonly string CompletionMessage = "Stopping firing\n" +
"Stopping end\n" +
"Stopped firing\n" +
"Stopped end";
private readonly ITestOutputHelper _output;
public ShutdownTests(ITestOutputHelper output)
{
_output = output;
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34090")]
[PlatformSpecific(TestPlatforms.Linux)]
public async Task ShutdownTestRun()
{
await ExecuteShutdownTest(nameof(ShutdownTestRun), "Run");
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34090")]
[PlatformSpecific(TestPlatforms.Linux)]
public async Task ShutdownTestWaitForShutdown()
{
await ExecuteShutdownTest(nameof(ShutdownTestWaitForShutdown), "WaitForShutdown");
}
private async Task ExecuteShutdownTest(string testName, string shutdownMechanic)
{
var xunitTestLoggerFactory = TestLoggerBuilder.Create(builder =>
{
builder.SetMinimumLevel(LogLevel.Trace);
builder.AddXunit(_output);
});
// TODO refactor deployers to not depend on source code
// see https://github.com/dotnet/extensions/issues/1697 and https://github.com/dotnet/aspnetcore/issues/10268
#pragma warning disable 0618
var applicationPath = string.Empty; // disabled for now
#pragma warning restore 0618
var deploymentParameters = new DeploymentParameters(
applicationPath,
RuntimeFlavor.CoreClr,
RuntimeArchitecture.x64)
{
TargetFramework = Tfm.NetCoreApp50,
ApplicationType = ApplicationType.Portable,
PublishApplicationBeforeDeployment = true,
StatusMessagesEnabled = false
};
deploymentParameters.EnvironmentVariables["DOTNET_STARTMECHANIC"] = shutdownMechanic;
using (var deployer = new SelfHostDeployer(deploymentParameters, xunitTestLoggerFactory))
{
var result = await deployer.DeployAsync();
var started = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
var completed = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
var output = string.Empty;
deployer.HostProcess.OutputDataReceived += (sender, args) =>
{
if (!string.IsNullOrEmpty(args.Data) && args.Data.StartsWith(StartedMessage))
{
output += args.Data.Substring(StartedMessage.Length) + '\n';
started.TrySetResult(0);
}
else
{
output += args.Data + '\n';
}
if (output.Contains(CompletionMessage))
{
completed.TrySetResult(0);
}
};
await started.Task.WaitAsync(TimeSpan.FromSeconds(60));
SendShutdownSignal(deployer.HostProcess);
await completed.Task.WaitAsync(TimeSpan.FromSeconds(60));
WaitForExitOrKill(deployer.HostProcess);
output = output.Trim('\n');
Assert.Equal(CompletionMessage, output);
}
}
private void SendShutdownSignal(Process hostProcess)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
SendSIGINT(hostProcess.Id);
}
/*
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
SendCtlC(hostProcess);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
}
*/
else
{
throw new PlatformNotSupportedException();
}
}
private static void SendSIGINT(int processId)
{
var startInfo = new ProcessStartInfo
{
FileName = "kill",
Arguments = processId.ToString(),
RedirectStandardOutput = true,
UseShellExecute = false
};
var process = Process.Start(startInfo);
WaitForExitOrKill(process);
}
private static void WaitForExitOrKill(Process process)
{
process.WaitForExit(1000);
if (!process.HasExited)
{
process.Kill();
}
Assert.Equal(0, process.ExitCode);
}
}
}
|
// 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.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting.IntegrationTesting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Test;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Hosting.FunctionalTests
{
public class ShutdownTests
{
private static readonly string StartedMessage = "Started";
private static readonly string CompletionMessage = "Stopping firing\n" +
"Stopping end\n" +
"Stopped firing\n" +
"Stopped end";
private readonly ITestOutputHelper _output;
public ShutdownTests(ITestOutputHelper output)
{
_output = output;
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34090")]
[PlatformSpecific(TestPlatforms.Linux)]
public async Task ShutdownTestRun()
{
await ExecuteShutdownTest(nameof(ShutdownTestRun), "Run");
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34090")]
[PlatformSpecific(TestPlatforms.Linux)]
public async Task ShutdownTestWaitForShutdown()
{
await ExecuteShutdownTest(nameof(ShutdownTestWaitForShutdown), "WaitForShutdown");
}
private async Task ExecuteShutdownTest(string testName, string shutdownMechanic)
{
var xunitTestLoggerFactory = TestLoggerBuilder.Create(builder =>
{
builder.SetMinimumLevel(LogLevel.Trace);
builder.AddXunit(_output);
});
// TODO refactor deployers to not depend on source code
// see https://github.com/dotnet/extensions/issues/1697 and https://github.com/dotnet/aspnetcore/issues/10268
#pragma warning disable 0618
var applicationPath = string.Empty; // disabled for now
#pragma warning restore 0618
var deploymentParameters = new DeploymentParameters(
applicationPath,
RuntimeFlavor.CoreClr,
RuntimeArchitecture.x64)
{
TargetFramework = Tfm.NetCoreApp50,
ApplicationType = ApplicationType.Portable,
PublishApplicationBeforeDeployment = true,
StatusMessagesEnabled = false
};
deploymentParameters.EnvironmentVariables["DOTNET_STARTMECHANIC"] = shutdownMechanic;
using (var deployer = new SelfHostDeployer(deploymentParameters, xunitTestLoggerFactory))
{
var result = await deployer.DeployAsync();
var started = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
var completed = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
var output = string.Empty;
deployer.HostProcess.OutputDataReceived += (sender, args) =>
{
if (!string.IsNullOrEmpty(args.Data) && args.Data.StartsWith(StartedMessage))
{
output += args.Data.Substring(StartedMessage.Length) + '\n';
started.TrySetResult(0);
}
else
{
output += args.Data + '\n';
}
if (output.Contains(CompletionMessage))
{
completed.TrySetResult(0);
}
};
await started.Task.WaitAsync(TimeSpan.FromSeconds(60));
SendShutdownSignal(deployer.HostProcess);
await completed.Task.WaitAsync(TimeSpan.FromSeconds(60));
WaitForExitOrKill(deployer.HostProcess);
output = output.Trim('\n');
Assert.Equal(CompletionMessage, output);
}
}
private void SendShutdownSignal(Process hostProcess)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
SendSIGINT(hostProcess.Id);
}
/*
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
SendCtlC(hostProcess);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
}
*/
else
{
throw new PlatformNotSupportedException();
}
}
private static void SendSIGINT(int processId)
{
var startInfo = new ProcessStartInfo
{
FileName = "kill",
Arguments = processId.ToString(),
RedirectStandardOutput = true,
UseShellExecute = false
};
var process = Process.Start(startInfo);
WaitForExitOrKill(process);
}
private static void WaitForExitOrKill(Process process)
{
process.WaitForExit(1000);
if (!process.HasExited)
{
process.Kill();
}
Assert.Equal(0, process.ExitCode);
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/HardwareIntrinsics/X86/Avx1/LoadDquVector256.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.X86;
using System.Runtime.Intrinsics;
namespace IntelHardwareIntrinsicTest
{
class Program
{
const int Pass = 100;
const int Fail = 0;
static unsafe int Main(string[] args)
{
int testResult = Pass;
if (Avx.IsSupported)
{
using (TestTable<int> intTable = new TestTable<int>(new int[8] { 1, -5, 100, 0, 1, 2, 3, 4 }, new int[8]))
{
var vf = Avx.LoadDquVector256((int*)(intTable.inArrayPtr));
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y))
{
Console.WriteLine("AVX LoadDquVector256 failed on int:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
}
using (TestTable<uint> intTable = new TestTable<uint>(new uint[8] { 1, 5, 100, 0, 1, 2, 3, 4 }, new uint[8]))
{
var vf = Avx.LoadDquVector256((uint*)(intTable.inArrayPtr));
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y))
{
Console.WriteLine("AVX LoadDquVector256 failed on uint:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
}
using (TestTable<long> intTable = new TestTable<long>(new long[4] { 1, -5, 100, 0 }, new long[4]))
{
var vf = Avx.LoadDquVector256((long*)(intTable.inArrayPtr));
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y))
{
Console.WriteLine("AVX LoadDquVector256 failed on long:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
}
using (TestTable<ulong> intTable = new TestTable<ulong>(new ulong[4] { 1, 5, 100, 0 }, new ulong[4]))
{
var vf = Avx.LoadDquVector256((ulong*)(intTable.inArrayPtr));
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y))
{
Console.WriteLine("AVX LoadDquVector256 failed on ulong:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
}
using (TestTable<short> intTable = new TestTable<short>(new short[16] { 1, -5, 100, 0, 1, 2, 3, 4, 1, -5, 100, 0, 1, 2, 3, 4 }, new short[16]))
{
var vf = Avx.LoadDquVector256((short*)(intTable.inArrayPtr));
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y))
{
Console.WriteLine("AVX LoadDquVector256 failed on short:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
}
using (TestTable<ushort> intTable = new TestTable<ushort>(new ushort[16] { 1, 5, 100, 0, 1, 2, 3, 4, 1, 5, 100, 0, 1, 2, 3, 4 }, new ushort[16]))
{
var vf = Avx.LoadDquVector256((ushort*)(intTable.inArrayPtr));
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y))
{
Console.WriteLine("AVX LoadDquVector256 failed on ushort:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
}
using (TestTable<byte> intTable = new TestTable<byte>(new byte[32] { 1, 5, 100, 0, 1, 2, 3, 4, 1, 5, 100, 0, 1, 2, 3, 4, 1, 5, 100, 0, 1, 2, 3, 4, 1, 5, 100, 0, 1, 2, 3, 4 }, new byte[32]))
{
var vf = Avx.LoadDquVector256((byte*)(intTable.inArrayPtr));
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y))
{
Console.WriteLine("AVX LoadDquVector256 failed on byte:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
}
using (TestTable<sbyte> intTable = new TestTable<sbyte>(new sbyte[32] { 1, -5, 100, 0, 1, 2, 3, 4, 1, -5, 100, 0, 1, 2, 3, 4, 1, -5, 100, 0, 1, 2, 3, 4, 1, -5, 100, 0, 1, 2, 3, 4 }, new sbyte[32]))
{
var vf = Avx.LoadDquVector256((sbyte*)(intTable.inArrayPtr));
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y))
{
Console.WriteLine("AVX LoadDquVector256 failed on sbyte:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
}
}
return testResult;
}
public unsafe struct TestTable<T> : IDisposable where T : struct
{
public T[] inArray;
public T[] outArray;
public void* inArrayPtr => inHandle.AddrOfPinnedObject().ToPointer();
public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer();
GCHandle inHandle;
GCHandle outHandle;
public TestTable(T[] a, T[] b)
{
this.inArray = a;
this.outArray = b;
inHandle = GCHandle.Alloc(inArray, GCHandleType.Pinned);
outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned);
}
public bool CheckResult(Func<T, T, bool> check)
{
for (int i = 0; i < inArray.Length; i++)
{
if (!check(inArray[i], outArray[i]))
{
return false;
}
}
return true;
}
public void Dispose()
{
inHandle.Free();
outHandle.Free();
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.X86;
using System.Runtime.Intrinsics;
namespace IntelHardwareIntrinsicTest
{
class Program
{
const int Pass = 100;
const int Fail = 0;
static unsafe int Main(string[] args)
{
int testResult = Pass;
if (Avx.IsSupported)
{
using (TestTable<int> intTable = new TestTable<int>(new int[8] { 1, -5, 100, 0, 1, 2, 3, 4 }, new int[8]))
{
var vf = Avx.LoadDquVector256((int*)(intTable.inArrayPtr));
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y))
{
Console.WriteLine("AVX LoadDquVector256 failed on int:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
}
using (TestTable<uint> intTable = new TestTable<uint>(new uint[8] { 1, 5, 100, 0, 1, 2, 3, 4 }, new uint[8]))
{
var vf = Avx.LoadDquVector256((uint*)(intTable.inArrayPtr));
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y))
{
Console.WriteLine("AVX LoadDquVector256 failed on uint:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
}
using (TestTable<long> intTable = new TestTable<long>(new long[4] { 1, -5, 100, 0 }, new long[4]))
{
var vf = Avx.LoadDquVector256((long*)(intTable.inArrayPtr));
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y))
{
Console.WriteLine("AVX LoadDquVector256 failed on long:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
}
using (TestTable<ulong> intTable = new TestTable<ulong>(new ulong[4] { 1, 5, 100, 0 }, new ulong[4]))
{
var vf = Avx.LoadDquVector256((ulong*)(intTable.inArrayPtr));
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y))
{
Console.WriteLine("AVX LoadDquVector256 failed on ulong:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
}
using (TestTable<short> intTable = new TestTable<short>(new short[16] { 1, -5, 100, 0, 1, 2, 3, 4, 1, -5, 100, 0, 1, 2, 3, 4 }, new short[16]))
{
var vf = Avx.LoadDquVector256((short*)(intTable.inArrayPtr));
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y))
{
Console.WriteLine("AVX LoadDquVector256 failed on short:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
}
using (TestTable<ushort> intTable = new TestTable<ushort>(new ushort[16] { 1, 5, 100, 0, 1, 2, 3, 4, 1, 5, 100, 0, 1, 2, 3, 4 }, new ushort[16]))
{
var vf = Avx.LoadDquVector256((ushort*)(intTable.inArrayPtr));
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y))
{
Console.WriteLine("AVX LoadDquVector256 failed on ushort:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
}
using (TestTable<byte> intTable = new TestTable<byte>(new byte[32] { 1, 5, 100, 0, 1, 2, 3, 4, 1, 5, 100, 0, 1, 2, 3, 4, 1, 5, 100, 0, 1, 2, 3, 4, 1, 5, 100, 0, 1, 2, 3, 4 }, new byte[32]))
{
var vf = Avx.LoadDquVector256((byte*)(intTable.inArrayPtr));
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y))
{
Console.WriteLine("AVX LoadDquVector256 failed on byte:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
}
using (TestTable<sbyte> intTable = new TestTable<sbyte>(new sbyte[32] { 1, -5, 100, 0, 1, 2, 3, 4, 1, -5, 100, 0, 1, 2, 3, 4, 1, -5, 100, 0, 1, 2, 3, 4, 1, -5, 100, 0, 1, 2, 3, 4 }, new sbyte[32]))
{
var vf = Avx.LoadDquVector256((sbyte*)(intTable.inArrayPtr));
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y))
{
Console.WriteLine("AVX LoadDquVector256 failed on sbyte:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
}
}
return testResult;
}
public unsafe struct TestTable<T> : IDisposable where T : struct
{
public T[] inArray;
public T[] outArray;
public void* inArrayPtr => inHandle.AddrOfPinnedObject().ToPointer();
public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer();
GCHandle inHandle;
GCHandle outHandle;
public TestTable(T[] a, T[] b)
{
this.inArray = a;
this.outArray = b;
inHandle = GCHandle.Alloc(inArray, GCHandleType.Pinned);
outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned);
}
public bool CheckResult(Func<T, T, bool> check)
{
for (int i = 0; i < inArray.Length; i++)
{
if (!check(inArray[i], outArray[i]))
{
return false;
}
}
return true;
}
public void Dispose()
{
inHandle.Free();
outHandle.Free();
}
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/Microsoft.VisualBasic.Core/tests/Microsoft/VisualBasic/CompilerServices/StructUtilsTests.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 Xunit;
namespace Microsoft.VisualBasic.CompilerServices.Tests
{
public static class StructUtilsTestData
{
public static TheoryData<object, int> RecordsAndLength() => new TheoryData<object, int>
{
{ null, 0 },
{ new Struct_Empty(), 0 },
{ new Struct_T<float>(), 4 },
{ new Struct_T<double>(), 8 },
{ new Struct_T<short>(), 2 },
{ new Struct_T<int>(), 4 },
{ new Struct_T<byte>(), 1 },
{ new Struct_T<long>(), 8 },
{ new Struct_T<DateTime>(), 8 },
{ new Struct_T<bool>(), 2 },
{ new Struct_T<decimal>(), 16 },
{ new Struct_T<char>(), 2 },
{ new Struct_T<string>(), 4 },
{ new Struct_ArrayT<byte>(elementCount: 10), 4 },
{ new Struct_ArrayT<int>(elementCount: 10), 4 },
{ new Struct_FixedArrayT10<byte>(), 10 },
{ new Struct_FixedArrayT10<int>(), 40 },
{ new Struct_FixedArrayT10x20<byte>(), 200 },
{ new Struct_FixedArrayT10x20<int>(), 800 },
{ new Struct_FixedString10(), 10 },
{ new Struct_PrivateInt(), 0 },
{ new Struct_MultipleWithAlignment(), 22 },
};
public struct Struct_Empty { }
public struct Struct_T<T> { public T x; }
public struct Struct_ArrayT<T> { public Struct_ArrayT(int elementCount) { x = new T[elementCount]; } public T[] x; }
public struct Struct_FixedArrayT10<T> { [VBFixedArray(9)] public T[] x; }
public struct Struct_FixedArrayT10x20<T> { [VBFixedArray(9, 19)] public T[] x; }
public struct Struct_FixedString10 { [VBFixedString(10)] public string x; }
#pragma warning disable 0169
public struct Struct_PrivateInt { private int x; }
#pragma warning restore 0169
public struct Struct_MultipleWithAlignment { public byte b; public char c; [VBFixedString(3)] public string s; public decimal d; }
}
}
|
// 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 Xunit;
namespace Microsoft.VisualBasic.CompilerServices.Tests
{
public static class StructUtilsTestData
{
public static TheoryData<object, int> RecordsAndLength() => new TheoryData<object, int>
{
{ null, 0 },
{ new Struct_Empty(), 0 },
{ new Struct_T<float>(), 4 },
{ new Struct_T<double>(), 8 },
{ new Struct_T<short>(), 2 },
{ new Struct_T<int>(), 4 },
{ new Struct_T<byte>(), 1 },
{ new Struct_T<long>(), 8 },
{ new Struct_T<DateTime>(), 8 },
{ new Struct_T<bool>(), 2 },
{ new Struct_T<decimal>(), 16 },
{ new Struct_T<char>(), 2 },
{ new Struct_T<string>(), 4 },
{ new Struct_ArrayT<byte>(elementCount: 10), 4 },
{ new Struct_ArrayT<int>(elementCount: 10), 4 },
{ new Struct_FixedArrayT10<byte>(), 10 },
{ new Struct_FixedArrayT10<int>(), 40 },
{ new Struct_FixedArrayT10x20<byte>(), 200 },
{ new Struct_FixedArrayT10x20<int>(), 800 },
{ new Struct_FixedString10(), 10 },
{ new Struct_PrivateInt(), 0 },
{ new Struct_MultipleWithAlignment(), 22 },
};
public struct Struct_Empty { }
public struct Struct_T<T> { public T x; }
public struct Struct_ArrayT<T> { public Struct_ArrayT(int elementCount) { x = new T[elementCount]; } public T[] x; }
public struct Struct_FixedArrayT10<T> { [VBFixedArray(9)] public T[] x; }
public struct Struct_FixedArrayT10x20<T> { [VBFixedArray(9, 19)] public T[] x; }
public struct Struct_FixedString10 { [VBFixedString(10)] public string x; }
#pragma warning disable 0169
public struct Struct_PrivateInt { private int x; }
#pragma warning restore 0169
public struct Struct_MultipleWithAlignment { public byte b; public char c; [VBFixedString(3)] public string s; public decimal d; }
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/coreclr/nativeaot/System.Private.Reflection.Metadata/src/System.Private.Reflection.Metadata.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\..\System.Private.CoreLib\src\System.Private.CoreLib.csproj" />
</ItemGroup>
<PropertyGroup>
<NativeFormatCommonPath>$(CompilerCommonPath)\Internal\NativeFormat</NativeFormatCommonPath>
<MetadataCommonPath>$(CompilerCommonPath)\Internal\Metadata\NativeFormat</MetadataCommonPath>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(NativeFormatCommonPath)\NativeFormat.cs" />
<Compile Include="$(NativeFormatCommonPath)\NativeFormatReader.cs" />
<Compile Include="$(NativeFormatCommonPath)\NativeFormatReader.Primitives.cs" />
<Compile Include="$(NativeFormatCommonPath)\NativeFormatReader.String.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="$(MetadataCommonPath)\NativeFormatReaderCommonGen.cs" />
<Compile Include="$(MetadataCommonPath)\MdBinaryReader.cs" />
<Compile Include="$(MetadataCommonPath)\MdBinaryReaderGen.cs" />
<Compile Include="$(MetadataCommonPath)\NativeMetadataReader.cs" />
<Compile Include="$(MetadataCommonPath)\NativeFormatReaderGen.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="$(AotCommonPath)\System\Runtime\CompilerServices\__BlockAllReflectionAttribute.cs">
<Link>System\Runtime\CompilerServices\__BlockAllReflectionAttribute.cs</Link>
</Compile>
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\..\System.Private.CoreLib\src\System.Private.CoreLib.csproj" />
</ItemGroup>
<PropertyGroup>
<NativeFormatCommonPath>$(CompilerCommonPath)\Internal\NativeFormat</NativeFormatCommonPath>
<MetadataCommonPath>$(CompilerCommonPath)\Internal\Metadata\NativeFormat</MetadataCommonPath>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(NativeFormatCommonPath)\NativeFormat.cs" />
<Compile Include="$(NativeFormatCommonPath)\NativeFormatReader.cs" />
<Compile Include="$(NativeFormatCommonPath)\NativeFormatReader.Primitives.cs" />
<Compile Include="$(NativeFormatCommonPath)\NativeFormatReader.String.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="$(MetadataCommonPath)\NativeFormatReaderCommonGen.cs" />
<Compile Include="$(MetadataCommonPath)\MdBinaryReader.cs" />
<Compile Include="$(MetadataCommonPath)\MdBinaryReaderGen.cs" />
<Compile Include="$(MetadataCommonPath)\NativeMetadataReader.cs" />
<Compile Include="$(MetadataCommonPath)\NativeFormatReaderGen.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="$(AotCommonPath)\System\Runtime\CompilerServices\__BlockAllReflectionAttribute.cs">
<Link>System\Runtime\CompilerServices\__BlockAllReflectionAttribute.cs</Link>
</Compile>
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/Regression/JitBlue/Runtime_57752/Runtime_57752_2.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
</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>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup>
<DebugType>None</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedFile.CreateFromFile.Tests.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;
using System.IO.Pipes;
using System.Threading.Tasks;
namespace System.IO.MemoryMappedFiles.Tests
{
/// <summary>
/// Tests for MemoryMappedFile.CreateFromFile.
/// </summary>
public class MemoryMappedFileTests_CreateFromFile : MemoryMappedFilesTestBase
{
/// <summary>
/// Tests invalid arguments to the CreateFromFile path parameter.
/// </summary>
[Fact]
public void InvalidArguments_Path()
{
// null is an invalid path
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName()));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName(), 4096));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Read));
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile fileStream parameter.
/// </summary>
[Fact]
public void InvalidArguments_FileStream()
{
// null is an invalid stream
AssertExtensions.Throws<ArgumentNullException>("fileStream", () => MemoryMappedFile.CreateFromFile(null, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile mode parameter.
/// </summary>
[Fact]
public void InvalidArguments_Mode()
{
// FileMode out of range
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42));
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null));
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096));
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096, MemoryMappedFileAccess.ReadWrite));
// FileMode.Append never allowed
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append));
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null));
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096));
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096, MemoryMappedFileAccess.ReadWrite));
// FileMode.CreateNew/Create/OpenOrCreate can't be used with default capacity, as the file will be empty
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Create));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.OpenOrCreate));
// FileMode.Truncate can't be used with default capacity, as resulting file will be empty
using (TempFile file = new TempFile(GetTestFilePath()))
{
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Truncate));
}
}
[Fact]
public void InvalidArguments_Mode_Truncate()
{
// FileMode.Truncate never allowed
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate));
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate, null));
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate, null, 4096));
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate, null, 4096, MemoryMappedFileAccess.ReadWrite));
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile access parameter.
/// </summary>
[Fact]
public void InvalidArguments_Access()
{
// Out of range access values with a path
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(-2)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(42)));
// Write-only access is not allowed on maps (only on views)
AssertExtensions.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write));
// Test the same things, but with a FileStream instead of a path
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// Out of range values with a stream
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(-2), HandleInheritability.None, true));
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(42), HandleInheritability.None, true));
// Write-only access is not allowed
AssertExtensions.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write, HandleInheritability.None, true));
}
}
/// <summary>
/// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used
/// to construct a map over that stream. The combinations should all be valid.
/// </summary>
[Theory]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.CopyOnWrite)]
public void FileAccessAndMapAccessCombinations_Valid(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true))
{
ValidateMemoryMappedFile(mmf, Capacity, mmfAccess);
}
}
/// <summary>
/// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used
/// to construct a map over that stream on Windows. The combinations should all be invalid, resulting in exception.
/// </summary>
[PlatformSpecific(TestPlatforms.Windows)] // On Windows, permission errors come from CreateFromFile
[Theory]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute)] // this and the next are explicitly left off of the Unix test due to differences in Unix permissions
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadWriteExecute)]
public void FileAccessAndMapAccessCombinations_Invalid_Windows(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess)
{
// On Windows, creating the file mapping does the permissions checks, so the exception comes from CreateFromFile.
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess))
{
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true));
}
}
/// <summary>
/// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used
/// to construct a map over that stream on Unix. The combinations should all be invalid, resulting in exception.
/// </summary>
[PlatformSpecific(TestPlatforms.AnyUnix)] // On Unix, permission errors come from CreateView*
[Theory]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWriteExecute)]
public void FileAccessAndMapAccessCombinations_Invalid_Unix(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess)
{
// On Unix we don't actually create the OS map until the view is created; this results in the permissions
// error being thrown from CreateView* instead of from CreateFromFile.
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true))
{
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor());
}
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile mapName parameter.
/// </summary>
[Fact]
public void InvalidArguments_MapName()
{
using (TempFile file = new TempFile(GetTestFilePath()))
{
// Empty string is an invalid map name
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096, MemoryMappedFileAccess.Read));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096, MemoryMappedFileAccess.Read));
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, string.Empty, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true));
}
}
}
/// <summary>
/// Test to verify that map names are left unsupported on Unix.
/// </summary>
[PlatformSpecific(TestPlatforms.AnyUnix)] // Check map names are unsupported on Unix
[Theory]
[MemberData(nameof(CreateValidMapNames))]
public void MapNamesNotSupported_Unix(string mapName)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
{
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity, MemoryMappedFileAccess.ReadWrite));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity, MemoryMappedFileAccess.ReadWrite));
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(fs, mapName, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true));
}
}
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile capacity parameter.
/// </summary>
[Fact]
public void InvalidArguments_Capacity()
{
using (TempFile file = new TempFile(GetTestFilePath()))
{
// Out of range values for capacity
Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), -1));
Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), -1, MemoryMappedFileAccess.Read));
// Positive capacity required when creating a map from an empty file
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, 0, MemoryMappedFileAccess.Read));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 0, MemoryMappedFileAccess.Read));
// With Read, the capacity can't be larger than the backing file's size.
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 1, MemoryMappedFileAccess.Read));
// Now with a FileStream...
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// The subsequent tests are only valid we if we start with an empty FileStream, which we should have.
// This also verifies the previous failed tests didn't change the length of the file.
Assert.Equal(0, fs.Length);
// Out of range values for capacity
Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(fs, null, -1, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
// Default (0) capacity with an empty file
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, null, 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
// Larger capacity than the underlying file, but read-only such that we can't expand the file
fs.SetLength(4096);
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, null, 8192, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 8192, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
// Capacity can't be less than the file size (for such cases a view can be created with the smaller size)
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateFromFile(fs, null, 1, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true));
}
// Capacity can't be less than the file size
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 1, MemoryMappedFileAccess.Read));
}
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile inheritability parameter.
/// </summary>
[Theory]
[InlineData((HandleInheritability)(-1))]
[InlineData((HandleInheritability)(42))]
public void InvalidArguments_Inheritability(HandleInheritability inheritability)
{
// Out of range values for inheritability
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("inheritability", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite, inheritability, true));
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile, focusing on the Open and OpenOrCreate modes,
/// and validating the creating maps each time they're created.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath),
new FileMode[] { FileMode.Open, FileMode.OpenOrCreate },
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.ReadWrite })]
[ActiveIssue("https://github.com/dotnet/runtime/issues/51375", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)]
public void ValidArgumentCombinationsWithPath_ModesOpenOrCreate(
FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access)
{
_ = access;
// Test each of the four path-based CreateFromFile overloads
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
// Finally, re-test the last overload, this time with an empty file to start
using (TempFile file = new TempFile(GetTestFilePath()))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile, focusing on the CreateNew mode,
/// and validating the creating maps each time they're created.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath),
new FileMode[] { FileMode.CreateNew },
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite })]
[ActiveIssue("https://github.com/dotnet/runtime/issues/51375", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)]
public void ValidArgumentCombinationsWithPath_ModeCreateNew(
FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access)
{
// For FileMode.CreateNew, the file will be created new and thus be empty, so we can only use the overloads
// that take a capacity, since the default capacity doesn't work with an empty file.
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity, access))
{
ValidateMemoryMappedFile(mmf, capacity, access);
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile, focusing on the Create mode,
/// and validating the creating maps each time they're created.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidNameCapacityCombinationsWithPath),
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 })]
[ActiveIssue("https://github.com/dotnet/runtime/issues/51375", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)]
public void ValidArgumentCombinationsWithPath_ModeCreate(string mapName, long capacity)
{
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Create, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Create, mapName, capacity, MemoryMappedFileAccess.ReadWrite))
{
ValidateMemoryMappedFile(mmf, capacity, MemoryMappedFileAccess.ReadWrite);
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Create, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
}
/// <summary>
/// Provides input data to the ValidArgumentCombinationsWithPath tests, yielding the full matrix
/// of combinations of input values provided, except for those that are known to be unsupported
/// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders
/// listed in the MemberData attribute (e.g. actual system page size instead of -1).
/// </summary>
/// <param name="modes">The modes to yield.</param>
/// <param name="mapNames">
/// The names to yield.
/// non-null may be excluded based on platform.
/// "CreateUniqueMapName()" will be translated to an invocation of that method.
/// </param>
/// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param>
/// <param name="accesses">
/// The accesses to yield. Non-writable accesses will be skipped if the current mode doesn't support it.
/// </param>
public static IEnumerable<object[]> MemberData_ValidArgumentCombinationsWithPath(
FileMode[] modes, string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses)
{
foreach (object[] namesCaps in MemberData_ValidNameCapacityCombinationsWithPath(mapNames, capacities))
{
foreach (FileMode mode in modes)
{
foreach (MemoryMappedFileAccess access in accesses)
{
if ((mode == FileMode.Create || mode == FileMode.CreateNew || mode == FileMode.Truncate) &&
!IsWritable(access))
{
continue;
}
yield return new object[] { mode, namesCaps[0], namesCaps[1], access };
}
}
}
}
public static IEnumerable<object[]> MemberData_ValidNameCapacityCombinationsWithPath(
string[] mapNames, long[] capacities)
{
foreach (string tmpMapName in mapNames)
{
if (tmpMapName != null && !MapNamesSupported)
{
continue;
}
foreach (long tmpCapacity in capacities)
{
long capacity = tmpCapacity == -1 ? s_pageSize.Value : tmpCapacity;
string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName;
yield return new object[] { mapName, capacity, };
}
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile that accepts a FileStream.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinationsWithStream),
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite },
new HandleInheritability[] { HandleInheritability.None, HandleInheritability.Inheritable },
new bool[] { false, true })]
[ActiveIssue("https://github.com/dotnet/runtime/issues/51375", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)]
public void ValidArgumentCombinationsWithStream(
string mapName, long capacity, MemoryMappedFileAccess access, HandleInheritability inheritability, bool leaveOpen)
{
// Create a file of the right size, then create the map for it.
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, mapName, capacity, access, inheritability, leaveOpen))
{
ValidateMemoryMappedFile(mmf, capacity, access, inheritability);
}
// Start with an empty file and let the map grow it to the right size. This requires write access.
if (IsWritable(access))
{
using (FileStream fs = File.Create(GetTestFilePath()))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, mapName, capacity, access, inheritability, leaveOpen))
{
ValidateMemoryMappedFile(mmf, capacity, access, inheritability);
}
}
}
/// <summary>
/// Provides input data to the ValidArgumentCombinationsWithStream tests, yielding the full matrix
/// of combinations of input values provided, except for those that are known to be unsupported
/// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders
/// listed in the MemberData attribute (e.g. actual system page size instead of -1).
/// </summary>
/// <param name="mapNames">
/// The names to yield.
/// non-null may be excluded based on platform.
/// "CreateUniqueMapName()" will be translated to an invocation of that method.
/// </param>
/// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param>
/// <param name="accesses">
/// The accesses to yield. Non-writable accesses will be skipped if the current mode doesn't support it.
/// </param>
/// <param name="inheritabilities">The inheritabilities to yield.</param>
/// <param name="inheritabilities">The leaveOpen values to yield.</param>
public static IEnumerable<object[]> MemberData_ValidArgumentCombinationsWithStream(
string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses, HandleInheritability[] inheritabilities, bool[] leaveOpens)
{
foreach (string tmpMapName in mapNames)
{
if (tmpMapName != null && !MapNamesSupported)
{
continue;
}
foreach (long tmpCapacity in capacities)
{
long capacity = tmpCapacity == -1 ?
s_pageSize.Value :
tmpCapacity;
foreach (MemoryMappedFileAccess access in accesses)
{
foreach (HandleInheritability inheritability in inheritabilities)
{
foreach (bool leaveOpen in leaveOpens)
{
string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName;
yield return new object[] { mapName, capacity, access, inheritability, leaveOpen };
}
}
}
}
}
}
/// <summary>
/// Test that a map using the default capacity (0) grows to the size of the underlying file.
/// </summary>
[Fact]
public void DefaultCapacityIsFileLength()
{
const int DesiredCapacity = 8192;
const int DefaultCapacity = 0;
// With path
using (TempFile file = new TempFile(GetTestFilePath(), DesiredCapacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, DefaultCapacity))
{
ValidateMemoryMappedFile(mmf, DesiredCapacity);
}
// With stream
using (TempFile file = new TempFile(GetTestFilePath(), DesiredCapacity))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, DefaultCapacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
{
ValidateMemoryMappedFile(mmf, DesiredCapacity);
}
}
/// <summary>
/// Test that appropriate exceptions are thrown creating a map with a non-existent file and a mode
/// that requires the file to exist.
/// </summary>
[Fact]
public void FileDoesNotExist_OpenFileMode()
{
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath()));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, null));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, null, 4096));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, null, 4096, MemoryMappedFileAccess.ReadWrite));
}
/// <summary>
/// Test that appropriate exceptions are thrown creating a map with an existing file and a mode
/// that requires the file to not exist.
/// </summary>
[Fact]
public void FileAlreadyExists()
{
using (TempFile file = new TempFile(GetTestFilePath()))
{
// FileMode.CreateNew invalid when the file already exists
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew));
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName()));
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName(), 4096));
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite));
}
}
/// <summary>
/// Test exceptional behavior when trying to create a map for a read-write file that's currently in use.
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // FileShare is limited on Unix, with None == exclusive, everything else == concurrent
public void FileInUse_CreateFromFile_FailsWithExistingReadWriteFile()
{
// Already opened with a FileStream
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path));
}
}
/// <summary>
/// Test exceptional behavior when trying to create a map for a non-shared file that's currently in use.
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // FileShare is limited on Unix, with None == exclusive, everything else == concurrent
public void FileInUse_CreateFromFile_FailsWithExistingReadWriteMap()
{
// Already opened with another read-write map
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path))
{
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path));
}
}
/// <summary>
/// Test exceptional behavior when trying to create a map for a non-shared file that's currently in use.
/// </summary>
[Fact]
[SkipOnPlatform(TestPlatforms.Browser, "the emscripten implementation ignores FileShare.None")]
public void FileInUse_CreateFromFile_FailsWithExistingNoShareFile()
{
// Already opened with a FileStream
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
using (FileStream fs = File.Open(file.Path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path));
}
}
/// <summary>
/// Test to validate we can create multiple concurrent read-only maps from the same file path.
/// </summary>
[Fact]
public void FileInUse_CreateFromFile_SucceedsWithReadOnly()
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, MemoryMappedFileAccess.Read))
using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, MemoryMappedFileAccess.Read))
using (MemoryMappedViewAccessor acc1 = mmf1.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read))
using (MemoryMappedViewAccessor acc2 = mmf2.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read))
{
Assert.Equal(acc1.Capacity, acc2.Capacity);
}
}
/// <summary>
/// Test the exceptional behavior of *Execute access levels.
/// </summary>
[PlatformSpecific(TestPlatforms.Windows)] // Unix model for executable differs from Windows
[Theory]
[InlineData(MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute)]
public void FileNotOpenedForExecute(MemoryMappedFileAccess access)
{
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
{
// The FileStream created by the map doesn't have GENERIC_EXECUTE set
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, 4096, access));
// The FileStream opened explicitly doesn't have GENERIC_EXECUTE set
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(fs, null, 4096, access, HandleInheritability.None, true));
}
}
}
/// <summary>
/// On Unix, modifying a file that is ReadOnly will fail under normal permissions.
/// If the test is being run under the superuser, however, modification of a ReadOnly
/// file is allowed.
/// </summary>
private void WriteToReadOnlyFile(MemoryMappedFileAccess access, bool succeeds)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
{
FileAttributes original = File.GetAttributes(file.Path);
File.SetAttributes(file.Path, FileAttributes.ReadOnly);
try
{
if (succeeds)
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, access))
ValidateMemoryMappedFile(mmf, Capacity, MemoryMappedFileAccess.Read);
else
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, access));
}
finally
{
File.SetAttributes(file.Path, original);
}
}
}
[Theory]
[InlineData(MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWrite)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/53021", TestPlatforms.Browser)]
public void WriteToReadOnlyFile_ReadWrite(MemoryMappedFileAccess access)
{
WriteToReadOnlyFile(access, access == MemoryMappedFileAccess.Read ||
PlatformDetection.IsSuperUser);
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/53021", TestPlatforms.Browser)]
public void WriteToReadOnlyFile_CopyOnWrite()
{
WriteToReadOnlyFile(MemoryMappedFileAccess.CopyOnWrite, PlatformDetection.IsSuperUser);
}
/// <summary>
/// Test to ensure that leaveOpen is appropriately respected, either leaving the FileStream open
/// or closing it on disposal.
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public void LeaveOpenRespected_Basic(bool leaveOpen)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// Handle should still be open
SafeFileHandle handle = fs.SafeFileHandle;
Assert.False(handle.IsClosed);
// Create and close the map
MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen).Dispose();
// The handle should now be open iff leaveOpen
Assert.NotEqual(leaveOpen, handle.IsClosed);
}
}
/// <summary>
/// Test to ensure that leaveOpen is appropriately respected, either leaving the FileStream open
/// or closing it on disposal.
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public void LeaveOpenRespected_OutstandingViews(bool leaveOpen)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// Handle should still be open
SafeFileHandle handle = fs.SafeFileHandle;
Assert.False(handle.IsClosed);
// Create the map, create each of the views, then close the map
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen))
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, Capacity))
using (MemoryMappedViewStream s = mmf.CreateViewStream(0, Capacity))
{
// Explicitly close the map. The handle should now be open iff leaveOpen.
mmf.Dispose();
Assert.NotEqual(leaveOpen, handle.IsClosed);
// But the views should still be usable.
ValidateMemoryMappedViewAccessor(acc, Capacity, MemoryMappedFileAccess.ReadWrite);
ValidateMemoryMappedViewStream(s, Capacity, MemoryMappedFileAccess.ReadWrite);
}
}
}
/// <summary>
/// Test to validate we can create multiple maps from the same FileStream.
/// </summary>
[Fact]
[SkipOnPlatform(TestPlatforms.Browser, "the emscripten implementation doesn't share data")]
public void MultipleMapsForTheSameFileStream()
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open))
using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
using (MemoryMappedViewAccessor acc1 = mmf1.CreateViewAccessor())
using (MemoryMappedViewAccessor acc2 = mmf2.CreateViewAccessor())
{
// The capacity of the two maps should be equal
Assert.Equal(acc1.Capacity, acc2.Capacity);
var rand = new Random();
for (int i = 1; i <= 10; i++)
{
// Write a value to one map, then read it from the other,
// ping-ponging between the two.
int pos = rand.Next((int)acc1.Capacity - 1);
MemoryMappedViewAccessor reader = acc1, writer = acc2;
if (i % 2 == 0)
{
reader = acc2;
writer = acc1;
}
writer.Write(pos, (byte)i);
writer.Flush();
Assert.Equal(i, reader.ReadByte(pos));
}
}
}
/// <summary>
/// Test to verify that the map's size increases the underlying file size if the map's capacity is larger.
/// </summary>
[Fact]
public void FileSizeExpandsToCapacity()
{
const int InitialCapacity = 256;
using (TempFile file = new TempFile(GetTestFilePath(), InitialCapacity))
{
// Create a map with a larger capacity, and verify the file has expanded.
MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, InitialCapacity * 2).Dispose();
using (FileStream fs = File.OpenRead(file.Path))
{
Assert.Equal(InitialCapacity * 2, fs.Length);
}
// Do the same thing again but with a FileStream.
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
MemoryMappedFile.CreateFromFile(fs, null, InitialCapacity * 4, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true).Dispose();
Assert.Equal(InitialCapacity * 4, fs.Length);
}
}
}
/// <summary>
/// Test the exceptional behavior when attempting to create a map so large it's not supported.
/// </summary>
[SkipOnPlatform(TestPlatforms.OSX, "Because of the file-based backing, OS X pops up a warning dialog about being out-of-space (even though we clean up immediately)")]
[Fact]
public void TooLargeCapacity()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.CreateNew))
{
try
{
long length = long.MaxValue;
MemoryMappedFile.CreateFromFile(fs, null, length, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true).Dispose();
Assert.Equal(length, fs.Length); // if it didn't fail to create the file, the length should be what was requested.
}
catch (IOException)
{
// Expected exception for too large a capacity
}
}
}
/// <summary>
/// Test to verify map names are handled appropriately, causing a conflict when they're active but
/// reusable in a sequential manner.
/// </summary>
[PlatformSpecific(TestPlatforms.Windows)] // Tests reusability of map names on Windows
[Theory]
[MemberData(nameof(CreateValidMapNames))]
public void ReusingNames_Windows(string name)
{
const int Capacity = 4096;
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity))
{
ValidateMemoryMappedFile(mmf, Capacity);
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity));
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity))
{
ValidateMemoryMappedFile(mmf, Capacity);
}
}
private void ValidateDeviceAccess(MemoryMappedFile memMap, long viewCapacity, MemoryMappedFileAccess access)
{
using (MemoryMappedViewAccessor view = memMap.CreateViewAccessor(0, viewCapacity, access))
{
if (access != MemoryMappedFileAccess.Write)
{
byte b = view.ReadByte(0);
// /dev/zero return zeroes.
Assert.Equal(0, b);
}
if (access != MemoryMappedFileAccess.Read)
{
view.Write(0, (byte)1);
}
}
}
/// <summary>
/// Test that we can map special character devices on Unix using FileStream.
/// </summary>
[ConditionalTheory]
[InlineData(MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWrite)]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void OpenCharacterDeviceAsStream(MemoryMappedFileAccess access)
{
const string device = "/dev/zero";
if (!File.Exists(device))
{
throw new SkipTestException($"'{device}' is not available.");
}
long viewCapacity = 0xFF;
try
{
using (FileStream fs = new FileStream(device, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
using (MemoryMappedFile memMap = MemoryMappedFile.CreateFromFile(fs, null, viewCapacity, access, HandleInheritability.None, false))
{
ValidateDeviceAccess(memMap, viewCapacity, access);
}
}
catch (UnauthorizedAccessException) { }
// ENODEV Operation not supported by device.
catch (IOException ex) when (ex.HResult == 19) { };
}
/// <summary>
/// Test that we can map special character devices on Unix using file name.
/// </summary>
[ConditionalTheory]
[InlineData(MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWrite)]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void OpenCharacterDeviceAsFile(MemoryMappedFileAccess access)
{
const string device = "/dev/zero";
if (!File.Exists(device))
{
throw new SkipTestException($"'{device}' is not available.");
}
long viewCapacity = 0xFF;
try
{
using (MemoryMappedFile memMap = MemoryMappedFile.CreateFromFile(device, FileMode.Open, null, viewCapacity, access))
{
ValidateDeviceAccess(memMap, viewCapacity, access);
}
}
catch (UnauthorizedAccessException) { }
// ENODEV Operation not supported by device.
catch (IOException ex) when (ex.HResult == 19) { };
}
/// <summary>
/// Test to verify that the MemoryMappedFile has the same underlying handle as the FileStream it's created from
/// </summary>
[PlatformSpecific(TestPlatforms.AnyUnix)]
[Fact]
public void MapHandleMatchesFileStreamHandle()
{
using (FileStream fs = File.OpenWrite(GetTestFilePath()))
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false))
{
SafeMemoryMappedFileHandle handle = mmf.SafeMemoryMappedFileHandle;
Assert.Equal(fs.SafeFileHandle.DangerousGetHandle(), handle.DangerousGetHandle());
}
}
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[SkipOnPlatform(TestPlatforms.Browser, "mkfifo is not supported on WASM")]
public async Task OpeningMemoryMappedFileFromFileStreamThatWrapsPipeThrowsNotSupportedException(long capacity)
{
(string pipePath, NamedPipeServerStream? serverStream) = CreatePipe();
using FileStream clientStream = new (pipePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
if (serverStream is not null)
{
await serverStream.WaitForConnectionAsync();
}
Assert.Throws<NotSupportedException>(() => MemoryMappedFile.CreateFromFile(clientStream, null, capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false));
serverStream?.Dispose();
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[SkipOnPlatform(TestPlatforms.Browser, "mkfifo is not supported on WASM")]
public void OpeningMemoryMappedFileFromPipePathThrowsNotSupportedException(long capacity)
{
(string pipePath, NamedPipeServerStream? serverStream) = CreatePipe();
Assert.Throws<NotSupportedException>(() => MemoryMappedFile.CreateFromFile(pipePath, FileMode.Open, null, capacity, MemoryMappedFileAccess.ReadWrite));
serverStream?.Dispose();
}
private (string pipePath, NamedPipeServerStream? serverStream) CreatePipe()
{
if (OperatingSystem.IsWindows())
{
string pipeName = GetNamedPipeServerStreamName();
string pipePath = Path.GetFullPath($@"\\.\pipe\{pipeName}");
return (pipePath, new NamedPipeServerStream(pipeName, PipeDirection.InOut));
}
else
{
string fifoPath = GetTestFilePath();
Assert.Equal(0, mkfifo(fifoPath, 438 /* 666 in octal */ ));
return (fifoPath, null);
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;
using System.IO.Pipes;
using System.Threading.Tasks;
namespace System.IO.MemoryMappedFiles.Tests
{
/// <summary>
/// Tests for MemoryMappedFile.CreateFromFile.
/// </summary>
public class MemoryMappedFileTests_CreateFromFile : MemoryMappedFilesTestBase
{
/// <summary>
/// Tests invalid arguments to the CreateFromFile path parameter.
/// </summary>
[Fact]
public void InvalidArguments_Path()
{
// null is an invalid path
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName()));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName(), 4096));
AssertExtensions.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Read));
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile fileStream parameter.
/// </summary>
[Fact]
public void InvalidArguments_FileStream()
{
// null is an invalid stream
AssertExtensions.Throws<ArgumentNullException>("fileStream", () => MemoryMappedFile.CreateFromFile(null, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile mode parameter.
/// </summary>
[Fact]
public void InvalidArguments_Mode()
{
// FileMode out of range
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42));
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null));
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096));
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096, MemoryMappedFileAccess.ReadWrite));
// FileMode.Append never allowed
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append));
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null));
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096));
AssertExtensions.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096, MemoryMappedFileAccess.ReadWrite));
// FileMode.CreateNew/Create/OpenOrCreate can't be used with default capacity, as the file will be empty
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Create));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.OpenOrCreate));
// FileMode.Truncate can't be used with default capacity, as resulting file will be empty
using (TempFile file = new TempFile(GetTestFilePath()))
{
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Truncate));
}
}
[Fact]
public void InvalidArguments_Mode_Truncate()
{
// FileMode.Truncate never allowed
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate));
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate, null));
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate, null, 4096));
AssertExtensions.Throws<ArgumentException>("mode", null, () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Truncate, null, 4096, MemoryMappedFileAccess.ReadWrite));
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile access parameter.
/// </summary>
[Fact]
public void InvalidArguments_Access()
{
// Out of range access values with a path
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(-2)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(42)));
// Write-only access is not allowed on maps (only on views)
AssertExtensions.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write));
// Test the same things, but with a FileStream instead of a path
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// Out of range values with a stream
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(-2), HandleInheritability.None, true));
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(42), HandleInheritability.None, true));
// Write-only access is not allowed
AssertExtensions.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write, HandleInheritability.None, true));
}
}
/// <summary>
/// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used
/// to construct a map over that stream. The combinations should all be valid.
/// </summary>
[Theory]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.CopyOnWrite)]
public void FileAccessAndMapAccessCombinations_Valid(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true))
{
ValidateMemoryMappedFile(mmf, Capacity, mmfAccess);
}
}
/// <summary>
/// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used
/// to construct a map over that stream on Windows. The combinations should all be invalid, resulting in exception.
/// </summary>
[PlatformSpecific(TestPlatforms.Windows)] // On Windows, permission errors come from CreateFromFile
[Theory]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute)] // this and the next are explicitly left off of the Unix test due to differences in Unix permissions
[InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadWriteExecute)]
public void FileAccessAndMapAccessCombinations_Invalid_Windows(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess)
{
// On Windows, creating the file mapping does the permissions checks, so the exception comes from CreateFromFile.
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess))
{
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true));
}
}
/// <summary>
/// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used
/// to construct a map over that stream on Unix. The combinations should all be invalid, resulting in exception.
/// </summary>
[PlatformSpecific(TestPlatforms.AnyUnix)] // On Unix, permission errors come from CreateView*
[Theory]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.Read)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.CopyOnWrite)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadExecute)]
[InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWriteExecute)]
public void FileAccessAndMapAccessCombinations_Invalid_Unix(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess)
{
// On Unix we don't actually create the OS map until the view is created; this results in the permissions
// error being thrown from CreateView* instead of from CreateFromFile.
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true))
{
Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor());
}
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile mapName parameter.
/// </summary>
[Fact]
public void InvalidArguments_MapName()
{
using (TempFile file = new TempFile(GetTestFilePath()))
{
// Empty string is an invalid map name
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096, MemoryMappedFileAccess.Read));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096, MemoryMappedFileAccess.Read));
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, string.Empty, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true));
}
}
}
/// <summary>
/// Test to verify that map names are left unsupported on Unix.
/// </summary>
[PlatformSpecific(TestPlatforms.AnyUnix)] // Check map names are unsupported on Unix
[Theory]
[MemberData(nameof(CreateValidMapNames))]
public void MapNamesNotSupported_Unix(string mapName)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
{
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity, MemoryMappedFileAccess.ReadWrite));
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity, MemoryMappedFileAccess.ReadWrite));
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(fs, mapName, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true));
}
}
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile capacity parameter.
/// </summary>
[Fact]
public void InvalidArguments_Capacity()
{
using (TempFile file = new TempFile(GetTestFilePath()))
{
// Out of range values for capacity
Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), -1));
Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), -1, MemoryMappedFileAccess.Read));
// Positive capacity required when creating a map from an empty file
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, 0, MemoryMappedFileAccess.Read));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 0, MemoryMappedFileAccess.Read));
// With Read, the capacity can't be larger than the backing file's size.
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 1, MemoryMappedFileAccess.Read));
// Now with a FileStream...
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// The subsequent tests are only valid we if we start with an empty FileStream, which we should have.
// This also verifies the previous failed tests didn't change the length of the file.
Assert.Equal(0, fs.Length);
// Out of range values for capacity
Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(fs, null, -1, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
// Default (0) capacity with an empty file
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, null, 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
// Larger capacity than the underlying file, but read-only such that we can't expand the file
fs.SetLength(4096);
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, null, 8192, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
AssertExtensions.Throws<ArgumentException>(null, () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 8192, MemoryMappedFileAccess.Read, HandleInheritability.None, true));
// Capacity can't be less than the file size (for such cases a view can be created with the smaller size)
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateFromFile(fs, null, 1, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true));
}
// Capacity can't be less than the file size
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 1, MemoryMappedFileAccess.Read));
}
}
/// <summary>
/// Tests invalid arguments to the CreateFromFile inheritability parameter.
/// </summary>
[Theory]
[InlineData((HandleInheritability)(-1))]
[InlineData((HandleInheritability)(42))]
public void InvalidArguments_Inheritability(HandleInheritability inheritability)
{
// Out of range values for inheritability
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("inheritability", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite, inheritability, true));
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile, focusing on the Open and OpenOrCreate modes,
/// and validating the creating maps each time they're created.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath),
new FileMode[] { FileMode.Open, FileMode.OpenOrCreate },
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.ReadWrite })]
[ActiveIssue("https://github.com/dotnet/runtime/issues/51375", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)]
public void ValidArgumentCombinationsWithPath_ModesOpenOrCreate(
FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access)
{
_ = access;
// Test each of the four path-based CreateFromFile overloads
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
// Finally, re-test the last overload, this time with an empty file to start
using (TempFile file = new TempFile(GetTestFilePath()))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile, focusing on the CreateNew mode,
/// and validating the creating maps each time they're created.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath),
new FileMode[] { FileMode.CreateNew },
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite })]
[ActiveIssue("https://github.com/dotnet/runtime/issues/51375", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)]
public void ValidArgumentCombinationsWithPath_ModeCreateNew(
FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access)
{
// For FileMode.CreateNew, the file will be created new and thus be empty, so we can only use the overloads
// that take a capacity, since the default capacity doesn't work with an empty file.
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity, access))
{
ValidateMemoryMappedFile(mmf, capacity, access);
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile, focusing on the Create mode,
/// and validating the creating maps each time they're created.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidNameCapacityCombinationsWithPath),
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 })]
[ActiveIssue("https://github.com/dotnet/runtime/issues/51375", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)]
public void ValidArgumentCombinationsWithPath_ModeCreate(string mapName, long capacity)
{
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Create, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Create, mapName, capacity, MemoryMappedFileAccess.ReadWrite))
{
ValidateMemoryMappedFile(mmf, capacity, MemoryMappedFileAccess.ReadWrite);
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Create, mapName, capacity))
{
ValidateMemoryMappedFile(mmf, capacity);
}
}
/// <summary>
/// Provides input data to the ValidArgumentCombinationsWithPath tests, yielding the full matrix
/// of combinations of input values provided, except for those that are known to be unsupported
/// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders
/// listed in the MemberData attribute (e.g. actual system page size instead of -1).
/// </summary>
/// <param name="modes">The modes to yield.</param>
/// <param name="mapNames">
/// The names to yield.
/// non-null may be excluded based on platform.
/// "CreateUniqueMapName()" will be translated to an invocation of that method.
/// </param>
/// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param>
/// <param name="accesses">
/// The accesses to yield. Non-writable accesses will be skipped if the current mode doesn't support it.
/// </param>
public static IEnumerable<object[]> MemberData_ValidArgumentCombinationsWithPath(
FileMode[] modes, string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses)
{
foreach (object[] namesCaps in MemberData_ValidNameCapacityCombinationsWithPath(mapNames, capacities))
{
foreach (FileMode mode in modes)
{
foreach (MemoryMappedFileAccess access in accesses)
{
if ((mode == FileMode.Create || mode == FileMode.CreateNew || mode == FileMode.Truncate) &&
!IsWritable(access))
{
continue;
}
yield return new object[] { mode, namesCaps[0], namesCaps[1], access };
}
}
}
}
public static IEnumerable<object[]> MemberData_ValidNameCapacityCombinationsWithPath(
string[] mapNames, long[] capacities)
{
foreach (string tmpMapName in mapNames)
{
if (tmpMapName != null && !MapNamesSupported)
{
continue;
}
foreach (long tmpCapacity in capacities)
{
long capacity = tmpCapacity == -1 ? s_pageSize.Value : tmpCapacity;
string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName;
yield return new object[] { mapName, capacity, };
}
}
}
/// <summary>
/// Test various combinations of arguments to CreateFromFile that accepts a FileStream.
/// </summary>
[Theory]
[MemberData(nameof(MemberData_ValidArgumentCombinationsWithStream),
new string[] { null, "CreateUniqueMapName()" },
new long[] { 1, 256, -1 /*pagesize*/, 10000 },
new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite },
new HandleInheritability[] { HandleInheritability.None, HandleInheritability.Inheritable },
new bool[] { false, true })]
[ActiveIssue("https://github.com/dotnet/runtime/issues/51375", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)]
public void ValidArgumentCombinationsWithStream(
string mapName, long capacity, MemoryMappedFileAccess access, HandleInheritability inheritability, bool leaveOpen)
{
// Create a file of the right size, then create the map for it.
using (TempFile file = new TempFile(GetTestFilePath(), capacity))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, mapName, capacity, access, inheritability, leaveOpen))
{
ValidateMemoryMappedFile(mmf, capacity, access, inheritability);
}
// Start with an empty file and let the map grow it to the right size. This requires write access.
if (IsWritable(access))
{
using (FileStream fs = File.Create(GetTestFilePath()))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, mapName, capacity, access, inheritability, leaveOpen))
{
ValidateMemoryMappedFile(mmf, capacity, access, inheritability);
}
}
}
/// <summary>
/// Provides input data to the ValidArgumentCombinationsWithStream tests, yielding the full matrix
/// of combinations of input values provided, except for those that are known to be unsupported
/// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders
/// listed in the MemberData attribute (e.g. actual system page size instead of -1).
/// </summary>
/// <param name="mapNames">
/// The names to yield.
/// non-null may be excluded based on platform.
/// "CreateUniqueMapName()" will be translated to an invocation of that method.
/// </param>
/// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param>
/// <param name="accesses">
/// The accesses to yield. Non-writable accesses will be skipped if the current mode doesn't support it.
/// </param>
/// <param name="inheritabilities">The inheritabilities to yield.</param>
/// <param name="inheritabilities">The leaveOpen values to yield.</param>
public static IEnumerable<object[]> MemberData_ValidArgumentCombinationsWithStream(
string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses, HandleInheritability[] inheritabilities, bool[] leaveOpens)
{
foreach (string tmpMapName in mapNames)
{
if (tmpMapName != null && !MapNamesSupported)
{
continue;
}
foreach (long tmpCapacity in capacities)
{
long capacity = tmpCapacity == -1 ?
s_pageSize.Value :
tmpCapacity;
foreach (MemoryMappedFileAccess access in accesses)
{
foreach (HandleInheritability inheritability in inheritabilities)
{
foreach (bool leaveOpen in leaveOpens)
{
string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName;
yield return new object[] { mapName, capacity, access, inheritability, leaveOpen };
}
}
}
}
}
}
/// <summary>
/// Test that a map using the default capacity (0) grows to the size of the underlying file.
/// </summary>
[Fact]
public void DefaultCapacityIsFileLength()
{
const int DesiredCapacity = 8192;
const int DefaultCapacity = 0;
// With path
using (TempFile file = new TempFile(GetTestFilePath(), DesiredCapacity))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, DefaultCapacity))
{
ValidateMemoryMappedFile(mmf, DesiredCapacity);
}
// With stream
using (TempFile file = new TempFile(GetTestFilePath(), DesiredCapacity))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, DefaultCapacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
{
ValidateMemoryMappedFile(mmf, DesiredCapacity);
}
}
/// <summary>
/// Test that appropriate exceptions are thrown creating a map with a non-existent file and a mode
/// that requires the file to exist.
/// </summary>
[Fact]
public void FileDoesNotExist_OpenFileMode()
{
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath()));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, null));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, null, 4096));
Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, null, 4096, MemoryMappedFileAccess.ReadWrite));
}
/// <summary>
/// Test that appropriate exceptions are thrown creating a map with an existing file and a mode
/// that requires the file to not exist.
/// </summary>
[Fact]
public void FileAlreadyExists()
{
using (TempFile file = new TempFile(GetTestFilePath()))
{
// FileMode.CreateNew invalid when the file already exists
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew));
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName()));
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName(), 4096));
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite));
}
}
/// <summary>
/// Test exceptional behavior when trying to create a map for a read-write file that's currently in use.
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // FileShare is limited on Unix, with None == exclusive, everything else == concurrent
public void FileInUse_CreateFromFile_FailsWithExistingReadWriteFile()
{
// Already opened with a FileStream
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path));
}
}
/// <summary>
/// Test exceptional behavior when trying to create a map for a non-shared file that's currently in use.
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // FileShare is limited on Unix, with None == exclusive, everything else == concurrent
public void FileInUse_CreateFromFile_FailsWithExistingReadWriteMap()
{
// Already opened with another read-write map
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path))
{
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path));
}
}
/// <summary>
/// Test exceptional behavior when trying to create a map for a non-shared file that's currently in use.
/// </summary>
[Fact]
[SkipOnPlatform(TestPlatforms.Browser, "the emscripten implementation ignores FileShare.None")]
public void FileInUse_CreateFromFile_FailsWithExistingNoShareFile()
{
// Already opened with a FileStream
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
using (FileStream fs = File.Open(file.Path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path));
}
}
/// <summary>
/// Test to validate we can create multiple concurrent read-only maps from the same file path.
/// </summary>
[Fact]
public void FileInUse_CreateFromFile_SucceedsWithReadOnly()
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, MemoryMappedFileAccess.Read))
using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, MemoryMappedFileAccess.Read))
using (MemoryMappedViewAccessor acc1 = mmf1.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read))
using (MemoryMappedViewAccessor acc2 = mmf2.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read))
{
Assert.Equal(acc1.Capacity, acc2.Capacity);
}
}
/// <summary>
/// Test the exceptional behavior of *Execute access levels.
/// </summary>
[PlatformSpecific(TestPlatforms.Windows)] // Unix model for executable differs from Windows
[Theory]
[InlineData(MemoryMappedFileAccess.ReadExecute)]
[InlineData(MemoryMappedFileAccess.ReadWriteExecute)]
public void FileNotOpenedForExecute(MemoryMappedFileAccess access)
{
using (TempFile file = new TempFile(GetTestFilePath(), 4096))
{
// The FileStream created by the map doesn't have GENERIC_EXECUTE set
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, 4096, access));
// The FileStream opened explicitly doesn't have GENERIC_EXECUTE set
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(fs, null, 4096, access, HandleInheritability.None, true));
}
}
}
/// <summary>
/// On Unix, modifying a file that is ReadOnly will fail under normal permissions.
/// If the test is being run under the superuser, however, modification of a ReadOnly
/// file is allowed.
/// </summary>
private void WriteToReadOnlyFile(MemoryMappedFileAccess access, bool succeeds)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
{
FileAttributes original = File.GetAttributes(file.Path);
File.SetAttributes(file.Path, FileAttributes.ReadOnly);
try
{
if (succeeds)
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, access))
ValidateMemoryMappedFile(mmf, Capacity, MemoryMappedFileAccess.Read);
else
Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, access));
}
finally
{
File.SetAttributes(file.Path, original);
}
}
}
[Theory]
[InlineData(MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWrite)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/53021", TestPlatforms.Browser)]
public void WriteToReadOnlyFile_ReadWrite(MemoryMappedFileAccess access)
{
WriteToReadOnlyFile(access, access == MemoryMappedFileAccess.Read ||
PlatformDetection.IsSuperUser);
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/53021", TestPlatforms.Browser)]
public void WriteToReadOnlyFile_CopyOnWrite()
{
WriteToReadOnlyFile(MemoryMappedFileAccess.CopyOnWrite, PlatformDetection.IsSuperUser);
}
/// <summary>
/// Test to ensure that leaveOpen is appropriately respected, either leaving the FileStream open
/// or closing it on disposal.
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public void LeaveOpenRespected_Basic(bool leaveOpen)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// Handle should still be open
SafeFileHandle handle = fs.SafeFileHandle;
Assert.False(handle.IsClosed);
// Create and close the map
MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen).Dispose();
// The handle should now be open iff leaveOpen
Assert.NotEqual(leaveOpen, handle.IsClosed);
}
}
/// <summary>
/// Test to ensure that leaveOpen is appropriately respected, either leaving the FileStream open
/// or closing it on disposal.
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public void LeaveOpenRespected_OutstandingViews(bool leaveOpen)
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath()))
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
// Handle should still be open
SafeFileHandle handle = fs.SafeFileHandle;
Assert.False(handle.IsClosed);
// Create the map, create each of the views, then close the map
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen))
using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, Capacity))
using (MemoryMappedViewStream s = mmf.CreateViewStream(0, Capacity))
{
// Explicitly close the map. The handle should now be open iff leaveOpen.
mmf.Dispose();
Assert.NotEqual(leaveOpen, handle.IsClosed);
// But the views should still be usable.
ValidateMemoryMappedViewAccessor(acc, Capacity, MemoryMappedFileAccess.ReadWrite);
ValidateMemoryMappedViewStream(s, Capacity, MemoryMappedFileAccess.ReadWrite);
}
}
}
/// <summary>
/// Test to validate we can create multiple maps from the same FileStream.
/// </summary>
[Fact]
[SkipOnPlatform(TestPlatforms.Browser, "the emscripten implementation doesn't share data")]
public void MultipleMapsForTheSameFileStream()
{
const int Capacity = 4096;
using (TempFile file = new TempFile(GetTestFilePath(), Capacity))
using (FileStream fs = new FileStream(file.Path, FileMode.Open))
using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
using (MemoryMappedViewAccessor acc1 = mmf1.CreateViewAccessor())
using (MemoryMappedViewAccessor acc2 = mmf2.CreateViewAccessor())
{
// The capacity of the two maps should be equal
Assert.Equal(acc1.Capacity, acc2.Capacity);
var rand = new Random();
for (int i = 1; i <= 10; i++)
{
// Write a value to one map, then read it from the other,
// ping-ponging between the two.
int pos = rand.Next((int)acc1.Capacity - 1);
MemoryMappedViewAccessor reader = acc1, writer = acc2;
if (i % 2 == 0)
{
reader = acc2;
writer = acc1;
}
writer.Write(pos, (byte)i);
writer.Flush();
Assert.Equal(i, reader.ReadByte(pos));
}
}
}
/// <summary>
/// Test to verify that the map's size increases the underlying file size if the map's capacity is larger.
/// </summary>
[Fact]
public void FileSizeExpandsToCapacity()
{
const int InitialCapacity = 256;
using (TempFile file = new TempFile(GetTestFilePath(), InitialCapacity))
{
// Create a map with a larger capacity, and verify the file has expanded.
MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, InitialCapacity * 2).Dispose();
using (FileStream fs = File.OpenRead(file.Path))
{
Assert.Equal(InitialCapacity * 2, fs.Length);
}
// Do the same thing again but with a FileStream.
using (FileStream fs = File.Open(file.Path, FileMode.Open))
{
MemoryMappedFile.CreateFromFile(fs, null, InitialCapacity * 4, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true).Dispose();
Assert.Equal(InitialCapacity * 4, fs.Length);
}
}
}
/// <summary>
/// Test the exceptional behavior when attempting to create a map so large it's not supported.
/// </summary>
[SkipOnPlatform(TestPlatforms.OSX, "Because of the file-based backing, OS X pops up a warning dialog about being out-of-space (even though we clean up immediately)")]
[Fact]
public void TooLargeCapacity()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.CreateNew))
{
try
{
long length = long.MaxValue;
MemoryMappedFile.CreateFromFile(fs, null, length, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true).Dispose();
Assert.Equal(length, fs.Length); // if it didn't fail to create the file, the length should be what was requested.
}
catch (IOException)
{
// Expected exception for too large a capacity
}
}
}
/// <summary>
/// Test to verify map names are handled appropriately, causing a conflict when they're active but
/// reusable in a sequential manner.
/// </summary>
[PlatformSpecific(TestPlatforms.Windows)] // Tests reusability of map names on Windows
[Theory]
[MemberData(nameof(CreateValidMapNames))]
public void ReusingNames_Windows(string name)
{
const int Capacity = 4096;
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity))
{
ValidateMemoryMappedFile(mmf, Capacity);
Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity));
}
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity))
{
ValidateMemoryMappedFile(mmf, Capacity);
}
}
private void ValidateDeviceAccess(MemoryMappedFile memMap, long viewCapacity, MemoryMappedFileAccess access)
{
using (MemoryMappedViewAccessor view = memMap.CreateViewAccessor(0, viewCapacity, access))
{
if (access != MemoryMappedFileAccess.Write)
{
byte b = view.ReadByte(0);
// /dev/zero return zeroes.
Assert.Equal(0, b);
}
if (access != MemoryMappedFileAccess.Read)
{
view.Write(0, (byte)1);
}
}
}
/// <summary>
/// Test that we can map special character devices on Unix using FileStream.
/// </summary>
[ConditionalTheory]
[InlineData(MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWrite)]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void OpenCharacterDeviceAsStream(MemoryMappedFileAccess access)
{
const string device = "/dev/zero";
if (!File.Exists(device))
{
throw new SkipTestException($"'{device}' is not available.");
}
long viewCapacity = 0xFF;
try
{
using (FileStream fs = new FileStream(device, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
using (MemoryMappedFile memMap = MemoryMappedFile.CreateFromFile(fs, null, viewCapacity, access, HandleInheritability.None, false))
{
ValidateDeviceAccess(memMap, viewCapacity, access);
}
}
catch (UnauthorizedAccessException) { }
// ENODEV Operation not supported by device.
catch (IOException ex) when (ex.HResult == 19) { };
}
/// <summary>
/// Test that we can map special character devices on Unix using file name.
/// </summary>
[ConditionalTheory]
[InlineData(MemoryMappedFileAccess.Read)]
[InlineData(MemoryMappedFileAccess.ReadWrite)]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void OpenCharacterDeviceAsFile(MemoryMappedFileAccess access)
{
const string device = "/dev/zero";
if (!File.Exists(device))
{
throw new SkipTestException($"'{device}' is not available.");
}
long viewCapacity = 0xFF;
try
{
using (MemoryMappedFile memMap = MemoryMappedFile.CreateFromFile(device, FileMode.Open, null, viewCapacity, access))
{
ValidateDeviceAccess(memMap, viewCapacity, access);
}
}
catch (UnauthorizedAccessException) { }
// ENODEV Operation not supported by device.
catch (IOException ex) when (ex.HResult == 19) { };
}
/// <summary>
/// Test to verify that the MemoryMappedFile has the same underlying handle as the FileStream it's created from
/// </summary>
[PlatformSpecific(TestPlatforms.AnyUnix)]
[Fact]
public void MapHandleMatchesFileStreamHandle()
{
using (FileStream fs = File.OpenWrite(GetTestFilePath()))
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false))
{
SafeMemoryMappedFileHandle handle = mmf.SafeMemoryMappedFileHandle;
Assert.Equal(fs.SafeFileHandle.DangerousGetHandle(), handle.DangerousGetHandle());
}
}
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[SkipOnPlatform(TestPlatforms.Browser, "mkfifo is not supported on WASM")]
public async Task OpeningMemoryMappedFileFromFileStreamThatWrapsPipeThrowsNotSupportedException(long capacity)
{
(string pipePath, NamedPipeServerStream? serverStream) = CreatePipe();
using FileStream clientStream = new (pipePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
if (serverStream is not null)
{
await serverStream.WaitForConnectionAsync();
}
Assert.Throws<NotSupportedException>(() => MemoryMappedFile.CreateFromFile(clientStream, null, capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false));
serverStream?.Dispose();
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[SkipOnPlatform(TestPlatforms.Browser, "mkfifo is not supported on WASM")]
public void OpeningMemoryMappedFileFromPipePathThrowsNotSupportedException(long capacity)
{
(string pipePath, NamedPipeServerStream? serverStream) = CreatePipe();
Assert.Throws<NotSupportedException>(() => MemoryMappedFile.CreateFromFile(pipePath, FileMode.Open, null, capacity, MemoryMappedFileAccess.ReadWrite));
serverStream?.Dispose();
}
private (string pipePath, NamedPipeServerStream? serverStream) CreatePipe()
{
if (OperatingSystem.IsWindows())
{
string pipeName = GetNamedPipeServerStreamName();
string pipePath = Path.GetFullPath($@"\\.\pipe\{pipeName}");
return (pipePath, new NamedPipeServerStream(pipeName, PipeDirection.InOut));
}
else
{
string fifoPath = GetTestFilePath();
Assert.Equal(0, mkfifo(fifoPath, 438 /* 666 in octal */ ));
return (fifoPath, null);
}
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/Generics/Arrays/ConstructedTypes/Jagged/class03.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="class03.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="class03.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.Serialization;
namespace System.Runtime.CompilerServices
{
/// <summary>
/// Exception used to wrap all non-CLS compliant exceptions.
/// </summary>
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed class RuntimeWrappedException : Exception
{
private object _wrappedException; // EE expects this name
// Not an api but has to be public as System.Linq.Expression invokes this through Reflection when an expression
// throws an object that doesn't derive from Exception.
public RuntimeWrappedException(object thrownObject)
: base(SR.RuntimeWrappedException)
{
HResult = HResults.COR_E_RUNTIMEWRAPPED;
_wrappedException = thrownObject;
}
private RuntimeWrappedException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
_wrappedException = info.GetValue("WrappedException", typeof(object))!;
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("WrappedException", _wrappedException, typeof(object));
}
public object WrappedException => _wrappedException;
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.Serialization;
namespace System.Runtime.CompilerServices
{
/// <summary>
/// Exception used to wrap all non-CLS compliant exceptions.
/// </summary>
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed class RuntimeWrappedException : Exception
{
private object _wrappedException; // EE expects this name
// Not an api but has to be public as System.Linq.Expression invokes this through Reflection when an expression
// throws an object that doesn't derive from Exception.
public RuntimeWrappedException(object thrownObject)
: base(SR.RuntimeWrappedException)
{
HResult = HResults.COR_E_RUNTIMEWRAPPED;
_wrappedException = thrownObject;
}
private RuntimeWrappedException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
_wrappedException = info.GetValue("WrappedException", typeof(object))!;
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("WrappedException", _wrappedException, typeof(object));
}
public object WrappedException => _wrappedException;
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.IO.Pipelines/tests/PipeWriterTests.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Pipelines.Tests
{
public class PipeWriterTests : PipeTest
{
public PipeWriterTests() : base(0, 0)
{
}
private byte[] Read()
{
Pipe.Writer.FlushAsync().GetAwaiter().GetResult();
ReadResult readResult = Pipe.Reader.ReadAsync().GetAwaiter().GetResult();
byte[] data = readResult.Buffer.ToArray();
Pipe.Reader.AdvanceTo(readResult.Buffer.End);
return data;
}
[Theory]
[InlineData(3, -1, 0)]
[InlineData(3, 0, -1)]
[InlineData(3, 0, 4)]
[InlineData(3, 4, 0)]
[InlineData(3, -1, -1)]
[InlineData(3, 4, 4)]
public void ThrowsForInvalidParameters(int arrayLength, int offset, int length)
{
PipeWriter writer = Pipe.Writer;
var array = new byte[arrayLength];
for (var i = 0; i < array.Length; i++)
{
array[i] = (byte)(i + 1);
}
writer.Write(new Span<byte>(array, 0, 0));
writer.Write(new Span<byte>(array, array.Length, 0));
try
{
writer.Write(new Span<byte>(array, offset, length));
Assert.True(false);
}
catch (Exception ex)
{
Assert.True(ex is ArgumentOutOfRangeException);
}
writer.Write(new Span<byte>(array, 0, array.Length));
Assert.Equal(array, Read());
}
[Theory]
[InlineData(0, 3)]
[InlineData(1, 1)]
[InlineData(1, 2)]
[InlineData(2, 1)]
public void CanWriteWithOffsetAndLength(int offset, int length)
{
PipeWriter writer = Pipe.Writer;
var array = new byte[] { 1, 2, 3 };
writer.Write(new Span<byte>(array, offset, length));
Assert.Equal(array.Skip(offset).Take(length).ToArray(), Read());
}
[Fact]
public void CanWriteIntoHeadlessBuffer()
{
PipeWriter writer = Pipe.Writer;
writer.Write(new byte[] { 1, 2, 3 });
Assert.Equal(new byte[] { 1, 2, 3 }, Read());
}
[Fact]
public void CanWriteMultipleTimes()
{
PipeWriter writer = Pipe.Writer;
writer.Write(new byte[] { 1 });
writer.Write(new byte[] { 2 });
writer.Write(new byte[] { 3 });
Assert.Equal(new byte[] { 1, 2, 3 }, Read());
}
[Fact]
public async Task CanWriteOverTheBlockLength()
{
Memory<byte> memory = Pipe.Writer.GetMemory();
PipeWriter writer = Pipe.Writer;
IEnumerable<byte> source = Enumerable.Range(0, memory.Length).Select(i => (byte)i);
byte[] expectedBytes = source.Concat(source).Concat(source).ToArray();
await writer.WriteAsync(expectedBytes);
Assert.Equal(expectedBytes, Read());
}
[Fact]
public void EnsureAllocatesSpan()
{
PipeWriter writer = Pipe.Writer;
var span = writer.GetSpan(10);
Assert.True(span.Length >= 10);
// 0 byte Flush would not complete the reader so we complete.
Pipe.Writer.Complete();
Assert.Equal(new byte[] { }, Read());
}
[Fact]
public void SlicesSpanAndAdvancesAfterWrite()
{
int initialLength = Pipe.Writer.GetSpan(3).Length;
PipeWriter writer = Pipe.Writer;
writer.Write(new byte[] { 1, 2, 3 });
Span<byte> span = Pipe.Writer.GetSpan();
Assert.Equal(initialLength - 3, span.Length);
Assert.Equal(new byte[] { 1, 2, 3 }, Read());
}
[Theory]
[InlineData(5)]
[InlineData(50)]
[InlineData(500)]
[InlineData(5000)]
[InlineData(50000)]
public async Task WriteLargeDataBinary(int length)
{
var data = new byte[length];
new Random(length).NextBytes(data);
PipeWriter output = Pipe.Writer;
await output.WriteAsync(data);
ReadResult result = await Pipe.Reader.ReadAsync();
ReadOnlySequence<byte> input = result.Buffer;
Assert.Equal(data, input.ToArray());
Pipe.Reader.AdvanceTo(input.End);
}
[Fact]
public async Task CanWriteNothingToBuffer()
{
PipeWriter buffer = Pipe.Writer;
buffer.GetMemory(0);
buffer.Advance(0); // doing nothing, the hard way
await buffer.FlushAsync();
}
[Fact]
public void EmptyWriteDoesNotThrow()
{
Pipe.Writer.Write(new byte[0]);
}
[Fact]
public void ThrowsOnAdvanceOverMemorySize()
{
Memory<byte> buffer = Pipe.Writer.GetMemory(1);
Assert.Throws<ArgumentOutOfRangeException>(() => Pipe.Writer.Advance(buffer.Length + 1));
}
[Fact]
public void ThrowsOnAdvanceWithNoMemory()
{
PipeWriter buffer = Pipe.Writer;
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.Advance(1));
}
[Fact]
public async Task WritesUsingGetSpanWorks()
{
var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz");
var pipe = new Pipe(new PipeOptions(pool: new HeapBufferPool(), minimumSegmentSize: 1));
PipeWriter writer = pipe.Writer;
for (int i = 0; i < bytes.Length; i++)
{
writer.GetSpan()[0] = bytes[i];
writer.Advance(1);
}
await writer.FlushAsync();
writer.Complete();
Assert.Equal(0, writer.UnflushedBytes);
ReadResult readResult = await pipe.Reader.ReadAsync();
Assert.Equal(bytes, readResult.Buffer.ToArray());
pipe.Reader.AdvanceTo(readResult.Buffer.End);
pipe.Reader.Complete();
}
[Fact]
public async Task WritesUsingGetMemoryWorks()
{
var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz");
var pipe = new Pipe(new PipeOptions(pool: new HeapBufferPool(), minimumSegmentSize: 1));
PipeWriter writer = pipe.Writer;
for (int i = 0; i < bytes.Length; i++)
{
writer.GetMemory().Span[0] = bytes[i];
writer.Advance(1);
}
await writer.FlushAsync();
writer.Complete();
Assert.Equal(0, writer.UnflushedBytes);
ReadResult readResult = await pipe.Reader.ReadAsync();
Assert.Equal(bytes, readResult.Buffer.ToArray());
pipe.Reader.AdvanceTo(readResult.Buffer.End);
pipe.Reader.Complete();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public async Task CompleteWithLargeWriteThrows()
{
var completeDelay = TimeSpan.FromMilliseconds(10);
var testTimeout = TimeSpan.FromMilliseconds(10000);
var pipe = new Pipe();
pipe.Reader.Complete();
var task = Task.Run(async () =>
{
await Task.Delay(completeDelay);
pipe.Writer.Complete();
});
// Complete while writing
await Assert.ThrowsAsync<InvalidOperationException>(async () =>
{
var testStartTime = DateTime.UtcNow;
var buffer = new byte[10000000];
ulong i = 0;
while (true)
{
await pipe.Writer.WriteAsync(buffer);
// abort test if we're executing for more than the testTimeout (check every 10000th iteration)
if (i++ % 10000 == 0 && DateTime.UtcNow - testStartTime > testTimeout)
break;
}
});
}
[Fact]
public async Task WriteAsyncWithACompletedReaderNoops()
{
var pool = new DisposeTrackingBufferPool();
var pipe = new Pipe(new PipeOptions(pool));
pipe.Reader.Complete();
byte[] writeBuffer = new byte[100];
for (var i = 0; i < 10000; i++)
{
await pipe.Writer.WriteAsync(writeBuffer);
}
Assert.Equal(0, pool.CurrentlyRentedBlocks);
}
[Fact]
public async Task GetMemoryFlushWithACompletedReaderNoops()
{
var pool = new DisposeTrackingBufferPool();
var pipe = new Pipe(new PipeOptions(pool));
pipe.Reader.Complete();
for (var i = 0; i < 10000; i++)
{
var mem = pipe.Writer.GetMemory();
pipe.Writer.Advance(mem.Length);
await pipe.Writer.FlushAsync(default);
}
Assert.Equal(1, pool.CurrentlyRentedBlocks);
pipe.Writer.Complete();
Assert.Equal(0, pool.CurrentlyRentedBlocks);
Assert.Equal(0, Pipe.Writer.UnflushedBytes);
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Pipelines.Tests
{
public class PipeWriterTests : PipeTest
{
public PipeWriterTests() : base(0, 0)
{
}
private byte[] Read()
{
Pipe.Writer.FlushAsync().GetAwaiter().GetResult();
ReadResult readResult = Pipe.Reader.ReadAsync().GetAwaiter().GetResult();
byte[] data = readResult.Buffer.ToArray();
Pipe.Reader.AdvanceTo(readResult.Buffer.End);
return data;
}
[Theory]
[InlineData(3, -1, 0)]
[InlineData(3, 0, -1)]
[InlineData(3, 0, 4)]
[InlineData(3, 4, 0)]
[InlineData(3, -1, -1)]
[InlineData(3, 4, 4)]
public void ThrowsForInvalidParameters(int arrayLength, int offset, int length)
{
PipeWriter writer = Pipe.Writer;
var array = new byte[arrayLength];
for (var i = 0; i < array.Length; i++)
{
array[i] = (byte)(i + 1);
}
writer.Write(new Span<byte>(array, 0, 0));
writer.Write(new Span<byte>(array, array.Length, 0));
try
{
writer.Write(new Span<byte>(array, offset, length));
Assert.True(false);
}
catch (Exception ex)
{
Assert.True(ex is ArgumentOutOfRangeException);
}
writer.Write(new Span<byte>(array, 0, array.Length));
Assert.Equal(array, Read());
}
[Theory]
[InlineData(0, 3)]
[InlineData(1, 1)]
[InlineData(1, 2)]
[InlineData(2, 1)]
public void CanWriteWithOffsetAndLength(int offset, int length)
{
PipeWriter writer = Pipe.Writer;
var array = new byte[] { 1, 2, 3 };
writer.Write(new Span<byte>(array, offset, length));
Assert.Equal(array.Skip(offset).Take(length).ToArray(), Read());
}
[Fact]
public void CanWriteIntoHeadlessBuffer()
{
PipeWriter writer = Pipe.Writer;
writer.Write(new byte[] { 1, 2, 3 });
Assert.Equal(new byte[] { 1, 2, 3 }, Read());
}
[Fact]
public void CanWriteMultipleTimes()
{
PipeWriter writer = Pipe.Writer;
writer.Write(new byte[] { 1 });
writer.Write(new byte[] { 2 });
writer.Write(new byte[] { 3 });
Assert.Equal(new byte[] { 1, 2, 3 }, Read());
}
[Fact]
public async Task CanWriteOverTheBlockLength()
{
Memory<byte> memory = Pipe.Writer.GetMemory();
PipeWriter writer = Pipe.Writer;
IEnumerable<byte> source = Enumerable.Range(0, memory.Length).Select(i => (byte)i);
byte[] expectedBytes = source.Concat(source).Concat(source).ToArray();
await writer.WriteAsync(expectedBytes);
Assert.Equal(expectedBytes, Read());
}
[Fact]
public void EnsureAllocatesSpan()
{
PipeWriter writer = Pipe.Writer;
var span = writer.GetSpan(10);
Assert.True(span.Length >= 10);
// 0 byte Flush would not complete the reader so we complete.
Pipe.Writer.Complete();
Assert.Equal(new byte[] { }, Read());
}
[Fact]
public void SlicesSpanAndAdvancesAfterWrite()
{
int initialLength = Pipe.Writer.GetSpan(3).Length;
PipeWriter writer = Pipe.Writer;
writer.Write(new byte[] { 1, 2, 3 });
Span<byte> span = Pipe.Writer.GetSpan();
Assert.Equal(initialLength - 3, span.Length);
Assert.Equal(new byte[] { 1, 2, 3 }, Read());
}
[Theory]
[InlineData(5)]
[InlineData(50)]
[InlineData(500)]
[InlineData(5000)]
[InlineData(50000)]
public async Task WriteLargeDataBinary(int length)
{
var data = new byte[length];
new Random(length).NextBytes(data);
PipeWriter output = Pipe.Writer;
await output.WriteAsync(data);
ReadResult result = await Pipe.Reader.ReadAsync();
ReadOnlySequence<byte> input = result.Buffer;
Assert.Equal(data, input.ToArray());
Pipe.Reader.AdvanceTo(input.End);
}
[Fact]
public async Task CanWriteNothingToBuffer()
{
PipeWriter buffer = Pipe.Writer;
buffer.GetMemory(0);
buffer.Advance(0); // doing nothing, the hard way
await buffer.FlushAsync();
}
[Fact]
public void EmptyWriteDoesNotThrow()
{
Pipe.Writer.Write(new byte[0]);
}
[Fact]
public void ThrowsOnAdvanceOverMemorySize()
{
Memory<byte> buffer = Pipe.Writer.GetMemory(1);
Assert.Throws<ArgumentOutOfRangeException>(() => Pipe.Writer.Advance(buffer.Length + 1));
}
[Fact]
public void ThrowsOnAdvanceWithNoMemory()
{
PipeWriter buffer = Pipe.Writer;
Assert.Throws<ArgumentOutOfRangeException>(() => buffer.Advance(1));
}
[Fact]
public async Task WritesUsingGetSpanWorks()
{
var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz");
var pipe = new Pipe(new PipeOptions(pool: new HeapBufferPool(), minimumSegmentSize: 1));
PipeWriter writer = pipe.Writer;
for (int i = 0; i < bytes.Length; i++)
{
writer.GetSpan()[0] = bytes[i];
writer.Advance(1);
}
await writer.FlushAsync();
writer.Complete();
Assert.Equal(0, writer.UnflushedBytes);
ReadResult readResult = await pipe.Reader.ReadAsync();
Assert.Equal(bytes, readResult.Buffer.ToArray());
pipe.Reader.AdvanceTo(readResult.Buffer.End);
pipe.Reader.Complete();
}
[Fact]
public async Task WritesUsingGetMemoryWorks()
{
var bytes = Encoding.ASCII.GetBytes("abcdefghijklmnopqrstuvwzyz");
var pipe = new Pipe(new PipeOptions(pool: new HeapBufferPool(), minimumSegmentSize: 1));
PipeWriter writer = pipe.Writer;
for (int i = 0; i < bytes.Length; i++)
{
writer.GetMemory().Span[0] = bytes[i];
writer.Advance(1);
}
await writer.FlushAsync();
writer.Complete();
Assert.Equal(0, writer.UnflushedBytes);
ReadResult readResult = await pipe.Reader.ReadAsync();
Assert.Equal(bytes, readResult.Buffer.ToArray());
pipe.Reader.AdvanceTo(readResult.Buffer.End);
pipe.Reader.Complete();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public async Task CompleteWithLargeWriteThrows()
{
var completeDelay = TimeSpan.FromMilliseconds(10);
var testTimeout = TimeSpan.FromMilliseconds(10000);
var pipe = new Pipe();
pipe.Reader.Complete();
var task = Task.Run(async () =>
{
await Task.Delay(completeDelay);
pipe.Writer.Complete();
});
// Complete while writing
await Assert.ThrowsAsync<InvalidOperationException>(async () =>
{
var testStartTime = DateTime.UtcNow;
var buffer = new byte[10000000];
ulong i = 0;
while (true)
{
await pipe.Writer.WriteAsync(buffer);
// abort test if we're executing for more than the testTimeout (check every 10000th iteration)
if (i++ % 10000 == 0 && DateTime.UtcNow - testStartTime > testTimeout)
break;
}
});
}
[Fact]
public async Task WriteAsyncWithACompletedReaderNoops()
{
var pool = new DisposeTrackingBufferPool();
var pipe = new Pipe(new PipeOptions(pool));
pipe.Reader.Complete();
byte[] writeBuffer = new byte[100];
for (var i = 0; i < 10000; i++)
{
await pipe.Writer.WriteAsync(writeBuffer);
}
Assert.Equal(0, pool.CurrentlyRentedBlocks);
}
[Fact]
public async Task GetMemoryFlushWithACompletedReaderNoops()
{
var pool = new DisposeTrackingBufferPool();
var pipe = new Pipe(new PipeOptions(pool));
pipe.Reader.Complete();
for (var i = 0; i < 10000; i++)
{
var mem = pipe.Writer.GetMemory();
pipe.Writer.Advance(mem.Length);
await pipe.Writer.FlushAsync(default);
}
Assert.Equal(1, pool.CurrentlyRentedBlocks);
pipe.Writer.Complete();
Assert.Equal(0, pool.CurrentlyRentedBlocks);
Assert.Equal(0, Pipe.Writer.UnflushedBytes);
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.CodeDom/tests/System/CodeDom/CodeRemoveEventStatementTests.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.CodeDom.Tests
{
public class CodeRemoveEventStatementTests : CodeStatementTestBase<CodeRemoveEventStatement>
{
[Fact]
public void Ctor_Default()
{
var removeEvent = new CodeRemoveEventStatement();
Assert.Empty(removeEvent.Event.EventName);
Assert.Null(removeEvent.Event.TargetObject);
Assert.Null(removeEvent.Listener);
}
public static IEnumerable<object[]> Ctor_CodeExpression_String_CodeExpression_TestData()
{
yield return new object[] { null, null, null };
yield return new object[] { new CodePrimitiveExpression("Value1"), "EventName", new CodePrimitiveExpression("Value2") };
}
[Theory]
[MemberData(nameof(Ctor_CodeExpression_String_CodeExpression_TestData))]
public void Ctor_CodeExpression_String_CodeExpression(CodeExpression targetObject, string eventName, CodeExpression listener)
{
var removeEvent = new CodeRemoveEventStatement(targetObject, eventName, listener);
Assert.Equal(targetObject, removeEvent.Event.TargetObject);
Assert.Equal(eventName ?? string.Empty, removeEvent.Event.EventName);
Assert.Equal(listener, removeEvent.Listener);
}
public static IEnumerable<object[]> CodeEventReferenceExpression_CodeExpression_TestData()
{
yield return new object[] { null, null };
yield return new object[] { new CodeEventReferenceExpression(null, null), null };
yield return new object[] { new CodeEventReferenceExpression(new CodePrimitiveExpression("Value1"), "EventName"), new CodePrimitiveExpression("Value2") };
}
[Theory]
[MemberData(nameof(CodeEventReferenceExpression_CodeExpression_TestData))]
public void Ctor_CodeEventReferenceExpression_CodeExpression(CodeEventReferenceExpression eventExpresion, CodeExpression listener)
{
var removeEvent = new CodeRemoveEventStatement(eventExpresion, listener);
Assert.Equal((eventExpresion ?? new CodeEventReferenceExpression()).TargetObject, removeEvent.Event.TargetObject);
Assert.Equal((eventExpresion ?? new CodeEventReferenceExpression()).EventName, removeEvent.Event.EventName);
Assert.Equal(listener, removeEvent.Listener);
}
[Theory]
[MemberData(nameof(CodeEventReferenceExpression_CodeExpression_TestData))]
public void Event_Set_Get_ReturnsExpected(CodeEventReferenceExpression value, CodeExpression listener)
{
_ = listener;
var removeEvent = new CodeRemoveEventStatement();
removeEvent.Event = value;
Assert.Equal((value ?? new CodeEventReferenceExpression()).TargetObject, removeEvent.Event.TargetObject);
Assert.Equal((value ?? new CodeEventReferenceExpression()).EventName, removeEvent.Event.EventName);
}
[Theory]
[MemberData(nameof(CodeExpression_TestData))]
public void Listener_Set_Get_ReturnsExpected(CodeExpression value)
{
var removeEvent = new CodeRemoveEventStatement();
removeEvent.Listener = value;
Assert.Equal(value, removeEvent.Listener);
}
}
}
|
// 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.CodeDom.Tests
{
public class CodeRemoveEventStatementTests : CodeStatementTestBase<CodeRemoveEventStatement>
{
[Fact]
public void Ctor_Default()
{
var removeEvent = new CodeRemoveEventStatement();
Assert.Empty(removeEvent.Event.EventName);
Assert.Null(removeEvent.Event.TargetObject);
Assert.Null(removeEvent.Listener);
}
public static IEnumerable<object[]> Ctor_CodeExpression_String_CodeExpression_TestData()
{
yield return new object[] { null, null, null };
yield return new object[] { new CodePrimitiveExpression("Value1"), "EventName", new CodePrimitiveExpression("Value2") };
}
[Theory]
[MemberData(nameof(Ctor_CodeExpression_String_CodeExpression_TestData))]
public void Ctor_CodeExpression_String_CodeExpression(CodeExpression targetObject, string eventName, CodeExpression listener)
{
var removeEvent = new CodeRemoveEventStatement(targetObject, eventName, listener);
Assert.Equal(targetObject, removeEvent.Event.TargetObject);
Assert.Equal(eventName ?? string.Empty, removeEvent.Event.EventName);
Assert.Equal(listener, removeEvent.Listener);
}
public static IEnumerable<object[]> CodeEventReferenceExpression_CodeExpression_TestData()
{
yield return new object[] { null, null };
yield return new object[] { new CodeEventReferenceExpression(null, null), null };
yield return new object[] { new CodeEventReferenceExpression(new CodePrimitiveExpression("Value1"), "EventName"), new CodePrimitiveExpression("Value2") };
}
[Theory]
[MemberData(nameof(CodeEventReferenceExpression_CodeExpression_TestData))]
public void Ctor_CodeEventReferenceExpression_CodeExpression(CodeEventReferenceExpression eventExpresion, CodeExpression listener)
{
var removeEvent = new CodeRemoveEventStatement(eventExpresion, listener);
Assert.Equal((eventExpresion ?? new CodeEventReferenceExpression()).TargetObject, removeEvent.Event.TargetObject);
Assert.Equal((eventExpresion ?? new CodeEventReferenceExpression()).EventName, removeEvent.Event.EventName);
Assert.Equal(listener, removeEvent.Listener);
}
[Theory]
[MemberData(nameof(CodeEventReferenceExpression_CodeExpression_TestData))]
public void Event_Set_Get_ReturnsExpected(CodeEventReferenceExpression value, CodeExpression listener)
{
_ = listener;
var removeEvent = new CodeRemoveEventStatement();
removeEvent.Event = value;
Assert.Equal((value ?? new CodeEventReferenceExpression()).TargetObject, removeEvent.Event.TargetObject);
Assert.Equal((value ?? new CodeEventReferenceExpression()).EventName, removeEvent.Event.EventName);
}
[Theory]
[MemberData(nameof(CodeExpression_TestData))]
public void Listener_Set_Get_ReturnsExpected(CodeExpression value)
{
var removeEvent = new CodeRemoveEventStatement();
removeEvent.Listener = value;
Assert.Equal(value, removeEvent.Listener);
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.notnetcoreapp.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;
using Microsoft.Extensions.Hosting.Internal;
namespace Microsoft.Extensions.Hosting
{
public partial class HostBuilder
{
private static void AddLifetime(IServiceCollection services)
{
services.AddSingleton<IHostLifetime, ConsoleLifetime>();
}
}
}
|
// 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;
using Microsoft.Extensions.Hosting.Internal;
namespace Microsoft.Extensions.Hosting
{
public partial class HostBuilder
{
private static void AddLifetime(IServiceCollection services)
{
services.AddSingleton<IHostLifetime, ConsoleLifetime>();
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/coreclr/pal/src/libunwind/src/hppa/Gget_proc_info.c
|
/* libunwind - a platform-independent unwind library
Copyright (C) 2004 Hewlett-Packard Co
Contributed by David Mosberger-Tang <[email protected]>
This file is part of libunwind.
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. */
#include "unwind_i.h"
int
unw_get_proc_info (unw_cursor_t *cursor, unw_proc_info_t *pi)
{
struct cursor *c = (struct cursor *) cursor;
if (dwarf_make_proc_info (&c->dwarf) < 0)
{
/* On hppa, some key routines such as _start() and _dl_start()
are missing DWARF unwind info. We don't want to fail in that
case, because those frames are uninteresting and just mark
the end of the frame-chain anyhow. */
memset (pi, 0, sizeof (*pi));
pi->start_ip = c->dwarf.ip;
pi->end_ip = c->dwarf.ip + 4;
return 0;
}
*pi = c->dwarf.pi;
return 0;
}
|
/* libunwind - a platform-independent unwind library
Copyright (C) 2004 Hewlett-Packard Co
Contributed by David Mosberger-Tang <[email protected]>
This file is part of libunwind.
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. */
#include "unwind_i.h"
int
unw_get_proc_info (unw_cursor_t *cursor, unw_proc_info_t *pi)
{
struct cursor *c = (struct cursor *) cursor;
if (dwarf_make_proc_info (&c->dwarf) < 0)
{
/* On hppa, some key routines such as _start() and _dl_start()
are missing DWARF unwind info. We don't want to fail in that
case, because those frames are uninteresting and just mark
the end of the frame-chain anyhow. */
memset (pi, 0, sizeof (*pi));
pi->start_ip = c->dwarf.ip;
pi->end_ip = c->dwarf.ip + 4;
return 0;
}
*pi = c->dwarf.pi;
return 0;
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/coreclr/pal/src/libunwind/src/unwind/RaiseException.c
|
/* libunwind - a platform-independent unwind library
Copyright (C) 2003-2004 Hewlett-Packard Co
Contributed by David Mosberger-Tang <[email protected]>
This file is part of libunwind.
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. */
#include "unwind-internal.h"
_Unwind_Reason_Code
_Unwind_RaiseException (struct _Unwind_Exception *exception_object)
{
uint64_t exception_class = exception_object->exception_class;
_Unwind_Personality_Fn personality;
struct _Unwind_Context context;
_Unwind_Reason_Code reason;
unw_proc_info_t pi;
unw_context_t uc;
unw_word_t ip;
int ret;
Debug (1, "(exception_object=%p)\n", exception_object);
if (_Unwind_InitContext (&context, &uc) < 0)
return _URC_FATAL_PHASE1_ERROR;
/* Phase 1 (search phase) */
while (1)
{
if ((ret = unw_step (&context.cursor)) <= 0)
{
if (ret == 0)
{
Debug (1, "no handler found\n");
return _URC_END_OF_STACK;
}
else
return _URC_FATAL_PHASE1_ERROR;
}
if (unw_get_proc_info (&context.cursor, &pi) < 0)
return _URC_FATAL_PHASE1_ERROR;
personality = (_Unwind_Personality_Fn) (uintptr_t) pi.handler;
if (personality)
{
reason = (*personality) (_U_VERSION, _UA_SEARCH_PHASE,
exception_class, exception_object,
&context);
if (reason != _URC_CONTINUE_UNWIND)
{
if (reason == _URC_HANDLER_FOUND)
break;
else
{
Debug (1, "personality returned %d\n", reason);
return _URC_FATAL_PHASE1_ERROR;
}
}
}
}
/* Exceptions are associated with IP-ranges. If a given exception
is handled at a particular IP, it will _always_ be handled at
that IP. If this weren't true, we'd have to track the tuple
(IP,SP,BSP) to uniquely identify the stack frame that's handling
the exception. */
if (unw_get_reg (&context.cursor, UNW_REG_IP, &ip) < 0)
return _URC_FATAL_PHASE1_ERROR;
exception_object->private_1 = 0; /* clear "stop" pointer */
exception_object->private_2 = ip; /* save frame marker */
Debug (1, "found handler for IP=%lx; entering cleanup phase\n", (long) ip);
/* Reset the cursor to the first frame: */
if (unw_init_local (&context.cursor, &uc) < 0)
return _URC_FATAL_PHASE1_ERROR;
return _Unwind_Phase2 (exception_object, &context);
}
_Unwind_Reason_Code
__libunwind_Unwind_RaiseException (struct _Unwind_Exception *)
ALIAS (_Unwind_RaiseException);
|
/* libunwind - a platform-independent unwind library
Copyright (C) 2003-2004 Hewlett-Packard Co
Contributed by David Mosberger-Tang <[email protected]>
This file is part of libunwind.
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. */
#include "unwind-internal.h"
_Unwind_Reason_Code
_Unwind_RaiseException (struct _Unwind_Exception *exception_object)
{
uint64_t exception_class = exception_object->exception_class;
_Unwind_Personality_Fn personality;
struct _Unwind_Context context;
_Unwind_Reason_Code reason;
unw_proc_info_t pi;
unw_context_t uc;
unw_word_t ip;
int ret;
Debug (1, "(exception_object=%p)\n", exception_object);
if (_Unwind_InitContext (&context, &uc) < 0)
return _URC_FATAL_PHASE1_ERROR;
/* Phase 1 (search phase) */
while (1)
{
if ((ret = unw_step (&context.cursor)) <= 0)
{
if (ret == 0)
{
Debug (1, "no handler found\n");
return _URC_END_OF_STACK;
}
else
return _URC_FATAL_PHASE1_ERROR;
}
if (unw_get_proc_info (&context.cursor, &pi) < 0)
return _URC_FATAL_PHASE1_ERROR;
personality = (_Unwind_Personality_Fn) (uintptr_t) pi.handler;
if (personality)
{
reason = (*personality) (_U_VERSION, _UA_SEARCH_PHASE,
exception_class, exception_object,
&context);
if (reason != _URC_CONTINUE_UNWIND)
{
if (reason == _URC_HANDLER_FOUND)
break;
else
{
Debug (1, "personality returned %d\n", reason);
return _URC_FATAL_PHASE1_ERROR;
}
}
}
}
/* Exceptions are associated with IP-ranges. If a given exception
is handled at a particular IP, it will _always_ be handled at
that IP. If this weren't true, we'd have to track the tuple
(IP,SP,BSP) to uniquely identify the stack frame that's handling
the exception. */
if (unw_get_reg (&context.cursor, UNW_REG_IP, &ip) < 0)
return _URC_FATAL_PHASE1_ERROR;
exception_object->private_1 = 0; /* clear "stop" pointer */
exception_object->private_2 = ip; /* save frame marker */
Debug (1, "found handler for IP=%lx; entering cleanup phase\n", (long) ip);
/* Reset the cursor to the first frame: */
if (unw_init_local (&context.cursor, &uc) < 0)
return _URC_FATAL_PHASE1_ERROR;
return _Unwind_Phase2 (exception_object, &context);
}
_Unwind_Reason_Code
__libunwind_Unwind_RaiseException (struct _Unwind_Exception *)
ALIAS (_Unwind_RaiseException);
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ManagedBinaryEmitter.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.Metadata;
using System.Collections.Immutable;
using System.Reflection.PortableExecutable;
using System.IO;
using System.Diagnostics;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using ILCompiler.DependencyAnalysis;
namespace ILCompiler
{
public class ManagedBinaryEmitter
{
public class EmittedTypeDefinition
{
private readonly ManagedBinaryEmitter _managedEmitter;
private List<EmittedMethodDefinition> _methods = new List<EmittedMethodDefinition>();
public string Name { get; private set; }
public bool IsValueType { get; private set; }
public IReadOnlyList<EmittedMethodDefinition> Methods => _methods;
internal EmittedTypeDefinition(string name, bool isValueType, ManagedBinaryEmitter managedEmitter)
{
Name = name;
IsValueType = isValueType;
_managedEmitter = managedEmitter;
}
public EmittedMethodDefinition EmitMethodDefinition(string name, MethodSignature signature)
{
var newMethodDef = new EmittedMethodDefinition(name, signature, _managedEmitter);
_methods.Add(newMethodDef);
return newMethodDef;
}
}
public class EmittedMethodDefinition
{
private readonly ManagedBinaryEmitter _managedEmitter;
public string Name { get; private set; }
public MethodSignature Signature { get; private set; }
public InstructionEncoder Code { get; private set; }
internal EmittedMethodDefinition(string name, MethodSignature signature, ManagedBinaryEmitter managedEmitter)
{
Name = name;
Signature = signature;
_managedEmitter = managedEmitter;
Code = new InstructionEncoder(new BlobBuilder());
}
}
private readonly TypeSystemContext _typeSystemContext;
private MetadataBuilder _metadataBuilder;
private MethodBodyStreamEncoder _methodBodyStream;
private List<EmittedTypeDefinition> _emittedTypes;
protected MetadataBuilder Builder => _metadataBuilder;
public ManagedBinaryEmitter(TypeSystemContext typeSystemContext, string assemblyName)
{
_typeSystemContext = typeSystemContext;
_metadataBuilder = new MetadataBuilder();
_methodBodyStream = new MethodBodyStreamEncoder(new BlobBuilder());
_emittedTypes = new List<EmittedTypeDefinition>();
_metadataBuilder.AddAssembly(
_metadataBuilder.GetOrAddString(assemblyName),
new Version(0, 0, 0, 0),
culture: default(StringHandle),
publicKey: default(BlobHandle),
flags: default(AssemblyFlags),
hashAlgorithm: AssemblyHashAlgorithm.None);
_metadataBuilder.AddModule(
0,
_metadataBuilder.GetOrAddString(assemblyName),
default(GuidHandle), default(GuidHandle), default(GuidHandle));
// Module type
_metadataBuilder.AddTypeDefinition(
default(TypeAttributes),
default(StringHandle),
_metadataBuilder.GetOrAddString("<Module>"),
baseType: default(EntityHandle),
fieldList: MetadataTokens.FieldDefinitionHandle(1),
methodList: MetadataTokens.MethodDefinitionHandle(1));
_signatureEmitter = new EcmaSignatureEncoder<EntityProviderForEcmaSignature>(new EntityProviderForEcmaSignature(this));
}
public EmittedTypeDefinition EmitTypeDefinition(string typeName, bool isValueType)
{
EmittedTypeDefinition newTypeDef = new EmittedTypeDefinition(typeName, isValueType, this);
_emittedTypes.Add(newTypeDef);
return newTypeDef;
}
public EntityHandle EmitMetadataHandleForTypeSystemEntity(TypeSystemEntity entity)
{
switch (entity)
{
case FieldDesc field: return MakeMemberReferenceHandle(field);
case MethodDesc method: return MakeMemberReferenceHandle(method);
case TypeDesc type: return MakeTypeRefOrSpecHandle(type);
default:
throw new NotSupportedException();
}
}
public BlobHandle EmitSignatureBlobForMethodSignature(MethodSignature signature)
{
return MakeSignatureHandle(signature);
}
/// <summary>
/// Encode a type signature into a specified blob.
/// </summary>
/// <param name="blobBuilder">Blob to encode type signature into. Must not be null</param>
public void EncodeSignatureForType(TypeDesc type, BlobBuilder blobBuilder)
{
SignatureTypeEncoder sigEncoder = new SignatureTypeEncoder(blobBuilder);
_signatureEmitter.EncodeTypeSignature(sigEncoder, type);
}
public void EmitOutputFile(string outputPath)
{
using (FileStream sw = new FileStream(outputPath, FileMode.Create, FileAccess.ReadWrite))
{
EmitToStream(sw);
}
}
public void EmitToStream(Stream stream)
{
foreach (var typeDef in _emittedTypes)
{
MethodDefinitionHandle? firstMethodHandle = null;
foreach (var methodDef in typeDef.Methods)
{
int bodyOffset = _methodBodyStream.AddMethodBody(methodDef.Code);
BlobHandle signature = MakeSignatureHandle(methodDef.Signature);
MethodDefinitionHandle methodHandle = _metadataBuilder.AddMethodDefinition(
MethodAttributes.PrivateScope | MethodAttributes.Static,
MethodImplAttributes.IL | MethodImplAttributes.Managed,
_metadataBuilder.GetOrAddString(methodDef.Name),
signature,
bodyOffset,
parameterList: default(ParameterHandle));
if (firstMethodHandle == null)
firstMethodHandle = methodHandle;
}
_metadataBuilder.AddTypeDefinition(
default(TypeAttributes),
default(StringHandle),
_metadataBuilder.GetOrAddString(typeDef.Name),
typeDef.IsValueType ?
MakeTypeRefHandle(_typeSystemContext.GetWellKnownType(WellKnownType.ValueType)) :
MakeTypeRefHandle(_typeSystemContext.GetWellKnownType(WellKnownType.Object)),
fieldList: MetadataTokens.FieldDefinitionHandle(1),
methodList: firstMethodHandle.Value);
}
BlobBuilder peBlob = new BlobBuilder();
new ManagedPEBuilder(PEHeaderBuilder.CreateLibraryHeader(), new MetadataRootBuilder(_metadataBuilder), _methodBodyStream.Builder).Serialize(peBlob);
peBlob.WriteContentTo(stream);
// Clear some variables to catch any caller trying to emit data after writing the output file
_emittedTypes = null;
_metadataBuilder = null;
_methodBodyStream = default(MethodBodyStreamEncoder);
}
#region TypeSystem Entities To Handle Encoders
private Dictionary<IAssemblyDesc, AssemblyReferenceHandle> _assemblyRefHandles = new Dictionary<IAssemblyDesc, AssemblyReferenceHandle>();
private Dictionary<TypeDesc, EntityHandle> _typeRefOrSpecHandles = new Dictionary<TypeDesc, EntityHandle>();
private Dictionary<TypeSystemEntity, EntityHandle> _memberRefOrSpecHandles = new Dictionary<TypeSystemEntity, EntityHandle>();
private Dictionary<MethodSignature, BlobHandle> _methodSignatureHandles = new Dictionary<MethodSignature, BlobHandle>();
private Dictionary<FieldDesc, BlobHandle> _fieldSignatureHandles = new Dictionary<FieldDesc, BlobHandle>();
private struct EntityProviderForEcmaSignature : IEntityHandleProvider
{
private ManagedBinaryEmitter _emitter;
public EntityProviderForEcmaSignature(ManagedBinaryEmitter emitter)
{
_emitter = emitter;
}
public EntityHandle GetTypeDefOrRefHandleForTypeDesc(TypeDesc type)
{
return _emitter.MakeTypeRefHandle(type);
}
}
private EcmaSignatureEncoder<EntityProviderForEcmaSignature> _signatureEmitter;
private BlobHandle MakeSignatureHandle(MethodSignature signature)
{
BlobHandle handle;
if (!_methodSignatureHandles.TryGetValue(signature, out handle))
{
BlobBuilder metadataSignature = new BlobBuilder();
_signatureEmitter.EncodeMethodSignature(metadataSignature, signature);
_methodSignatureHandles[signature] = handle = _metadataBuilder.GetOrAddBlob(metadataSignature);
}
return handle;
}
private BlobHandle MakeSignatureHandle(TypeSystemEntity methodOrField)
{
if (methodOrField is MethodDesc)
{
return MakeSignatureHandle(((MethodDesc)methodOrField).Signature);
}
else
{
BlobHandle handle;
FieldDesc field = (FieldDesc)methodOrField;
if (!_fieldSignatureHandles.TryGetValue(field, out handle))
{
BlobBuilder metadataSignature = new BlobBuilder();
SignatureTypeEncoder fieldSigEncoder = new BlobEncoder(metadataSignature).FieldSignature();
_signatureEmitter.EncodeTypeSignature(fieldSigEncoder, field.FieldType);
_fieldSignatureHandles[field] = handle = _metadataBuilder.GetOrAddBlob(metadataSignature);
}
return handle;
}
}
private AssemblyReferenceHandle MakeAssemblyReferenceHandle(IAssemblyDesc assemblyRef)
{
AssemblyReferenceHandle handle;
if (!_assemblyRefHandles.TryGetValue(assemblyRef, out handle))
{
AssemblyName assemblyName = assemblyRef.GetName();
handle = _metadataBuilder.AddAssemblyReference(
_metadataBuilder.GetOrAddString(assemblyName.Name),
assemblyName.Version,
default(StringHandle),
_metadataBuilder.GetOrAddBlob(ImmutableArray.Create<byte>(assemblyName.GetPublicKeyToken())),
default(AssemblyFlags),
default(BlobHandle));
_assemblyRefHandles[assemblyRef] = handle;
}
return handle;
}
private EntityHandle MakeTypeRefHandle(TypeDesc type)
{
Debug.Assert(type.IsTypeDefinition);
Debug.Assert(type is MetadataType);
EntityHandle handle;
if (!_typeRefOrSpecHandles.TryGetValue(type, out handle))
{
EntityHandle scope;
MetadataType typeAsMetadataType = (MetadataType)type;
if (typeAsMetadataType.ContainingType != null)
scope = MakeTypeRefHandle(typeAsMetadataType.ContainingType);
else
scope = MakeAssemblyReferenceHandle((IAssemblyDesc)typeAsMetadataType.Module);
handle = _metadataBuilder.AddTypeReference(
scope,
_metadataBuilder.GetOrAddString(typeAsMetadataType.Namespace),
_metadataBuilder.GetOrAddString(typeAsMetadataType.Name));
_typeRefOrSpecHandles[type] = handle;
}
return handle;
}
private EntityHandle MakeTypeRefOrSpecHandle(TypeDesc type)
{
EntityHandle handle;
if (!_typeRefOrSpecHandles.TryGetValue(type, out handle))
{
if(!type.IsDefType || !type.IsTypeDefinition || type is RuntimeDeterminedType)
{
SignatureTypeEncoder sigEncoder = new SignatureTypeEncoder(new BlobBuilder());
_signatureEmitter.EncodeTypeSignature(sigEncoder, type);
handle = _metadataBuilder.AddTypeSpecification(_metadataBuilder.GetOrAddBlob(sigEncoder.Builder));
}
else
{
handle = MakeTypeRefHandle(type);
}
_typeRefOrSpecHandles[type] = handle;
}
return handle;
}
private EntityHandle MakeMemberReferenceHandle(TypeSystemEntity methodOrField)
{
EntityHandle handle;
if (!_memberRefOrSpecHandles.TryGetValue(methodOrField, out handle))
{
MethodDesc method = methodOrField as MethodDesc;
FieldDesc field = methodOrField as FieldDesc;
TypeDesc owningType = (method != null ? method.OwningType : field.OwningType);
string name = (method != null ? method.Name : field.Name);
BlobHandle signature = method != null ?
MakeSignatureHandle(method.GetTypicalMethodDefinition()) :
MakeSignatureHandle(field);
handle = _metadataBuilder.AddMemberReference(
MakeTypeRefOrSpecHandle(owningType),
_metadataBuilder.GetOrAddString(name),
signature);
if (method != null && method.HasInstantiation && !method.IsTypicalMethodDefinition)
{
BlobEncoder methodSpecEncoder = new BlobEncoder(new BlobBuilder());
GenericTypeArgumentsEncoder argEncoder = methodSpecEncoder.MethodSpecificationSignature(method.Instantiation.Length);
for (int i = 0; i < method.Instantiation.Length; i++)
{
SignatureTypeEncoder argTypeEncoder = argEncoder.AddArgument();
_signatureEmitter.EncodeTypeSignature(argTypeEncoder, method.Instantiation[i]);
}
handle = _metadataBuilder.AddMethodSpecification(handle, _metadataBuilder.GetOrAddBlob(methodSpecEncoder.Builder));
}
_memberRefOrSpecHandles[methodOrField] = handle;
}
return handle;
}
#endregion
}
public static class InstructionEncoderExtensions
{
public static void EmitLdToken(this InstructionEncoder code, TypeSystemEntity typeSystemEntity, ManagedBinaryEmitter emitter)
{
code.OpCode(ILOpCode.Ldtoken);
code.Token(emitter.EmitMetadataHandleForTypeSystemEntity(typeSystemEntity));
}
public static void EmitI4Constant(this InstructionEncoder code, int value)
{
code.OpCode(ILOpCode.Ldc_i4);
code.CodeBuilder.WriteInt32(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.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.Metadata;
using System.Collections.Immutable;
using System.Reflection.PortableExecutable;
using System.IO;
using System.Diagnostics;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using ILCompiler.DependencyAnalysis;
namespace ILCompiler
{
public class ManagedBinaryEmitter
{
public class EmittedTypeDefinition
{
private readonly ManagedBinaryEmitter _managedEmitter;
private List<EmittedMethodDefinition> _methods = new List<EmittedMethodDefinition>();
public string Name { get; private set; }
public bool IsValueType { get; private set; }
public IReadOnlyList<EmittedMethodDefinition> Methods => _methods;
internal EmittedTypeDefinition(string name, bool isValueType, ManagedBinaryEmitter managedEmitter)
{
Name = name;
IsValueType = isValueType;
_managedEmitter = managedEmitter;
}
public EmittedMethodDefinition EmitMethodDefinition(string name, MethodSignature signature)
{
var newMethodDef = new EmittedMethodDefinition(name, signature, _managedEmitter);
_methods.Add(newMethodDef);
return newMethodDef;
}
}
public class EmittedMethodDefinition
{
private readonly ManagedBinaryEmitter _managedEmitter;
public string Name { get; private set; }
public MethodSignature Signature { get; private set; }
public InstructionEncoder Code { get; private set; }
internal EmittedMethodDefinition(string name, MethodSignature signature, ManagedBinaryEmitter managedEmitter)
{
Name = name;
Signature = signature;
_managedEmitter = managedEmitter;
Code = new InstructionEncoder(new BlobBuilder());
}
}
private readonly TypeSystemContext _typeSystemContext;
private MetadataBuilder _metadataBuilder;
private MethodBodyStreamEncoder _methodBodyStream;
private List<EmittedTypeDefinition> _emittedTypes;
protected MetadataBuilder Builder => _metadataBuilder;
public ManagedBinaryEmitter(TypeSystemContext typeSystemContext, string assemblyName)
{
_typeSystemContext = typeSystemContext;
_metadataBuilder = new MetadataBuilder();
_methodBodyStream = new MethodBodyStreamEncoder(new BlobBuilder());
_emittedTypes = new List<EmittedTypeDefinition>();
_metadataBuilder.AddAssembly(
_metadataBuilder.GetOrAddString(assemblyName),
new Version(0, 0, 0, 0),
culture: default(StringHandle),
publicKey: default(BlobHandle),
flags: default(AssemblyFlags),
hashAlgorithm: AssemblyHashAlgorithm.None);
_metadataBuilder.AddModule(
0,
_metadataBuilder.GetOrAddString(assemblyName),
default(GuidHandle), default(GuidHandle), default(GuidHandle));
// Module type
_metadataBuilder.AddTypeDefinition(
default(TypeAttributes),
default(StringHandle),
_metadataBuilder.GetOrAddString("<Module>"),
baseType: default(EntityHandle),
fieldList: MetadataTokens.FieldDefinitionHandle(1),
methodList: MetadataTokens.MethodDefinitionHandle(1));
_signatureEmitter = new EcmaSignatureEncoder<EntityProviderForEcmaSignature>(new EntityProviderForEcmaSignature(this));
}
public EmittedTypeDefinition EmitTypeDefinition(string typeName, bool isValueType)
{
EmittedTypeDefinition newTypeDef = new EmittedTypeDefinition(typeName, isValueType, this);
_emittedTypes.Add(newTypeDef);
return newTypeDef;
}
public EntityHandle EmitMetadataHandleForTypeSystemEntity(TypeSystemEntity entity)
{
switch (entity)
{
case FieldDesc field: return MakeMemberReferenceHandle(field);
case MethodDesc method: return MakeMemberReferenceHandle(method);
case TypeDesc type: return MakeTypeRefOrSpecHandle(type);
default:
throw new NotSupportedException();
}
}
public BlobHandle EmitSignatureBlobForMethodSignature(MethodSignature signature)
{
return MakeSignatureHandle(signature);
}
/// <summary>
/// Encode a type signature into a specified blob.
/// </summary>
/// <param name="blobBuilder">Blob to encode type signature into. Must not be null</param>
public void EncodeSignatureForType(TypeDesc type, BlobBuilder blobBuilder)
{
SignatureTypeEncoder sigEncoder = new SignatureTypeEncoder(blobBuilder);
_signatureEmitter.EncodeTypeSignature(sigEncoder, type);
}
public void EmitOutputFile(string outputPath)
{
using (FileStream sw = new FileStream(outputPath, FileMode.Create, FileAccess.ReadWrite))
{
EmitToStream(sw);
}
}
public void EmitToStream(Stream stream)
{
foreach (var typeDef in _emittedTypes)
{
MethodDefinitionHandle? firstMethodHandle = null;
foreach (var methodDef in typeDef.Methods)
{
int bodyOffset = _methodBodyStream.AddMethodBody(methodDef.Code);
BlobHandle signature = MakeSignatureHandle(methodDef.Signature);
MethodDefinitionHandle methodHandle = _metadataBuilder.AddMethodDefinition(
MethodAttributes.PrivateScope | MethodAttributes.Static,
MethodImplAttributes.IL | MethodImplAttributes.Managed,
_metadataBuilder.GetOrAddString(methodDef.Name),
signature,
bodyOffset,
parameterList: default(ParameterHandle));
if (firstMethodHandle == null)
firstMethodHandle = methodHandle;
}
_metadataBuilder.AddTypeDefinition(
default(TypeAttributes),
default(StringHandle),
_metadataBuilder.GetOrAddString(typeDef.Name),
typeDef.IsValueType ?
MakeTypeRefHandle(_typeSystemContext.GetWellKnownType(WellKnownType.ValueType)) :
MakeTypeRefHandle(_typeSystemContext.GetWellKnownType(WellKnownType.Object)),
fieldList: MetadataTokens.FieldDefinitionHandle(1),
methodList: firstMethodHandle.Value);
}
BlobBuilder peBlob = new BlobBuilder();
new ManagedPEBuilder(PEHeaderBuilder.CreateLibraryHeader(), new MetadataRootBuilder(_metadataBuilder), _methodBodyStream.Builder).Serialize(peBlob);
peBlob.WriteContentTo(stream);
// Clear some variables to catch any caller trying to emit data after writing the output file
_emittedTypes = null;
_metadataBuilder = null;
_methodBodyStream = default(MethodBodyStreamEncoder);
}
#region TypeSystem Entities To Handle Encoders
private Dictionary<IAssemblyDesc, AssemblyReferenceHandle> _assemblyRefHandles = new Dictionary<IAssemblyDesc, AssemblyReferenceHandle>();
private Dictionary<TypeDesc, EntityHandle> _typeRefOrSpecHandles = new Dictionary<TypeDesc, EntityHandle>();
private Dictionary<TypeSystemEntity, EntityHandle> _memberRefOrSpecHandles = new Dictionary<TypeSystemEntity, EntityHandle>();
private Dictionary<MethodSignature, BlobHandle> _methodSignatureHandles = new Dictionary<MethodSignature, BlobHandle>();
private Dictionary<FieldDesc, BlobHandle> _fieldSignatureHandles = new Dictionary<FieldDesc, BlobHandle>();
private struct EntityProviderForEcmaSignature : IEntityHandleProvider
{
private ManagedBinaryEmitter _emitter;
public EntityProviderForEcmaSignature(ManagedBinaryEmitter emitter)
{
_emitter = emitter;
}
public EntityHandle GetTypeDefOrRefHandleForTypeDesc(TypeDesc type)
{
return _emitter.MakeTypeRefHandle(type);
}
}
private EcmaSignatureEncoder<EntityProviderForEcmaSignature> _signatureEmitter;
private BlobHandle MakeSignatureHandle(MethodSignature signature)
{
BlobHandle handle;
if (!_methodSignatureHandles.TryGetValue(signature, out handle))
{
BlobBuilder metadataSignature = new BlobBuilder();
_signatureEmitter.EncodeMethodSignature(metadataSignature, signature);
_methodSignatureHandles[signature] = handle = _metadataBuilder.GetOrAddBlob(metadataSignature);
}
return handle;
}
private BlobHandle MakeSignatureHandle(TypeSystemEntity methodOrField)
{
if (methodOrField is MethodDesc)
{
return MakeSignatureHandle(((MethodDesc)methodOrField).Signature);
}
else
{
BlobHandle handle;
FieldDesc field = (FieldDesc)methodOrField;
if (!_fieldSignatureHandles.TryGetValue(field, out handle))
{
BlobBuilder metadataSignature = new BlobBuilder();
SignatureTypeEncoder fieldSigEncoder = new BlobEncoder(metadataSignature).FieldSignature();
_signatureEmitter.EncodeTypeSignature(fieldSigEncoder, field.FieldType);
_fieldSignatureHandles[field] = handle = _metadataBuilder.GetOrAddBlob(metadataSignature);
}
return handle;
}
}
private AssemblyReferenceHandle MakeAssemblyReferenceHandle(IAssemblyDesc assemblyRef)
{
AssemblyReferenceHandle handle;
if (!_assemblyRefHandles.TryGetValue(assemblyRef, out handle))
{
AssemblyName assemblyName = assemblyRef.GetName();
handle = _metadataBuilder.AddAssemblyReference(
_metadataBuilder.GetOrAddString(assemblyName.Name),
assemblyName.Version,
default(StringHandle),
_metadataBuilder.GetOrAddBlob(ImmutableArray.Create<byte>(assemblyName.GetPublicKeyToken())),
default(AssemblyFlags),
default(BlobHandle));
_assemblyRefHandles[assemblyRef] = handle;
}
return handle;
}
private EntityHandle MakeTypeRefHandle(TypeDesc type)
{
Debug.Assert(type.IsTypeDefinition);
Debug.Assert(type is MetadataType);
EntityHandle handle;
if (!_typeRefOrSpecHandles.TryGetValue(type, out handle))
{
EntityHandle scope;
MetadataType typeAsMetadataType = (MetadataType)type;
if (typeAsMetadataType.ContainingType != null)
scope = MakeTypeRefHandle(typeAsMetadataType.ContainingType);
else
scope = MakeAssemblyReferenceHandle((IAssemblyDesc)typeAsMetadataType.Module);
handle = _metadataBuilder.AddTypeReference(
scope,
_metadataBuilder.GetOrAddString(typeAsMetadataType.Namespace),
_metadataBuilder.GetOrAddString(typeAsMetadataType.Name));
_typeRefOrSpecHandles[type] = handle;
}
return handle;
}
private EntityHandle MakeTypeRefOrSpecHandle(TypeDesc type)
{
EntityHandle handle;
if (!_typeRefOrSpecHandles.TryGetValue(type, out handle))
{
if(!type.IsDefType || !type.IsTypeDefinition || type is RuntimeDeterminedType)
{
SignatureTypeEncoder sigEncoder = new SignatureTypeEncoder(new BlobBuilder());
_signatureEmitter.EncodeTypeSignature(sigEncoder, type);
handle = _metadataBuilder.AddTypeSpecification(_metadataBuilder.GetOrAddBlob(sigEncoder.Builder));
}
else
{
handle = MakeTypeRefHandle(type);
}
_typeRefOrSpecHandles[type] = handle;
}
return handle;
}
private EntityHandle MakeMemberReferenceHandle(TypeSystemEntity methodOrField)
{
EntityHandle handle;
if (!_memberRefOrSpecHandles.TryGetValue(methodOrField, out handle))
{
MethodDesc method = methodOrField as MethodDesc;
FieldDesc field = methodOrField as FieldDesc;
TypeDesc owningType = (method != null ? method.OwningType : field.OwningType);
string name = (method != null ? method.Name : field.Name);
BlobHandle signature = method != null ?
MakeSignatureHandle(method.GetTypicalMethodDefinition()) :
MakeSignatureHandle(field);
handle = _metadataBuilder.AddMemberReference(
MakeTypeRefOrSpecHandle(owningType),
_metadataBuilder.GetOrAddString(name),
signature);
if (method != null && method.HasInstantiation && !method.IsTypicalMethodDefinition)
{
BlobEncoder methodSpecEncoder = new BlobEncoder(new BlobBuilder());
GenericTypeArgumentsEncoder argEncoder = methodSpecEncoder.MethodSpecificationSignature(method.Instantiation.Length);
for (int i = 0; i < method.Instantiation.Length; i++)
{
SignatureTypeEncoder argTypeEncoder = argEncoder.AddArgument();
_signatureEmitter.EncodeTypeSignature(argTypeEncoder, method.Instantiation[i]);
}
handle = _metadataBuilder.AddMethodSpecification(handle, _metadataBuilder.GetOrAddBlob(methodSpecEncoder.Builder));
}
_memberRefOrSpecHandles[methodOrField] = handle;
}
return handle;
}
#endregion
}
public static class InstructionEncoderExtensions
{
public static void EmitLdToken(this InstructionEncoder code, TypeSystemEntity typeSystemEntity, ManagedBinaryEmitter emitter)
{
code.OpCode(ILOpCode.Ldtoken);
code.Token(emitter.EmitMetadataHandleForTypeSystemEntity(typeSystemEntity));
}
public static void EmitI4Constant(this InstructionEncoder code, int value)
{
code.OpCode(ILOpCode.Ldc_i4);
code.CodeBuilder.WriteInt32(value);
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.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.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Transactions.Configuration;
using System.Transactions.Distributed;
namespace System.Transactions
{
public delegate Transaction? HostCurrentTransactionCallback();
public delegate void TransactionStartedEventHandler(object? sender, TransactionEventArgs e);
public static class TransactionManager
{
// Revovery Information Version
private const int RecoveryInformationVersion1 = 1;
// Hashtable of promoted transactions, keyed by identifier guid. This is used by
// FindPromotedTransaction to support transaction equivalence when a transaction is
// serialized and then deserialized back in this app-domain.
private static Hashtable? s_promotedTransactionTable;
// Sorted Table of transaction timeouts
private static TransactionTable? s_transactionTable;
private static TransactionStartedEventHandler? s_distributedTransactionStartedDelegate;
public static event TransactionStartedEventHandler? DistributedTransactionStarted
{
add
{
lock (ClassSyncObject)
{
s_distributedTransactionStartedDelegate = (TransactionStartedEventHandler?)System.Delegate.Combine(s_distributedTransactionStartedDelegate, value);
if (value != null)
{
ProcessExistingTransactions(value);
}
}
}
remove
{
lock (ClassSyncObject)
{
s_distributedTransactionStartedDelegate = (TransactionStartedEventHandler?)System.Delegate.Remove(s_distributedTransactionStartedDelegate, value);
}
}
}
internal static void ProcessExistingTransactions(TransactionStartedEventHandler eventHandler)
{
lock (PromotedTransactionTable)
{
// Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
IDictionaryEnumerator e = PromotedTransactionTable.GetEnumerator();
while (e.MoveNext())
{
WeakReference weakRef = (WeakReference)e.Value!;
if (weakRef.Target is Transaction tx)
{
TransactionEventArgs args = new TransactionEventArgs();
args._transaction = tx.InternalClone();
eventHandler(args._transaction, args);
}
}
}
}
internal static void FireDistributedTransactionStarted(Transaction transaction)
{
TransactionStartedEventHandler? localStartedEventHandler = null;
lock (ClassSyncObject)
{
localStartedEventHandler = s_distributedTransactionStartedDelegate;
}
if (null != localStartedEventHandler)
{
TransactionEventArgs args = new TransactionEventArgs();
args._transaction = transaction.InternalClone();
localStartedEventHandler(args._transaction, args);
}
}
// Data storage for current delegate
internal static HostCurrentTransactionCallback? s_currentDelegate;
internal static bool s_currentDelegateSet;
// CurrentDelegate
//
// Store a delegate to be used to query for an external current transaction.
[DisallowNull]
public static HostCurrentTransactionCallback? HostCurrentCallback
{
// get_HostCurrentCallback is used from get_CurrentTransaction, which doesn't have any permission requirements.
// We don't expose what is returned from this property in that case. But we don't want just anybody being able
// to retrieve the value.
get
{
// Note do not add trace notifications to this method. It is called
// at the startup of SQLCLR and tracing has too much working set overhead.
return s_currentDelegate;
}
set
{
// Note do not add trace notifications to this method. It is called
// at the startup of SQLCLR and tracing has too much working set overhead.
ArgumentNullException.ThrowIfNull(value);
lock (ClassSyncObject)
{
if (s_currentDelegateSet)
{
throw new InvalidOperationException(SR.CurrentDelegateSet);
}
s_currentDelegateSet = true;
}
s_currentDelegate = value;
}
}
public static Enlistment Reenlist(
Guid resourceManagerIdentifier,
byte[] recoveryInformation,
IEnlistmentNotification enlistmentNotification)
{
if (resourceManagerIdentifier == Guid.Empty)
{
throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier));
}
if (null == recoveryInformation)
{
throw new ArgumentNullException(nameof(recoveryInformation));
}
if (null == enlistmentNotification)
{
throw new ArgumentNullException(nameof(enlistmentNotification));
}
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "TransactionManager.Reenlist");
etwLog.TransactionManagerReenlist(resourceManagerIdentifier);
}
// Put the recovery information into a stream.
MemoryStream stream = new MemoryStream(recoveryInformation);
int recoveryInformationVersion;
string? nodeName = null;
byte[]? resourceManagerRecoveryInformation = null;
try
{
BinaryReader reader = new BinaryReader(stream);
recoveryInformationVersion = reader.ReadInt32();
if (recoveryInformationVersion == TransactionManager.RecoveryInformationVersion1)
{
nodeName = reader.ReadString();
resourceManagerRecoveryInformation = reader.ReadBytes(recoveryInformation.Length - checked((int)stream.Position));
}
else
{
if (etwLog.IsEnabled())
{
etwLog.TransactionExceptionTrace(TraceSourceType.TraceSourceBase, TransactionExceptionType.UnrecognizedRecoveryInformation, nameof(recoveryInformation), string.Empty);
}
throw new ArgumentException(SR.UnrecognizedRecoveryInformation, nameof(recoveryInformation));
}
}
catch (EndOfStreamException e)
{
if (etwLog.IsEnabled())
{
etwLog.TransactionExceptionTrace(TraceSourceType.TraceSourceBase, TransactionExceptionType.UnrecognizedRecoveryInformation, nameof(recoveryInformation), e.ToString());
}
throw new ArgumentException(SR.UnrecognizedRecoveryInformation, nameof(recoveryInformation), e);
}
catch (FormatException e)
{
if (etwLog.IsEnabled())
{
etwLog.TransactionExceptionTrace(TraceSourceType.TraceSourceBase, TransactionExceptionType.UnrecognizedRecoveryInformation, nameof(recoveryInformation), e.ToString());
}
throw new ArgumentException(SR.UnrecognizedRecoveryInformation, nameof(recoveryInformation), e);
}
finally
{
stream.Dispose();
}
DistributedTransactionManager transactionManager = CheckTransactionManager(nodeName);
// Now ask the Transaction Manager to reenlist.
object syncRoot = new object();
Enlistment returnValue = new Enlistment(enlistmentNotification, syncRoot);
EnlistmentState.EnlistmentStatePromoted.EnterState(returnValue.InternalEnlistment);
returnValue.InternalEnlistment.PromotedEnlistment =
transactionManager.ReenlistTransaction(
resourceManagerIdentifier,
resourceManagerRecoveryInformation,
(RecoveringInternalEnlistment)returnValue.InternalEnlistment
);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, "TransactionManager.Reenlist");
}
return returnValue;
}
private static DistributedTransactionManager CheckTransactionManager(string? nodeName)
{
DistributedTransactionManager tm = DistributedTransactionManager;
if (!((tm.NodeName == null && (nodeName == null || nodeName.Length == 0)) ||
(tm.NodeName != null && tm.NodeName.Equals(nodeName))))
{
throw new ArgumentException(SR.InvalidRecoveryInformation, "recoveryInformation");
}
return tm;
}
public static void RecoveryComplete(Guid resourceManagerIdentifier)
{
if (resourceManagerIdentifier == Guid.Empty)
{
throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier));
}
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "TransactionManager.RecoveryComplete");
etwLog.TransactionManagerRecoveryComplete(resourceManagerIdentifier);
}
DistributedTransactionManager.ResourceManagerRecoveryComplete(resourceManagerIdentifier);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, "TransactionManager.RecoveryComplete");
}
}
// Object for synchronizing access to the entire class( avoiding lock( typeof( ... )) )
private static object? s_classSyncObject;
// Helper object for static synchronization
private static object ClassSyncObject => LazyInitializer.EnsureInitialized(ref s_classSyncObject);
internal static IsolationLevel DefaultIsolationLevel
{
get
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "TransactionManager.get_DefaultIsolationLevel");
etwLog.MethodExit(TraceSourceType.TraceSourceBase, "TransactionManager.get_DefaultIsolationLevel");
}
return IsolationLevel.Serializable;
}
}
private static DefaultSettingsSection? s_defaultSettings;
private static DefaultSettingsSection DefaultSettings
{
get
{
if (s_defaultSettings == null)
{
s_defaultSettings = DefaultSettingsSection.GetSection();
}
return s_defaultSettings;
}
}
private static MachineSettingsSection? s_machineSettings;
private static MachineSettingsSection MachineSettings
{
get
{
if (s_machineSettings == null)
{
s_machineSettings = MachineSettingsSection.GetSection();
}
return s_machineSettings;
}
}
private static bool s_defaultTimeoutValidated;
private static TimeSpan s_defaultTimeout;
public static TimeSpan DefaultTimeout
{
get
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "TransactionManager.get_DefaultTimeout");
}
if (!s_defaultTimeoutValidated)
{
s_defaultTimeout = ValidateTimeout(DefaultSettings.Timeout);
// If the timeout value got adjusted, it must have been greater than MaximumTimeout.
if (s_defaultTimeout != DefaultSettings.Timeout)
{
if (etwLog.IsEnabled())
{
etwLog.ConfiguredDefaultTimeoutAdjusted();
}
}
s_defaultTimeoutValidated = true;
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, "TransactionManager.get_DefaultTimeout");
}
return s_defaultTimeout;
}
}
private static bool s_cachedMaxTimeout;
private static TimeSpan s_maximumTimeout;
public static TimeSpan MaximumTimeout
{
get
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "TransactionManager.get_DefaultMaximumTimeout");
}
LazyInitializer.EnsureInitialized(ref s_maximumTimeout, ref s_cachedMaxTimeout, ref s_classSyncObject, () => MachineSettings.MaxTimeout);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, "TransactionManager.get_DefaultMaximumTimeout");
}
return s_maximumTimeout;
}
}
/// <summary>
/// This static function throws an ArgumentOutOfRange if the specified IsolationLevel is not within
/// the range of valid values.
/// </summary>
/// <param name="transactionIsolationLevel">
/// The IsolationLevel value to validate.
/// </param>
internal static void ValidateIsolationLevel(IsolationLevel transactionIsolationLevel)
{
switch (transactionIsolationLevel)
{
case IsolationLevel.Serializable:
case IsolationLevel.RepeatableRead:
case IsolationLevel.ReadCommitted:
case IsolationLevel.ReadUncommitted:
case IsolationLevel.Unspecified:
case IsolationLevel.Chaos:
case IsolationLevel.Snapshot:
break;
default:
throw new ArgumentOutOfRangeException(nameof(transactionIsolationLevel));
}
}
/// <summary>
/// This static function throws an ArgumentOutOfRange if the specified TimeSpan does not meet
/// requirements of a valid transaction timeout. Timeout values must be positive.
/// </summary>
/// <param name="transactionTimeout">
/// The TimeSpan value to validate.
/// </param>
internal static TimeSpan ValidateTimeout(TimeSpan transactionTimeout)
{
if (transactionTimeout < TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(transactionTimeout));
}
if (MaximumTimeout != TimeSpan.Zero)
{
if (transactionTimeout > MaximumTimeout || transactionTimeout == TimeSpan.Zero)
{
return MaximumTimeout;
}
}
return transactionTimeout;
}
internal static Transaction? FindPromotedTransaction(Guid transactionIdentifier)
{
Hashtable promotedTransactionTable = PromotedTransactionTable;
WeakReference? weakRef = (WeakReference?)promotedTransactionTable[transactionIdentifier];
if (null != weakRef)
{
if (weakRef.Target is Transaction tx)
{
return tx.InternalClone();
}
else // an old, moldy weak reference. Let's get rid of it.
{
lock (promotedTransactionTable)
{
promotedTransactionTable.Remove(transactionIdentifier);
}
}
}
return null;
}
internal static Transaction FindOrCreatePromotedTransaction(Guid transactionIdentifier, DistributedTransaction dtx)
{
Transaction? tx = null;
Hashtable promotedTransactionTable = PromotedTransactionTable;
lock (promotedTransactionTable)
{
WeakReference? weakRef = (WeakReference?)promotedTransactionTable[transactionIdentifier];
if (null != weakRef)
{
tx = weakRef.Target as Transaction;
if (null != tx)
{
// If we found a transaction then dispose it
dtx.Dispose();
return tx.InternalClone();
}
else
{
// an old, moldy weak reference. Let's get rid of it.
lock (promotedTransactionTable)
{
promotedTransactionTable.Remove(transactionIdentifier);
}
}
}
tx = new Transaction(dtx);
// Since we are adding this reference to the table create an object that will clean that entry up.
tx._internalTransaction._finalizedObject = new FinalizedObject(tx._internalTransaction, dtx.Identifier);
weakRef = new WeakReference(tx, false);
promotedTransactionTable[dtx.Identifier] = weakRef;
}
dtx.SavedLtmPromotedTransaction = tx;
FireDistributedTransactionStarted(tx);
return tx;
}
// Table for promoted transactions
internal static Hashtable PromotedTransactionTable =>
LazyInitializer.EnsureInitialized(ref s_promotedTransactionTable, ref s_classSyncObject, () => new Hashtable(100));
// Table for transaction timeouts
internal static TransactionTable TransactionTable =>
LazyInitializer.EnsureInitialized(ref s_transactionTable, ref s_classSyncObject, () => new TransactionTable());
// Fault in a DistributedTransactionManager if one has not already been created.
internal static DistributedTransactionManager? distributedTransactionManager;
internal static DistributedTransactionManager DistributedTransactionManager =>
// If the distributed transaction manager is not configured, throw an exception
LazyInitializer.EnsureInitialized(ref distributedTransactionManager, ref s_classSyncObject, () => new DistributedTransactionManager());
}
}
|
// 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.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Transactions.Configuration;
using System.Transactions.Distributed;
namespace System.Transactions
{
public delegate Transaction? HostCurrentTransactionCallback();
public delegate void TransactionStartedEventHandler(object? sender, TransactionEventArgs e);
public static class TransactionManager
{
// Revovery Information Version
private const int RecoveryInformationVersion1 = 1;
// Hashtable of promoted transactions, keyed by identifier guid. This is used by
// FindPromotedTransaction to support transaction equivalence when a transaction is
// serialized and then deserialized back in this app-domain.
private static Hashtable? s_promotedTransactionTable;
// Sorted Table of transaction timeouts
private static TransactionTable? s_transactionTable;
private static TransactionStartedEventHandler? s_distributedTransactionStartedDelegate;
public static event TransactionStartedEventHandler? DistributedTransactionStarted
{
add
{
lock (ClassSyncObject)
{
s_distributedTransactionStartedDelegate = (TransactionStartedEventHandler?)System.Delegate.Combine(s_distributedTransactionStartedDelegate, value);
if (value != null)
{
ProcessExistingTransactions(value);
}
}
}
remove
{
lock (ClassSyncObject)
{
s_distributedTransactionStartedDelegate = (TransactionStartedEventHandler?)System.Delegate.Remove(s_distributedTransactionStartedDelegate, value);
}
}
}
internal static void ProcessExistingTransactions(TransactionStartedEventHandler eventHandler)
{
lock (PromotedTransactionTable)
{
// Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
IDictionaryEnumerator e = PromotedTransactionTable.GetEnumerator();
while (e.MoveNext())
{
WeakReference weakRef = (WeakReference)e.Value!;
if (weakRef.Target is Transaction tx)
{
TransactionEventArgs args = new TransactionEventArgs();
args._transaction = tx.InternalClone();
eventHandler(args._transaction, args);
}
}
}
}
internal static void FireDistributedTransactionStarted(Transaction transaction)
{
TransactionStartedEventHandler? localStartedEventHandler = null;
lock (ClassSyncObject)
{
localStartedEventHandler = s_distributedTransactionStartedDelegate;
}
if (null != localStartedEventHandler)
{
TransactionEventArgs args = new TransactionEventArgs();
args._transaction = transaction.InternalClone();
localStartedEventHandler(args._transaction, args);
}
}
// Data storage for current delegate
internal static HostCurrentTransactionCallback? s_currentDelegate;
internal static bool s_currentDelegateSet;
// CurrentDelegate
//
// Store a delegate to be used to query for an external current transaction.
[DisallowNull]
public static HostCurrentTransactionCallback? HostCurrentCallback
{
// get_HostCurrentCallback is used from get_CurrentTransaction, which doesn't have any permission requirements.
// We don't expose what is returned from this property in that case. But we don't want just anybody being able
// to retrieve the value.
get
{
// Note do not add trace notifications to this method. It is called
// at the startup of SQLCLR and tracing has too much working set overhead.
return s_currentDelegate;
}
set
{
// Note do not add trace notifications to this method. It is called
// at the startup of SQLCLR and tracing has too much working set overhead.
ArgumentNullException.ThrowIfNull(value);
lock (ClassSyncObject)
{
if (s_currentDelegateSet)
{
throw new InvalidOperationException(SR.CurrentDelegateSet);
}
s_currentDelegateSet = true;
}
s_currentDelegate = value;
}
}
public static Enlistment Reenlist(
Guid resourceManagerIdentifier,
byte[] recoveryInformation,
IEnlistmentNotification enlistmentNotification)
{
if (resourceManagerIdentifier == Guid.Empty)
{
throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier));
}
if (null == recoveryInformation)
{
throw new ArgumentNullException(nameof(recoveryInformation));
}
if (null == enlistmentNotification)
{
throw new ArgumentNullException(nameof(enlistmentNotification));
}
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "TransactionManager.Reenlist");
etwLog.TransactionManagerReenlist(resourceManagerIdentifier);
}
// Put the recovery information into a stream.
MemoryStream stream = new MemoryStream(recoveryInformation);
int recoveryInformationVersion;
string? nodeName = null;
byte[]? resourceManagerRecoveryInformation = null;
try
{
BinaryReader reader = new BinaryReader(stream);
recoveryInformationVersion = reader.ReadInt32();
if (recoveryInformationVersion == TransactionManager.RecoveryInformationVersion1)
{
nodeName = reader.ReadString();
resourceManagerRecoveryInformation = reader.ReadBytes(recoveryInformation.Length - checked((int)stream.Position));
}
else
{
if (etwLog.IsEnabled())
{
etwLog.TransactionExceptionTrace(TraceSourceType.TraceSourceBase, TransactionExceptionType.UnrecognizedRecoveryInformation, nameof(recoveryInformation), string.Empty);
}
throw new ArgumentException(SR.UnrecognizedRecoveryInformation, nameof(recoveryInformation));
}
}
catch (EndOfStreamException e)
{
if (etwLog.IsEnabled())
{
etwLog.TransactionExceptionTrace(TraceSourceType.TraceSourceBase, TransactionExceptionType.UnrecognizedRecoveryInformation, nameof(recoveryInformation), e.ToString());
}
throw new ArgumentException(SR.UnrecognizedRecoveryInformation, nameof(recoveryInformation), e);
}
catch (FormatException e)
{
if (etwLog.IsEnabled())
{
etwLog.TransactionExceptionTrace(TraceSourceType.TraceSourceBase, TransactionExceptionType.UnrecognizedRecoveryInformation, nameof(recoveryInformation), e.ToString());
}
throw new ArgumentException(SR.UnrecognizedRecoveryInformation, nameof(recoveryInformation), e);
}
finally
{
stream.Dispose();
}
DistributedTransactionManager transactionManager = CheckTransactionManager(nodeName);
// Now ask the Transaction Manager to reenlist.
object syncRoot = new object();
Enlistment returnValue = new Enlistment(enlistmentNotification, syncRoot);
EnlistmentState.EnlistmentStatePromoted.EnterState(returnValue.InternalEnlistment);
returnValue.InternalEnlistment.PromotedEnlistment =
transactionManager.ReenlistTransaction(
resourceManagerIdentifier,
resourceManagerRecoveryInformation,
(RecoveringInternalEnlistment)returnValue.InternalEnlistment
);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, "TransactionManager.Reenlist");
}
return returnValue;
}
private static DistributedTransactionManager CheckTransactionManager(string? nodeName)
{
DistributedTransactionManager tm = DistributedTransactionManager;
if (!((tm.NodeName == null && (nodeName == null || nodeName.Length == 0)) ||
(tm.NodeName != null && tm.NodeName.Equals(nodeName))))
{
throw new ArgumentException(SR.InvalidRecoveryInformation, "recoveryInformation");
}
return tm;
}
public static void RecoveryComplete(Guid resourceManagerIdentifier)
{
if (resourceManagerIdentifier == Guid.Empty)
{
throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier));
}
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "TransactionManager.RecoveryComplete");
etwLog.TransactionManagerRecoveryComplete(resourceManagerIdentifier);
}
DistributedTransactionManager.ResourceManagerRecoveryComplete(resourceManagerIdentifier);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, "TransactionManager.RecoveryComplete");
}
}
// Object for synchronizing access to the entire class( avoiding lock( typeof( ... )) )
private static object? s_classSyncObject;
// Helper object for static synchronization
private static object ClassSyncObject => LazyInitializer.EnsureInitialized(ref s_classSyncObject);
internal static IsolationLevel DefaultIsolationLevel
{
get
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "TransactionManager.get_DefaultIsolationLevel");
etwLog.MethodExit(TraceSourceType.TraceSourceBase, "TransactionManager.get_DefaultIsolationLevel");
}
return IsolationLevel.Serializable;
}
}
private static DefaultSettingsSection? s_defaultSettings;
private static DefaultSettingsSection DefaultSettings
{
get
{
if (s_defaultSettings == null)
{
s_defaultSettings = DefaultSettingsSection.GetSection();
}
return s_defaultSettings;
}
}
private static MachineSettingsSection? s_machineSettings;
private static MachineSettingsSection MachineSettings
{
get
{
if (s_machineSettings == null)
{
s_machineSettings = MachineSettingsSection.GetSection();
}
return s_machineSettings;
}
}
private static bool s_defaultTimeoutValidated;
private static TimeSpan s_defaultTimeout;
public static TimeSpan DefaultTimeout
{
get
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "TransactionManager.get_DefaultTimeout");
}
if (!s_defaultTimeoutValidated)
{
s_defaultTimeout = ValidateTimeout(DefaultSettings.Timeout);
// If the timeout value got adjusted, it must have been greater than MaximumTimeout.
if (s_defaultTimeout != DefaultSettings.Timeout)
{
if (etwLog.IsEnabled())
{
etwLog.ConfiguredDefaultTimeoutAdjusted();
}
}
s_defaultTimeoutValidated = true;
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, "TransactionManager.get_DefaultTimeout");
}
return s_defaultTimeout;
}
}
private static bool s_cachedMaxTimeout;
private static TimeSpan s_maximumTimeout;
public static TimeSpan MaximumTimeout
{
get
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "TransactionManager.get_DefaultMaximumTimeout");
}
LazyInitializer.EnsureInitialized(ref s_maximumTimeout, ref s_cachedMaxTimeout, ref s_classSyncObject, () => MachineSettings.MaxTimeout);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, "TransactionManager.get_DefaultMaximumTimeout");
}
return s_maximumTimeout;
}
}
/// <summary>
/// This static function throws an ArgumentOutOfRange if the specified IsolationLevel is not within
/// the range of valid values.
/// </summary>
/// <param name="transactionIsolationLevel">
/// The IsolationLevel value to validate.
/// </param>
internal static void ValidateIsolationLevel(IsolationLevel transactionIsolationLevel)
{
switch (transactionIsolationLevel)
{
case IsolationLevel.Serializable:
case IsolationLevel.RepeatableRead:
case IsolationLevel.ReadCommitted:
case IsolationLevel.ReadUncommitted:
case IsolationLevel.Unspecified:
case IsolationLevel.Chaos:
case IsolationLevel.Snapshot:
break;
default:
throw new ArgumentOutOfRangeException(nameof(transactionIsolationLevel));
}
}
/// <summary>
/// This static function throws an ArgumentOutOfRange if the specified TimeSpan does not meet
/// requirements of a valid transaction timeout. Timeout values must be positive.
/// </summary>
/// <param name="transactionTimeout">
/// The TimeSpan value to validate.
/// </param>
internal static TimeSpan ValidateTimeout(TimeSpan transactionTimeout)
{
if (transactionTimeout < TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(transactionTimeout));
}
if (MaximumTimeout != TimeSpan.Zero)
{
if (transactionTimeout > MaximumTimeout || transactionTimeout == TimeSpan.Zero)
{
return MaximumTimeout;
}
}
return transactionTimeout;
}
internal static Transaction? FindPromotedTransaction(Guid transactionIdentifier)
{
Hashtable promotedTransactionTable = PromotedTransactionTable;
WeakReference? weakRef = (WeakReference?)promotedTransactionTable[transactionIdentifier];
if (null != weakRef)
{
if (weakRef.Target is Transaction tx)
{
return tx.InternalClone();
}
else // an old, moldy weak reference. Let's get rid of it.
{
lock (promotedTransactionTable)
{
promotedTransactionTable.Remove(transactionIdentifier);
}
}
}
return null;
}
internal static Transaction FindOrCreatePromotedTransaction(Guid transactionIdentifier, DistributedTransaction dtx)
{
Transaction? tx = null;
Hashtable promotedTransactionTable = PromotedTransactionTable;
lock (promotedTransactionTable)
{
WeakReference? weakRef = (WeakReference?)promotedTransactionTable[transactionIdentifier];
if (null != weakRef)
{
tx = weakRef.Target as Transaction;
if (null != tx)
{
// If we found a transaction then dispose it
dtx.Dispose();
return tx.InternalClone();
}
else
{
// an old, moldy weak reference. Let's get rid of it.
lock (promotedTransactionTable)
{
promotedTransactionTable.Remove(transactionIdentifier);
}
}
}
tx = new Transaction(dtx);
// Since we are adding this reference to the table create an object that will clean that entry up.
tx._internalTransaction._finalizedObject = new FinalizedObject(tx._internalTransaction, dtx.Identifier);
weakRef = new WeakReference(tx, false);
promotedTransactionTable[dtx.Identifier] = weakRef;
}
dtx.SavedLtmPromotedTransaction = tx;
FireDistributedTransactionStarted(tx);
return tx;
}
// Table for promoted transactions
internal static Hashtable PromotedTransactionTable =>
LazyInitializer.EnsureInitialized(ref s_promotedTransactionTable, ref s_classSyncObject, () => new Hashtable(100));
// Table for transaction timeouts
internal static TransactionTable TransactionTable =>
LazyInitializer.EnsureInitialized(ref s_transactionTable, ref s_classSyncObject, () => new TransactionTable());
// Fault in a DistributedTransactionManager if one has not already been created.
internal static DistributedTransactionManager? distributedTransactionManager;
internal static DistributedTransactionManager DistributedTransactionManager =>
// If the distributed transaction manager is not configured, throw an exception
LazyInitializer.EnsureInitialized(ref distributedTransactionManager, ref s_classSyncObject, () => new DistributedTransactionManager());
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/Methodical/flowgraph/bug619534/ehCodeMotion.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="ehCodeMotion.cs" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="ehCodeMotion.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/tracing/eventpipe/common/Microsoft.Diagnostics.NETCore.Client/NativeMethods.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 Microsoft.Win32.SafeHandles;
namespace Microsoft.Diagnostics.NETCore.Client
{
internal class NativeMethods
{
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool PeekNamedPipe(
SafePipeHandle hNamedPipe,
byte[] lpBuffer,
int bufferSize,
IntPtr lpBytesRead,
IntPtr lpTotalBytesAvail,
IntPtr lpBytesLeftThisMessage
);
}
}
|
// 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 Microsoft.Win32.SafeHandles;
namespace Microsoft.Diagnostics.NETCore.Client
{
internal class NativeMethods
{
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool PeekNamedPipe(
SafePipeHandle hNamedPipe,
byte[] lpBuffer,
int bufferSize,
IntPtr lpBytesRead,
IntPtr lpTotalBytesAvail,
IntPtr lpBytesLeftThisMessage
);
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/IL_Conformance/Old/Conformance_Base/ceq_r4.il
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
.assembly extern legacy library mscorlib {}
.class public _ceq {
.field public static float32 _inf
.field public static float32 _min
.field public static float32 _one
.field public static float32 _zero
.field public static float32 zero
.field public static float32 one
.field public static float32 max
.field public static float32 inf
.field public static float32 NaN
.method public static void initialize() {
.maxstack 10
ldc.r4 float32(0xFF800000)
stsfld float32 _ceq::_inf
ldc.r4 float32(0xFF7FFFFF)
stsfld float32 _ceq::_min
ldc.r4 float32(0xBF800000)
stsfld float32 _ceq::_one
ldc.r4 float32(0x80000000)
stsfld float32 _ceq::_zero
ldc.r4 float32(0x00000000)
stsfld float32 _ceq::zero
ldc.r4 float32(0x3F800000)
stsfld float32 _ceq::one
ldc.r4 float32(0x7F7FFFFF)
stsfld float32 _ceq::max
ldc.r4 float32(0x7F800000)
stsfld float32 _ceq::inf
ldc.r4 float32(0x7FC00000)
stsfld float32 _ceq::NaN
ret
}
.method public static int32 main(class [mscorlib]System.String[]) {
.entrypoint
.maxstack 10
call void _ceq::initialize()
ldsfld float32 _ceq::_inf
ldsfld float32 _ceq::_inf
ceq
brfalse FAIL
ldsfld float32 _ceq::_inf
ldsfld float32 _ceq::_min
ceq
brtrue FAIL
ldsfld float32 _ceq::_inf
ldsfld float32 _ceq::_one
ceq
brtrue FAIL
ldsfld float32 _ceq::_inf
ldsfld float32 _ceq::_zero
ceq
brtrue FAIL
ldsfld float32 _ceq::_inf
ldsfld float32 _ceq::zero
ceq
brtrue FAIL
ldsfld float32 _ceq::_inf
ldsfld float32 _ceq::one
ceq
brtrue FAIL
ldsfld float32 _ceq::_inf
ldsfld float32 _ceq::max
ceq
brtrue FAIL
ldsfld float32 _ceq::_inf
ldsfld float32 _ceq::inf
ceq
brtrue FAIL
ldsfld float32 _ceq::_inf
ldsfld float32 _ceq::NaN
ceq
brtrue FAIL
ldsfld float32 _ceq::_min
ldsfld float32 _ceq::_inf
ceq
brtrue FAIL
ldsfld float32 _ceq::_min
ldsfld float32 _ceq::_min
ceq
brfalse FAIL
ldsfld float32 _ceq::_min
ldsfld float32 _ceq::_one
ceq
brtrue FAIL
ldsfld float32 _ceq::_min
ldsfld float32 _ceq::_zero
ceq
brtrue FAIL
ldsfld float32 _ceq::_min
ldsfld float32 _ceq::zero
ceq
brtrue FAIL
ldsfld float32 _ceq::_min
ldsfld float32 _ceq::one
ceq
brtrue FAIL
ldsfld float32 _ceq::_min
ldsfld float32 _ceq::max
ceq
brtrue FAIL
ldsfld float32 _ceq::_min
ldsfld float32 _ceq::inf
ceq
brtrue FAIL
ldsfld float32 _ceq::_min
ldsfld float32 _ceq::NaN
ceq
brtrue FAIL
ldsfld float32 _ceq::_one
ldsfld float32 _ceq::_inf
ceq
brtrue FAIL
ldsfld float32 _ceq::_one
ldsfld float32 _ceq::_min
ceq
brtrue FAIL
ldsfld float32 _ceq::_one
ldsfld float32 _ceq::_one
ceq
brfalse FAIL
ldsfld float32 _ceq::_one
ldsfld float32 _ceq::_zero
ceq
brtrue FAIL
ldsfld float32 _ceq::_one
ldsfld float32 _ceq::zero
ceq
brtrue FAIL
ldsfld float32 _ceq::_one
ldsfld float32 _ceq::one
ceq
brtrue FAIL
ldsfld float32 _ceq::_one
ldsfld float32 _ceq::max
ceq
brtrue FAIL
ldsfld float32 _ceq::_one
ldsfld float32 _ceq::inf
ceq
brtrue FAIL
ldsfld float32 _ceq::_one
ldsfld float32 _ceq::NaN
ceq
brtrue FAIL
ldsfld float32 _ceq::_zero
ldsfld float32 _ceq::_inf
ceq
brtrue FAIL
ldsfld float32 _ceq::_zero
ldsfld float32 _ceq::_min
ceq
brtrue FAIL
ldsfld float32 _ceq::_zero
ldsfld float32 _ceq::_one
ceq
brtrue FAIL
ldsfld float32 _ceq::_zero
ldsfld float32 _ceq::_zero
ceq
brfalse FAIL
ldsfld float32 _ceq::_zero
ldsfld float32 _ceq::zero
ceq
brfalse FAIL
ldsfld float32 _ceq::_zero
ldsfld float32 _ceq::one
ceq
brtrue FAIL
ldsfld float32 _ceq::_zero
ldsfld float32 _ceq::max
ceq
brtrue FAIL
ldsfld float32 _ceq::_zero
ldsfld float32 _ceq::inf
ceq
brtrue FAIL
ldsfld float32 _ceq::_zero
ldsfld float32 _ceq::NaN
ceq
brtrue FAIL
ldsfld float32 _ceq::zero
ldsfld float32 _ceq::_inf
ceq
brtrue FAIL
ldsfld float32 _ceq::zero
ldsfld float32 _ceq::_min
ceq
brtrue FAIL
ldsfld float32 _ceq::zero
ldsfld float32 _ceq::_one
ceq
brtrue FAIL
ldsfld float32 _ceq::zero
ldsfld float32 _ceq::_zero
ceq
brfalse FAIL
ldsfld float32 _ceq::zero
ldsfld float32 _ceq::zero
ceq
brfalse FAIL
ldsfld float32 _ceq::zero
ldsfld float32 _ceq::one
ceq
brtrue FAIL
ldsfld float32 _ceq::zero
ldsfld float32 _ceq::max
ceq
brtrue FAIL
ldsfld float32 _ceq::zero
ldsfld float32 _ceq::inf
ceq
brtrue FAIL
ldsfld float32 _ceq::zero
ldsfld float32 _ceq::NaN
ceq
brtrue FAIL
ldsfld float32 _ceq::one
ldsfld float32 _ceq::_inf
ceq
brtrue FAIL
ldsfld float32 _ceq::one
ldsfld float32 _ceq::_min
ceq
brtrue FAIL
ldsfld float32 _ceq::one
ldsfld float32 _ceq::_one
ceq
brtrue FAIL
ldsfld float32 _ceq::one
ldsfld float32 _ceq::_zero
ceq
brtrue FAIL
ldsfld float32 _ceq::one
ldsfld float32 _ceq::zero
ceq
brtrue FAIL
ldsfld float32 _ceq::one
ldsfld float32 _ceq::one
ceq
brfalse FAIL
ldsfld float32 _ceq::one
ldsfld float32 _ceq::max
ceq
brtrue FAIL
ldsfld float32 _ceq::one
ldsfld float32 _ceq::inf
ceq
brtrue FAIL
ldsfld float32 _ceq::one
ldsfld float32 _ceq::NaN
ceq
brtrue FAIL
ldsfld float32 _ceq::max
ldsfld float32 _ceq::_inf
ceq
brtrue FAIL
ldsfld float32 _ceq::max
ldsfld float32 _ceq::_min
ceq
brtrue FAIL
ldsfld float32 _ceq::max
ldsfld float32 _ceq::_one
ceq
brtrue FAIL
ldsfld float32 _ceq::max
ldsfld float32 _ceq::_zero
ceq
brtrue FAIL
ldsfld float32 _ceq::max
ldsfld float32 _ceq::zero
ceq
brtrue FAIL
ldsfld float32 _ceq::max
ldsfld float32 _ceq::one
ceq
brtrue FAIL
ldsfld float32 _ceq::max
ldsfld float32 _ceq::max
ceq
brfalse FAIL
ldsfld float32 _ceq::max
ldsfld float32 _ceq::inf
ceq
brtrue FAIL
ldsfld float32 _ceq::max
ldsfld float32 _ceq::NaN
ceq
brtrue FAIL
ldsfld float32 _ceq::inf
ldsfld float32 _ceq::_inf
ceq
brtrue FAIL
ldsfld float32 _ceq::inf
ldsfld float32 _ceq::_min
ceq
brtrue FAIL
ldsfld float32 _ceq::inf
ldsfld float32 _ceq::_one
ceq
brtrue FAIL
ldsfld float32 _ceq::inf
ldsfld float32 _ceq::_zero
ceq
brtrue FAIL
ldsfld float32 _ceq::inf
ldsfld float32 _ceq::zero
ceq
brtrue FAIL
ldsfld float32 _ceq::inf
ldsfld float32 _ceq::one
ceq
brtrue FAIL
ldsfld float32 _ceq::inf
ldsfld float32 _ceq::max
ceq
brtrue FAIL
ldsfld float32 _ceq::inf
ldsfld float32 _ceq::inf
ceq
brfalse FAIL
ldsfld float32 _ceq::inf
ldsfld float32 _ceq::NaN
ceq
brtrue FAIL
ldsfld float32 _ceq::NaN
ldsfld float32 _ceq::_inf
ceq
brtrue FAIL
ldsfld float32 _ceq::NaN
ldsfld float32 _ceq::_min
ceq
brtrue FAIL
ldsfld float32 _ceq::NaN
ldsfld float32 _ceq::_one
ceq
brtrue FAIL
ldsfld float32 _ceq::NaN
ldsfld float32 _ceq::_zero
ceq
brtrue FAIL
ldsfld float32 _ceq::NaN
ldsfld float32 _ceq::zero
ceq
brtrue FAIL
ldsfld float32 _ceq::NaN
ldsfld float32 _ceq::one
ceq
brtrue FAIL
ldsfld float32 _ceq::NaN
ldsfld float32 _ceq::max
ceq
brtrue FAIL
ldsfld float32 _ceq::NaN
ldsfld float32 _ceq::inf
ceq
brtrue FAIL
ldsfld float32 _ceq::NaN
ldsfld float32 _ceq::NaN
ceq
brtrue FAIL
ldc.i4 100
ret
FAIL:
ldc.i4 0x0
ret
}
}
.assembly ceq_r4{}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
.assembly extern legacy library mscorlib {}
.class public _ceq {
.field public static float32 _inf
.field public static float32 _min
.field public static float32 _one
.field public static float32 _zero
.field public static float32 zero
.field public static float32 one
.field public static float32 max
.field public static float32 inf
.field public static float32 NaN
.method public static void initialize() {
.maxstack 10
ldc.r4 float32(0xFF800000)
stsfld float32 _ceq::_inf
ldc.r4 float32(0xFF7FFFFF)
stsfld float32 _ceq::_min
ldc.r4 float32(0xBF800000)
stsfld float32 _ceq::_one
ldc.r4 float32(0x80000000)
stsfld float32 _ceq::_zero
ldc.r4 float32(0x00000000)
stsfld float32 _ceq::zero
ldc.r4 float32(0x3F800000)
stsfld float32 _ceq::one
ldc.r4 float32(0x7F7FFFFF)
stsfld float32 _ceq::max
ldc.r4 float32(0x7F800000)
stsfld float32 _ceq::inf
ldc.r4 float32(0x7FC00000)
stsfld float32 _ceq::NaN
ret
}
.method public static int32 main(class [mscorlib]System.String[]) {
.entrypoint
.maxstack 10
call void _ceq::initialize()
ldsfld float32 _ceq::_inf
ldsfld float32 _ceq::_inf
ceq
brfalse FAIL
ldsfld float32 _ceq::_inf
ldsfld float32 _ceq::_min
ceq
brtrue FAIL
ldsfld float32 _ceq::_inf
ldsfld float32 _ceq::_one
ceq
brtrue FAIL
ldsfld float32 _ceq::_inf
ldsfld float32 _ceq::_zero
ceq
brtrue FAIL
ldsfld float32 _ceq::_inf
ldsfld float32 _ceq::zero
ceq
brtrue FAIL
ldsfld float32 _ceq::_inf
ldsfld float32 _ceq::one
ceq
brtrue FAIL
ldsfld float32 _ceq::_inf
ldsfld float32 _ceq::max
ceq
brtrue FAIL
ldsfld float32 _ceq::_inf
ldsfld float32 _ceq::inf
ceq
brtrue FAIL
ldsfld float32 _ceq::_inf
ldsfld float32 _ceq::NaN
ceq
brtrue FAIL
ldsfld float32 _ceq::_min
ldsfld float32 _ceq::_inf
ceq
brtrue FAIL
ldsfld float32 _ceq::_min
ldsfld float32 _ceq::_min
ceq
brfalse FAIL
ldsfld float32 _ceq::_min
ldsfld float32 _ceq::_one
ceq
brtrue FAIL
ldsfld float32 _ceq::_min
ldsfld float32 _ceq::_zero
ceq
brtrue FAIL
ldsfld float32 _ceq::_min
ldsfld float32 _ceq::zero
ceq
brtrue FAIL
ldsfld float32 _ceq::_min
ldsfld float32 _ceq::one
ceq
brtrue FAIL
ldsfld float32 _ceq::_min
ldsfld float32 _ceq::max
ceq
brtrue FAIL
ldsfld float32 _ceq::_min
ldsfld float32 _ceq::inf
ceq
brtrue FAIL
ldsfld float32 _ceq::_min
ldsfld float32 _ceq::NaN
ceq
brtrue FAIL
ldsfld float32 _ceq::_one
ldsfld float32 _ceq::_inf
ceq
brtrue FAIL
ldsfld float32 _ceq::_one
ldsfld float32 _ceq::_min
ceq
brtrue FAIL
ldsfld float32 _ceq::_one
ldsfld float32 _ceq::_one
ceq
brfalse FAIL
ldsfld float32 _ceq::_one
ldsfld float32 _ceq::_zero
ceq
brtrue FAIL
ldsfld float32 _ceq::_one
ldsfld float32 _ceq::zero
ceq
brtrue FAIL
ldsfld float32 _ceq::_one
ldsfld float32 _ceq::one
ceq
brtrue FAIL
ldsfld float32 _ceq::_one
ldsfld float32 _ceq::max
ceq
brtrue FAIL
ldsfld float32 _ceq::_one
ldsfld float32 _ceq::inf
ceq
brtrue FAIL
ldsfld float32 _ceq::_one
ldsfld float32 _ceq::NaN
ceq
brtrue FAIL
ldsfld float32 _ceq::_zero
ldsfld float32 _ceq::_inf
ceq
brtrue FAIL
ldsfld float32 _ceq::_zero
ldsfld float32 _ceq::_min
ceq
brtrue FAIL
ldsfld float32 _ceq::_zero
ldsfld float32 _ceq::_one
ceq
brtrue FAIL
ldsfld float32 _ceq::_zero
ldsfld float32 _ceq::_zero
ceq
brfalse FAIL
ldsfld float32 _ceq::_zero
ldsfld float32 _ceq::zero
ceq
brfalse FAIL
ldsfld float32 _ceq::_zero
ldsfld float32 _ceq::one
ceq
brtrue FAIL
ldsfld float32 _ceq::_zero
ldsfld float32 _ceq::max
ceq
brtrue FAIL
ldsfld float32 _ceq::_zero
ldsfld float32 _ceq::inf
ceq
brtrue FAIL
ldsfld float32 _ceq::_zero
ldsfld float32 _ceq::NaN
ceq
brtrue FAIL
ldsfld float32 _ceq::zero
ldsfld float32 _ceq::_inf
ceq
brtrue FAIL
ldsfld float32 _ceq::zero
ldsfld float32 _ceq::_min
ceq
brtrue FAIL
ldsfld float32 _ceq::zero
ldsfld float32 _ceq::_one
ceq
brtrue FAIL
ldsfld float32 _ceq::zero
ldsfld float32 _ceq::_zero
ceq
brfalse FAIL
ldsfld float32 _ceq::zero
ldsfld float32 _ceq::zero
ceq
brfalse FAIL
ldsfld float32 _ceq::zero
ldsfld float32 _ceq::one
ceq
brtrue FAIL
ldsfld float32 _ceq::zero
ldsfld float32 _ceq::max
ceq
brtrue FAIL
ldsfld float32 _ceq::zero
ldsfld float32 _ceq::inf
ceq
brtrue FAIL
ldsfld float32 _ceq::zero
ldsfld float32 _ceq::NaN
ceq
brtrue FAIL
ldsfld float32 _ceq::one
ldsfld float32 _ceq::_inf
ceq
brtrue FAIL
ldsfld float32 _ceq::one
ldsfld float32 _ceq::_min
ceq
brtrue FAIL
ldsfld float32 _ceq::one
ldsfld float32 _ceq::_one
ceq
brtrue FAIL
ldsfld float32 _ceq::one
ldsfld float32 _ceq::_zero
ceq
brtrue FAIL
ldsfld float32 _ceq::one
ldsfld float32 _ceq::zero
ceq
brtrue FAIL
ldsfld float32 _ceq::one
ldsfld float32 _ceq::one
ceq
brfalse FAIL
ldsfld float32 _ceq::one
ldsfld float32 _ceq::max
ceq
brtrue FAIL
ldsfld float32 _ceq::one
ldsfld float32 _ceq::inf
ceq
brtrue FAIL
ldsfld float32 _ceq::one
ldsfld float32 _ceq::NaN
ceq
brtrue FAIL
ldsfld float32 _ceq::max
ldsfld float32 _ceq::_inf
ceq
brtrue FAIL
ldsfld float32 _ceq::max
ldsfld float32 _ceq::_min
ceq
brtrue FAIL
ldsfld float32 _ceq::max
ldsfld float32 _ceq::_one
ceq
brtrue FAIL
ldsfld float32 _ceq::max
ldsfld float32 _ceq::_zero
ceq
brtrue FAIL
ldsfld float32 _ceq::max
ldsfld float32 _ceq::zero
ceq
brtrue FAIL
ldsfld float32 _ceq::max
ldsfld float32 _ceq::one
ceq
brtrue FAIL
ldsfld float32 _ceq::max
ldsfld float32 _ceq::max
ceq
brfalse FAIL
ldsfld float32 _ceq::max
ldsfld float32 _ceq::inf
ceq
brtrue FAIL
ldsfld float32 _ceq::max
ldsfld float32 _ceq::NaN
ceq
brtrue FAIL
ldsfld float32 _ceq::inf
ldsfld float32 _ceq::_inf
ceq
brtrue FAIL
ldsfld float32 _ceq::inf
ldsfld float32 _ceq::_min
ceq
brtrue FAIL
ldsfld float32 _ceq::inf
ldsfld float32 _ceq::_one
ceq
brtrue FAIL
ldsfld float32 _ceq::inf
ldsfld float32 _ceq::_zero
ceq
brtrue FAIL
ldsfld float32 _ceq::inf
ldsfld float32 _ceq::zero
ceq
brtrue FAIL
ldsfld float32 _ceq::inf
ldsfld float32 _ceq::one
ceq
brtrue FAIL
ldsfld float32 _ceq::inf
ldsfld float32 _ceq::max
ceq
brtrue FAIL
ldsfld float32 _ceq::inf
ldsfld float32 _ceq::inf
ceq
brfalse FAIL
ldsfld float32 _ceq::inf
ldsfld float32 _ceq::NaN
ceq
brtrue FAIL
ldsfld float32 _ceq::NaN
ldsfld float32 _ceq::_inf
ceq
brtrue FAIL
ldsfld float32 _ceq::NaN
ldsfld float32 _ceq::_min
ceq
brtrue FAIL
ldsfld float32 _ceq::NaN
ldsfld float32 _ceq::_one
ceq
brtrue FAIL
ldsfld float32 _ceq::NaN
ldsfld float32 _ceq::_zero
ceq
brtrue FAIL
ldsfld float32 _ceq::NaN
ldsfld float32 _ceq::zero
ceq
brtrue FAIL
ldsfld float32 _ceq::NaN
ldsfld float32 _ceq::one
ceq
brtrue FAIL
ldsfld float32 _ceq::NaN
ldsfld float32 _ceq::max
ceq
brtrue FAIL
ldsfld float32 _ceq::NaN
ldsfld float32 _ceq::inf
ceq
brtrue FAIL
ldsfld float32 _ceq::NaN
ldsfld float32 _ceq::NaN
ceq
brtrue FAIL
ldc.i4 100
ret
FAIL:
ldc.i4 0x0
ret
}
}
.assembly ceq_r4{}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest86/Generated86.ilproj
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="Generated86.il" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TestFramework\TestFramework.csproj" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="Generated86.il" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TestFramework\TestFramework.csproj" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/IfAction.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Xml.Xsl.XsltOld
{
using System;
using System.Diagnostics;
using System.Xml;
using System.Xml.XPath;
internal class IfAction : ContainerAction
{
internal enum ConditionType
{
ConditionIf,
ConditionWhen,
ConditionOtherwise
}
private readonly ConditionType _type;
private int _testKey = Compiler.InvalidQueryKey;
internal IfAction(ConditionType type)
{
_type = type;
}
internal override void Compile(Compiler compiler)
{
CompileAttributes(compiler);
if (_type != ConditionType.ConditionOtherwise)
{
CheckRequiredAttribute(compiler, _testKey != Compiler.InvalidQueryKey, "test");
}
if (compiler.Recurse())
{
CompileTemplate(compiler);
compiler.ToParent();
}
}
internal override bool CompileAttribute(Compiler compiler)
{
string name = compiler.Input.LocalName;
string value = compiler.Input.Value;
if (Ref.Equal(name, compiler.Atoms.Test))
{
if (_type == ConditionType.ConditionOtherwise)
{
return false;
}
_testKey = compiler.AddBooleanQuery(value);
}
else
{
return false;
}
return true;
}
internal override void Execute(Processor processor, ActionFrame frame)
{
Debug.Assert(processor != null && frame != null);
switch (frame.State)
{
case Initialized:
if (_type == ConditionType.ConditionIf || _type == ConditionType.ConditionWhen)
{
Debug.Assert(_testKey != Compiler.InvalidQueryKey);
bool value = processor.EvaluateBoolean(frame, _testKey);
if (value == false)
{
frame.Finished();
break;
}
}
processor.PushActionFrame(frame);
frame.State = ProcessingChildren;
break; // Allow children to run
case ProcessingChildren:
if (_type == ConditionType.ConditionWhen || _type == ConditionType.ConditionOtherwise)
{
Debug.Assert(frame.Container != null);
frame.Exit();
}
frame.Finished();
break;
default:
Debug.Fail("Invalid IfAction execution state");
break;
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Xml.Xsl.XsltOld
{
using System;
using System.Diagnostics;
using System.Xml;
using System.Xml.XPath;
internal class IfAction : ContainerAction
{
internal enum ConditionType
{
ConditionIf,
ConditionWhen,
ConditionOtherwise
}
private readonly ConditionType _type;
private int _testKey = Compiler.InvalidQueryKey;
internal IfAction(ConditionType type)
{
_type = type;
}
internal override void Compile(Compiler compiler)
{
CompileAttributes(compiler);
if (_type != ConditionType.ConditionOtherwise)
{
CheckRequiredAttribute(compiler, _testKey != Compiler.InvalidQueryKey, "test");
}
if (compiler.Recurse())
{
CompileTemplate(compiler);
compiler.ToParent();
}
}
internal override bool CompileAttribute(Compiler compiler)
{
string name = compiler.Input.LocalName;
string value = compiler.Input.Value;
if (Ref.Equal(name, compiler.Atoms.Test))
{
if (_type == ConditionType.ConditionOtherwise)
{
return false;
}
_testKey = compiler.AddBooleanQuery(value);
}
else
{
return false;
}
return true;
}
internal override void Execute(Processor processor, ActionFrame frame)
{
Debug.Assert(processor != null && frame != null);
switch (frame.State)
{
case Initialized:
if (_type == ConditionType.ConditionIf || _type == ConditionType.ConditionWhen)
{
Debug.Assert(_testKey != Compiler.InvalidQueryKey);
bool value = processor.EvaluateBoolean(frame, _testKey);
if (value == false)
{
frame.Finished();
break;
}
}
processor.PushActionFrame(frame);
frame.State = ProcessingChildren;
break; // Allow children to run
case ProcessingChildren:
if (_type == ConditionType.ConditionWhen || _type == ConditionType.ConditionOtherwise)
{
Debug.Assert(frame.Container != null);
frame.Exit();
}
frame.Finished();
break;
default:
Debug.Fail("Invalid IfAction execution state");
break;
}
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/GC/Scenarios/GCSimulator/GCSimulator_135.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<GCStressIncompatible>true</GCStressIncompatible>
<CLRTestExecutionArguments>-t 1 -tp 0 -dz 17 -sdz 8517 -dc 10000 -sdc 5000 -lt 3 -f -dp 0.4 -dw 0.4</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 8517 -dc 10000 -sdc 5000 -lt 3 -f -dp 0.4 -dw 0.4</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,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/coreclr/nativeaot/Runtime/arm64/AllocFast.S
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include <unixasmmacros.inc>
#include "AsmOffsets.inc"
// GC type flags
GC_ALLOC_FINALIZE = 1
//
// Rename fields of nested structs
//
OFFSETOF__Thread__m_alloc_context__alloc_ptr = OFFSETOF__Thread__m_rgbAllocContextBuffer + OFFSETOF__gc_alloc_context__alloc_ptr
OFFSETOF__Thread__m_alloc_context__alloc_limit = OFFSETOF__Thread__m_rgbAllocContextBuffer + OFFSETOF__gc_alloc_context__alloc_limit
// Allocate non-array, non-finalizable object. If the allocation doesn't fit into the current thread's
// allocation context then automatically fallback to the slow allocation path.
// x0 == MethodTable
LEAF_ENTRY RhpNewFast, _TEXT
// x1 = GetThread()
#ifdef FEATURE_EMULATED_TLS
GETTHREAD_ETLS_1
#else
INLINE_GETTHREAD x1
#endif
//
// x0 contains MethodTable pointer
//
ldr w2, [x0, #OFFSETOF__MethodTable__m_uBaseSize]
//
// x0: MethodTable pointer
// x1: Thread pointer
// x2: base size
//
// Load potential new object address into x12.
ldr x12, [x1, #OFFSETOF__Thread__m_alloc_context__alloc_ptr]
// Determine whether the end of the object would lie outside of the current allocation context. If so,
// we abandon the attempt to allocate the object directly and fall back to the slow helper.
add x2, x2, x12
ldr x13, [x1, #OFFSETOF__Thread__m_alloc_context__alloc_limit]
cmp x2, x13
bhi RhpNewFast_RarePath
// Update the alloc pointer to account for the allocation.
str x2, [x1, #OFFSETOF__Thread__m_alloc_context__alloc_ptr]
// Set the new objects MethodTable pointer
str x0, [x12, #OFFSETOF__Object__m_pEEType]
mov x0, x12
ret
RhpNewFast_RarePath:
mov x1, #0
b RhpNewObject
LEAF_END RhpNewFast, _TEXT
// Allocate non-array object with finalizer.
// x0 == MethodTable
LEAF_ENTRY RhpNewFinalizable, _TEXT
mov x1, #GC_ALLOC_FINALIZE
b RhpNewObject
LEAF_END RhpNewFinalizable, _TEXT
// Allocate non-array object.
// x0 == MethodTable
// x1 == alloc flags
NESTED_ENTRY RhpNewObject, _TEXT, NoHandler
PUSH_COOP_PINVOKE_FRAME x3
// x3: transition frame
// Preserve the MethodTable in x19
mov x19, x0
mov w2, 0 // numElements
// Call the rest of the allocation helper.
// void* RhpGcAlloc(MethodTable *pEEType, uint32_t uFlags, uintptr_t numElements, void * pTransitionFrame)
bl RhpGcAlloc
// Set the new objects MethodTable pointer on success.
cbz x0, NewOutOfMemory
POP_COOP_PINVOKE_FRAME
EPILOG_RETURN
NewOutOfMemory:
// This is the OOM failure path. We are going to tail-call to a managed helper that will throw
// an out of memory exception that the caller of this allocator understands.
mov x0, x19 // MethodTable pointer
mov x1, 0 // Indicate that we should throw OOM.
POP_COOP_PINVOKE_FRAME
b RhExceptionHandling_FailedAllocation
NESTED_END RhpNewObject, _TEXT
// Allocate a string.
// x0 == MethodTable
// x1 == element/character count
LEAF_ENTRY RhNewString, _TEXT
// Make sure computing the overall allocation size wont overflow
movz x2, MAX_STRING_LENGTH & 0xFFFF
movk x2, MAX_STRING_LENGTH >> 16, lsl 16
cmp x1, x2
bhi StringSizeOverflow
// Compute overall allocation size (align(base size + (element size * elements), 8)).
mov w2, #STRING_COMPONENT_SIZE
mov x3, #(STRING_BASE_SIZE + 7)
umaddl x2, w1, w2, x3 // x2 = w1 * w2 + x3
and x2, x2, #-8
// x0 == MethodTable
// x1 == element count
// x2 == string size
#ifdef FEATURE_EMULATED_TLS
GETTHREAD_ETLS_3
#else
INLINE_GETTHREAD x3
#endif
// Load potential new object address into x12.
ldr x12, [x3, #OFFSETOF__Thread__m_alloc_context__alloc_ptr]
// Determine whether the end of the object would lie outside of the current allocation context. If so,
// we abandon the attempt to allocate the object directly and fall back to the slow helper.
add x2, x2, x12
ldr x12, [x3, #OFFSETOF__Thread__m_alloc_context__alloc_limit]
cmp x2, x12
bhi RhpNewArrayRare
// Reload new object address into r12.
ldr x12, [x3, #OFFSETOF__Thread__m_alloc_context__alloc_ptr]
// Update the alloc pointer to account for the allocation.
str x2, [x3, #OFFSETOF__Thread__m_alloc_context__alloc_ptr]
// Set the new objects MethodTable pointer and element count.
str x0, [x12, #OFFSETOF__Object__m_pEEType]
str x1, [x12, #OFFSETOF__Array__m_Length]
// Return the object allocated in x0.
mov x0, x12
ret
StringSizeOverflow:
// We get here if the length of the final string object can not be represented as an unsigned
// 32-bit value. We are going to tail-call to a managed helper that will throw
// an OOM exception that the caller of this allocator understands.
// x0 holds MethodTable pointer already
mov x1, #1 // Indicate that we should throw OverflowException
b RhExceptionHandling_FailedAllocation
LEAF_END RhNewString, _Text
// Allocate one dimensional, zero based array (SZARRAY).
// x0 == MethodTable
// x1 == element count
LEAF_ENTRY RhpNewArray, _Text
// We want to limit the element count to the non-negative 32-bit int range.
// If the element count is <= 0x7FFFFFFF, no overflow is possible because the component
// size is <= 0xffff (it is an unsigned 16-bit value), and the base size for the worst
// case (32 dimensional MdArray) is less than 0xffff, and thus the product fits in 64 bits.
mov x2, #0x7FFFFFFF
cmp x1, x2
bhi ArraySizeOverflow
ldrh w2, [x0, #OFFSETOF__MethodTable__m_usComponentSize]
umull x2, w1, w2
ldr w3, [x0, #OFFSETOF__MethodTable__m_uBaseSize]
add x2, x2, x3
add x2, x2, #7
and x2, x2, #-8
// x0 == MethodTable
// x1 == element count
// x2 == array size
#ifdef FEATURE_EMULATED_TLS
GETTHREAD_ETLS_3
#else
INLINE_GETTHREAD x3
#endif
// Load potential new object address into x12.
ldr x12, [x3, #OFFSETOF__Thread__m_alloc_context__alloc_ptr]
// Determine whether the end of the object would lie outside of the current allocation context. If so,
// we abandon the attempt to allocate the object directly and fall back to the slow helper.
add x2, x2, x12
ldr x12, [x3, #OFFSETOF__Thread__m_alloc_context__alloc_limit]
cmp x2, x12
bhi RhpNewArrayRare
// Reload new object address into x12.
ldr x12, [x3, #OFFSETOF__Thread__m_alloc_context__alloc_ptr]
// Update the alloc pointer to account for the allocation.
str x2, [x3, #OFFSETOF__Thread__m_alloc_context__alloc_ptr]
// Set the new objects MethodTable pointer and element count.
str x0, [x12, #OFFSETOF__Object__m_pEEType]
str x1, [x12, #OFFSETOF__Array__m_Length]
// Return the object allocated in r0.
mov x0, x12
ret
ArraySizeOverflow:
// We get here if the size of the final array object can not be represented as an unsigned
// 32-bit value. We are going to tail-call to a managed helper that will throw
// an overflow exception that the caller of this allocator understands.
// x0 holds MethodTable pointer already
mov x1, #1 // Indicate that we should throw OverflowException
b RhExceptionHandling_FailedAllocation
LEAF_END RhpNewArray, _TEXT
// Allocate one dimensional, zero based array (SZARRAY) using the slow path that calls a runtime helper.
// x0 == MethodTable
// x1 == element count
// x2 == array size + Thread::m_alloc_context::alloc_ptr
// x3 == Thread
NESTED_ENTRY RhpNewArrayRare, _TEXT, NoHandler
// Recover array size by subtracting the alloc_ptr from x2.
ldr x12, [x3, #OFFSETOF__Thread__m_alloc_context__alloc_ptr]
sub x2, x2, x12
PUSH_COOP_PINVOKE_FRAME x3
// Preserve data we will need later into the callee saved registers
mov x19, x0 // Preserve MethodTable
mov x2, x1 // numElements
mov x1, #0 // uFlags
// void* RhpGcAlloc(MethodTable *pEEType, uint32_t uFlags, uintptr_t numElements, void * pTransitionFrame)
bl RhpGcAlloc
// Set the new objects MethodTable pointer and length on success.
cbz x0, ArrayOutOfMemory
POP_COOP_PINVOKE_FRAME
EPILOG_RETURN
ArrayOutOfMemory:
// This is the OOM failure path. We are going to tail-call to a managed helper that will throw
// an out of memory exception that the caller of this allocator understands.
mov x0, x19 // MethodTable Pointer
mov x1, 0 // Indicate that we should throw OOM.
POP_COOP_PINVOKE_FRAME
b RhExceptionHandling_FailedAllocation
NESTED_END RhpNewArrayRare, _TEXT
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include <unixasmmacros.inc>
#include "AsmOffsets.inc"
// GC type flags
GC_ALLOC_FINALIZE = 1
//
// Rename fields of nested structs
//
OFFSETOF__Thread__m_alloc_context__alloc_ptr = OFFSETOF__Thread__m_rgbAllocContextBuffer + OFFSETOF__gc_alloc_context__alloc_ptr
OFFSETOF__Thread__m_alloc_context__alloc_limit = OFFSETOF__Thread__m_rgbAllocContextBuffer + OFFSETOF__gc_alloc_context__alloc_limit
// Allocate non-array, non-finalizable object. If the allocation doesn't fit into the current thread's
// allocation context then automatically fallback to the slow allocation path.
// x0 == MethodTable
LEAF_ENTRY RhpNewFast, _TEXT
// x1 = GetThread()
#ifdef FEATURE_EMULATED_TLS
GETTHREAD_ETLS_1
#else
INLINE_GETTHREAD x1
#endif
//
// x0 contains MethodTable pointer
//
ldr w2, [x0, #OFFSETOF__MethodTable__m_uBaseSize]
//
// x0: MethodTable pointer
// x1: Thread pointer
// x2: base size
//
// Load potential new object address into x12.
ldr x12, [x1, #OFFSETOF__Thread__m_alloc_context__alloc_ptr]
// Determine whether the end of the object would lie outside of the current allocation context. If so,
// we abandon the attempt to allocate the object directly and fall back to the slow helper.
add x2, x2, x12
ldr x13, [x1, #OFFSETOF__Thread__m_alloc_context__alloc_limit]
cmp x2, x13
bhi RhpNewFast_RarePath
// Update the alloc pointer to account for the allocation.
str x2, [x1, #OFFSETOF__Thread__m_alloc_context__alloc_ptr]
// Set the new objects MethodTable pointer
str x0, [x12, #OFFSETOF__Object__m_pEEType]
mov x0, x12
ret
RhpNewFast_RarePath:
mov x1, #0
b RhpNewObject
LEAF_END RhpNewFast, _TEXT
// Allocate non-array object with finalizer.
// x0 == MethodTable
LEAF_ENTRY RhpNewFinalizable, _TEXT
mov x1, #GC_ALLOC_FINALIZE
b RhpNewObject
LEAF_END RhpNewFinalizable, _TEXT
// Allocate non-array object.
// x0 == MethodTable
// x1 == alloc flags
NESTED_ENTRY RhpNewObject, _TEXT, NoHandler
PUSH_COOP_PINVOKE_FRAME x3
// x3: transition frame
// Preserve the MethodTable in x19
mov x19, x0
mov w2, 0 // numElements
// Call the rest of the allocation helper.
// void* RhpGcAlloc(MethodTable *pEEType, uint32_t uFlags, uintptr_t numElements, void * pTransitionFrame)
bl RhpGcAlloc
// Set the new objects MethodTable pointer on success.
cbz x0, NewOutOfMemory
POP_COOP_PINVOKE_FRAME
EPILOG_RETURN
NewOutOfMemory:
// This is the OOM failure path. We are going to tail-call to a managed helper that will throw
// an out of memory exception that the caller of this allocator understands.
mov x0, x19 // MethodTable pointer
mov x1, 0 // Indicate that we should throw OOM.
POP_COOP_PINVOKE_FRAME
b RhExceptionHandling_FailedAllocation
NESTED_END RhpNewObject, _TEXT
// Allocate a string.
// x0 == MethodTable
// x1 == element/character count
LEAF_ENTRY RhNewString, _TEXT
// Make sure computing the overall allocation size wont overflow
movz x2, MAX_STRING_LENGTH & 0xFFFF
movk x2, MAX_STRING_LENGTH >> 16, lsl 16
cmp x1, x2
bhi StringSizeOverflow
// Compute overall allocation size (align(base size + (element size * elements), 8)).
mov w2, #STRING_COMPONENT_SIZE
mov x3, #(STRING_BASE_SIZE + 7)
umaddl x2, w1, w2, x3 // x2 = w1 * w2 + x3
and x2, x2, #-8
// x0 == MethodTable
// x1 == element count
// x2 == string size
#ifdef FEATURE_EMULATED_TLS
GETTHREAD_ETLS_3
#else
INLINE_GETTHREAD x3
#endif
// Load potential new object address into x12.
ldr x12, [x3, #OFFSETOF__Thread__m_alloc_context__alloc_ptr]
// Determine whether the end of the object would lie outside of the current allocation context. If so,
// we abandon the attempt to allocate the object directly and fall back to the slow helper.
add x2, x2, x12
ldr x12, [x3, #OFFSETOF__Thread__m_alloc_context__alloc_limit]
cmp x2, x12
bhi RhpNewArrayRare
// Reload new object address into r12.
ldr x12, [x3, #OFFSETOF__Thread__m_alloc_context__alloc_ptr]
// Update the alloc pointer to account for the allocation.
str x2, [x3, #OFFSETOF__Thread__m_alloc_context__alloc_ptr]
// Set the new objects MethodTable pointer and element count.
str x0, [x12, #OFFSETOF__Object__m_pEEType]
str x1, [x12, #OFFSETOF__Array__m_Length]
// Return the object allocated in x0.
mov x0, x12
ret
StringSizeOverflow:
// We get here if the length of the final string object can not be represented as an unsigned
// 32-bit value. We are going to tail-call to a managed helper that will throw
// an OOM exception that the caller of this allocator understands.
// x0 holds MethodTable pointer already
mov x1, #1 // Indicate that we should throw OverflowException
b RhExceptionHandling_FailedAllocation
LEAF_END RhNewString, _Text
// Allocate one dimensional, zero based array (SZARRAY).
// x0 == MethodTable
// x1 == element count
LEAF_ENTRY RhpNewArray, _Text
// We want to limit the element count to the non-negative 32-bit int range.
// If the element count is <= 0x7FFFFFFF, no overflow is possible because the component
// size is <= 0xffff (it is an unsigned 16-bit value), and the base size for the worst
// case (32 dimensional MdArray) is less than 0xffff, and thus the product fits in 64 bits.
mov x2, #0x7FFFFFFF
cmp x1, x2
bhi ArraySizeOverflow
ldrh w2, [x0, #OFFSETOF__MethodTable__m_usComponentSize]
umull x2, w1, w2
ldr w3, [x0, #OFFSETOF__MethodTable__m_uBaseSize]
add x2, x2, x3
add x2, x2, #7
and x2, x2, #-8
// x0 == MethodTable
// x1 == element count
// x2 == array size
#ifdef FEATURE_EMULATED_TLS
GETTHREAD_ETLS_3
#else
INLINE_GETTHREAD x3
#endif
// Load potential new object address into x12.
ldr x12, [x3, #OFFSETOF__Thread__m_alloc_context__alloc_ptr]
// Determine whether the end of the object would lie outside of the current allocation context. If so,
// we abandon the attempt to allocate the object directly and fall back to the slow helper.
add x2, x2, x12
ldr x12, [x3, #OFFSETOF__Thread__m_alloc_context__alloc_limit]
cmp x2, x12
bhi RhpNewArrayRare
// Reload new object address into x12.
ldr x12, [x3, #OFFSETOF__Thread__m_alloc_context__alloc_ptr]
// Update the alloc pointer to account for the allocation.
str x2, [x3, #OFFSETOF__Thread__m_alloc_context__alloc_ptr]
// Set the new objects MethodTable pointer and element count.
str x0, [x12, #OFFSETOF__Object__m_pEEType]
str x1, [x12, #OFFSETOF__Array__m_Length]
// Return the object allocated in r0.
mov x0, x12
ret
ArraySizeOverflow:
// We get here if the size of the final array object can not be represented as an unsigned
// 32-bit value. We are going to tail-call to a managed helper that will throw
// an overflow exception that the caller of this allocator understands.
// x0 holds MethodTable pointer already
mov x1, #1 // Indicate that we should throw OverflowException
b RhExceptionHandling_FailedAllocation
LEAF_END RhpNewArray, _TEXT
// Allocate one dimensional, zero based array (SZARRAY) using the slow path that calls a runtime helper.
// x0 == MethodTable
// x1 == element count
// x2 == array size + Thread::m_alloc_context::alloc_ptr
// x3 == Thread
NESTED_ENTRY RhpNewArrayRare, _TEXT, NoHandler
// Recover array size by subtracting the alloc_ptr from x2.
ldr x12, [x3, #OFFSETOF__Thread__m_alloc_context__alloc_ptr]
sub x2, x2, x12
PUSH_COOP_PINVOKE_FRAME x3
// Preserve data we will need later into the callee saved registers
mov x19, x0 // Preserve MethodTable
mov x2, x1 // numElements
mov x1, #0 // uFlags
// void* RhpGcAlloc(MethodTable *pEEType, uint32_t uFlags, uintptr_t numElements, void * pTransitionFrame)
bl RhpGcAlloc
// Set the new objects MethodTable pointer and length on success.
cbz x0, ArrayOutOfMemory
POP_COOP_PINVOKE_FRAME
EPILOG_RETURN
ArrayOutOfMemory:
// This is the OOM failure path. We are going to tail-call to a managed helper that will throw
// an out of memory exception that the caller of this allocator understands.
mov x0, x19 // MethodTable Pointer
mov x1, 0 // Indicate that we should throw OOM.
POP_COOP_PINVOKE_FRAME
b RhExceptionHandling_FailedAllocation
NESTED_END RhpNewArrayRare, _TEXT
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/HardwareIntrinsics/General/Vector128/LessThanOrEqual.UInt16.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void LessThanOrEqualUInt16()
{
var test = new VectorBinaryOpTest__LessThanOrEqualUInt16();
// 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__LessThanOrEqualUInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
if ((alignment != 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<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<UInt16> _fld1;
public Vector128<UInt16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__LessThanOrEqualUInt16 testClass)
{
var result = Vector128.LessThanOrEqual(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt16[] _data2 = new UInt16[Op2ElementCount];
private static Vector128<UInt16> _clsVar1;
private static Vector128<UInt16> _clsVar2;
private Vector128<UInt16> _fld1;
private Vector128<UInt16> _fld2;
private DataTable _dataTable;
static VectorBinaryOpTest__LessThanOrEqualUInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
}
public VectorBinaryOpTest__LessThanOrEqualUInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector128.LessThanOrEqual(
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector128).GetMethod(nameof(Vector128.LessThanOrEqual), new Type[] {
typeof(Vector128<UInt16>),
typeof(Vector128<UInt16>)
});
if (method is null)
{
method = typeof(Vector128).GetMethod(nameof(Vector128.LessThanOrEqual), 1, new Type[] {
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(UInt16));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector128.LessThanOrEqual(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr);
var result = Vector128.LessThanOrEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__LessThanOrEqualUInt16();
var result = Vector128.LessThanOrEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector128.LessThanOrEqual(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector128.LessThanOrEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector128<UInt16> op1, Vector128<UInt16> op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != ((left[0] <= right[0]) ? ushort.MaxValue : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((left[i] <= right[i]) ? ushort.MaxValue : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.LessThanOrEqual)}<UInt16>(Vector128<UInt16>, Vector128<UInt16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\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 LessThanOrEqualUInt16()
{
var test = new VectorBinaryOpTest__LessThanOrEqualUInt16();
// 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__LessThanOrEqualUInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
if ((alignment != 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<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<UInt16> _fld1;
public Vector128<UInt16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__LessThanOrEqualUInt16 testClass)
{
var result = Vector128.LessThanOrEqual(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt16[] _data2 = new UInt16[Op2ElementCount];
private static Vector128<UInt16> _clsVar1;
private static Vector128<UInt16> _clsVar2;
private Vector128<UInt16> _fld1;
private Vector128<UInt16> _fld2;
private DataTable _dataTable;
static VectorBinaryOpTest__LessThanOrEqualUInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
}
public VectorBinaryOpTest__LessThanOrEqualUInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector128.LessThanOrEqual(
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector128).GetMethod(nameof(Vector128.LessThanOrEqual), new Type[] {
typeof(Vector128<UInt16>),
typeof(Vector128<UInt16>)
});
if (method is null)
{
method = typeof(Vector128).GetMethod(nameof(Vector128.LessThanOrEqual), 1, new Type[] {
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(UInt16));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector128.LessThanOrEqual(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr);
var result = Vector128.LessThanOrEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__LessThanOrEqualUInt16();
var result = Vector128.LessThanOrEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector128.LessThanOrEqual(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector128.LessThanOrEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector128<UInt16> op1, Vector128<UInt16> op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != ((left[0] <= right[0]) ? ushort.MaxValue : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((left[i] <= right[i]) ? ushort.MaxValue : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.LessThanOrEqual)}<UInt16>(Vector128<UInt16>, Vector128<UInt16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Text.Json/gen/Resources/xlf/Strings.de.xlf
|
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="de" original="../Strings.resx">
<body>
<trans-unit id="ContextClassesMustBePartialMessageFormat">
<source>Derived 'JsonSerializerContext' type '{0}' specifies JSON-serializable types. The type and all containing types must be made partial to kick off source generation.</source>
<target state="translated">Der abgeleitete JsonSerializerContext-Typ "{0}" gibt serialisierbare JSON-Typen an. Der Typ und alle enthaltenden Typen müssen partiell sein, um die Quellgenerierung zu starten.</target>
<note />
</trans-unit>
<trans-unit id="ContextClassesMustBePartialTitle">
<source>Derived 'JsonSerializerContext' types and all containing types must be partial.</source>
<target state="translated">Abgeleitete JsonSerializerContext-Typen und alle enthaltenden Typen müssen partiell sein.</target>
<note />
</trans-unit>
<trans-unit id="DataExtensionPropertyInvalidFormat">
<source>The data extension property '{0}.{1}' is invalid. It must implement 'IDictionary<string, JsonElement>' or 'IDictionary<string, object>', or be 'JsonObject'.</source>
<target state="translated">Die Datenerweiterungseigenschaft „{0}.{1}“ ist ungültig. Sie muss „IDictionary<string, JsonElement>“ oder „IDictionary<string, object>“ oder „JsonObject“ implementieren.</target>
<note />
</trans-unit>
<trans-unit id="DataExtensionPropertyInvalidTitle">
<source>Data extension property type invalid.</source>
<target state="translated">Der Typ der Datenerweiterungseigenschaft ist ungültig.</target>
<note />
</trans-unit>
<trans-unit id="DuplicateTypeNameMessageFormat">
<source>There are multiple types named {0}. Source was generated for the first one detected. Use 'JsonSerializableAttribute.TypeInfoPropertyName' to resolve this collision.</source>
<target state="translated">Es sind mehrere Typen namens "{0}" vorhanden. Die Quelle wurde für den ersten festgestellten Typ generiert. Verwenden Sie "JsonSerializableAttribute.TypeInfoPropertyName", um diesen Konflikt zu beheben.</target>
<note />
</trans-unit>
<trans-unit id="DuplicateTypeNameTitle">
<source>Duplicate type name.</source>
<target state="translated">Doppelter Typname</target>
<note />
</trans-unit>
<trans-unit id="InaccessibleJsonIncludePropertiesNotSupportedFormat">
<source>The member '{0}.{1}' has been annotated with the JsonIncludeAttribute but is not visible to the source generator.</source>
<target state="translated">Der Member "{0}. {1}" wurde mit dem JsonIncludeAttribute versehen, ist jedoch für den Quellgenerator nicht sichtbar.</target>
<note />
</trans-unit>
<trans-unit id="InaccessibleJsonIncludePropertiesNotSupportedTitle">
<source>Inaccessible properties annotated with the JsonIncludeAttribute are not supported in source generation mode.</source>
<target state="translated">Nicht zugängliche Eigenschaften, die mit dem JsonIncludeAttribute versehen sind, werden im Quellgenerierungsmodus nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="InitOnlyPropertyDeserializationNotSupportedFormat">
<source>The type '{0}' defines init-only properties, deserialization of which is currently not supported in source generation mode.</source>
<target state="translated">Der Typ "{0}" definiert nur init-Eigenschaften, deren Deserialisierung im Quellgenerierungsmodus derzeit nicht unterstützt wird.</target>
<note />
</trans-unit>
<trans-unit id="InitOnlyPropertyDeserializationNotSupportedTitle">
<source>Deserialization of init-only properties is currently not supported in source generation mode.</source>
<target state="translated">Die Deserialisierung von reinen init-Eigenschaften wird im Quellgenerierungsmodus derzeit nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="MultipleJsonConstructorAttributeFormat">
<source>Type '{0}' has multiple constructors annotated with 'JsonConstructorAttribute'.</source>
<target state="translated">Typ "{0}" weist mehrere Konstruktoren mit dem Kommentar "JsonConstructorAttribute" auf.</target>
<note />
</trans-unit>
<trans-unit id="MultipleJsonConstructorAttributeTitle">
<source>Type has multiple constructors annotated with JsonConstructorAttribute.</source>
<target state="translated">Der Typ weist mehrere Konstruktoren mit dem Kommentar JsonConstructorAttribute auf.</target>
<note />
</trans-unit>
<trans-unit id="MultipleJsonExtensionDataAttributeFormat">
<source>Type '{0}' has multiple members annotated with 'JsonExtensionDataAttribute'.</source>
<target state="translated">Typ „{0}“ enthält mehrere Elemente, die mit dem „JsonExtensionDataAttribute“ versehen sind.</target>
<note />
</trans-unit>
<trans-unit id="MultipleJsonExtensionDataAttributeTitle">
<source>Type has multiple members annotated with JsonExtensionDataAttribute.</source>
<target state="translated">Der Typ enthält mehrere Elemente, die mit dem JsonExtensionDataAttribute versehen sind.</target>
<note />
</trans-unit>
<trans-unit id="TypeNotSupportedMessageFormat">
<source>Did not generate serialization metadata for type '{0}'.</source>
<target state="translated">Die Serialisierungsmetadaten für den Typ "{0}" wurden nicht generiert.</target>
<note />
</trans-unit>
<trans-unit id="TypeNotSupportedTitle">
<source>Did not generate serialization metadata for type.</source>
<target state="translated">Serialisierungsmetadaten für den Typ wurden nicht generiert</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
|
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="de" original="../Strings.resx">
<body>
<trans-unit id="ContextClassesMustBePartialMessageFormat">
<source>Derived 'JsonSerializerContext' type '{0}' specifies JSON-serializable types. The type and all containing types must be made partial to kick off source generation.</source>
<target state="translated">Der abgeleitete JsonSerializerContext-Typ "{0}" gibt serialisierbare JSON-Typen an. Der Typ und alle enthaltenden Typen müssen partiell sein, um die Quellgenerierung zu starten.</target>
<note />
</trans-unit>
<trans-unit id="ContextClassesMustBePartialTitle">
<source>Derived 'JsonSerializerContext' types and all containing types must be partial.</source>
<target state="translated">Abgeleitete JsonSerializerContext-Typen und alle enthaltenden Typen müssen partiell sein.</target>
<note />
</trans-unit>
<trans-unit id="DataExtensionPropertyInvalidFormat">
<source>The data extension property '{0}.{1}' is invalid. It must implement 'IDictionary<string, JsonElement>' or 'IDictionary<string, object>', or be 'JsonObject'.</source>
<target state="translated">Die Datenerweiterungseigenschaft „{0}.{1}“ ist ungültig. Sie muss „IDictionary<string, JsonElement>“ oder „IDictionary<string, object>“ oder „JsonObject“ implementieren.</target>
<note />
</trans-unit>
<trans-unit id="DataExtensionPropertyInvalidTitle">
<source>Data extension property type invalid.</source>
<target state="translated">Der Typ der Datenerweiterungseigenschaft ist ungültig.</target>
<note />
</trans-unit>
<trans-unit id="DuplicateTypeNameMessageFormat">
<source>There are multiple types named {0}. Source was generated for the first one detected. Use 'JsonSerializableAttribute.TypeInfoPropertyName' to resolve this collision.</source>
<target state="translated">Es sind mehrere Typen namens "{0}" vorhanden. Die Quelle wurde für den ersten festgestellten Typ generiert. Verwenden Sie "JsonSerializableAttribute.TypeInfoPropertyName", um diesen Konflikt zu beheben.</target>
<note />
</trans-unit>
<trans-unit id="DuplicateTypeNameTitle">
<source>Duplicate type name.</source>
<target state="translated">Doppelter Typname</target>
<note />
</trans-unit>
<trans-unit id="InaccessibleJsonIncludePropertiesNotSupportedFormat">
<source>The member '{0}.{1}' has been annotated with the JsonIncludeAttribute but is not visible to the source generator.</source>
<target state="translated">Der Member "{0}. {1}" wurde mit dem JsonIncludeAttribute versehen, ist jedoch für den Quellgenerator nicht sichtbar.</target>
<note />
</trans-unit>
<trans-unit id="InaccessibleJsonIncludePropertiesNotSupportedTitle">
<source>Inaccessible properties annotated with the JsonIncludeAttribute are not supported in source generation mode.</source>
<target state="translated">Nicht zugängliche Eigenschaften, die mit dem JsonIncludeAttribute versehen sind, werden im Quellgenerierungsmodus nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="InitOnlyPropertyDeserializationNotSupportedFormat">
<source>The type '{0}' defines init-only properties, deserialization of which is currently not supported in source generation mode.</source>
<target state="translated">Der Typ "{0}" definiert nur init-Eigenschaften, deren Deserialisierung im Quellgenerierungsmodus derzeit nicht unterstützt wird.</target>
<note />
</trans-unit>
<trans-unit id="InitOnlyPropertyDeserializationNotSupportedTitle">
<source>Deserialization of init-only properties is currently not supported in source generation mode.</source>
<target state="translated">Die Deserialisierung von reinen init-Eigenschaften wird im Quellgenerierungsmodus derzeit nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="MultipleJsonConstructorAttributeFormat">
<source>Type '{0}' has multiple constructors annotated with 'JsonConstructorAttribute'.</source>
<target state="translated">Typ "{0}" weist mehrere Konstruktoren mit dem Kommentar "JsonConstructorAttribute" auf.</target>
<note />
</trans-unit>
<trans-unit id="MultipleJsonConstructorAttributeTitle">
<source>Type has multiple constructors annotated with JsonConstructorAttribute.</source>
<target state="translated">Der Typ weist mehrere Konstruktoren mit dem Kommentar JsonConstructorAttribute auf.</target>
<note />
</trans-unit>
<trans-unit id="MultipleJsonExtensionDataAttributeFormat">
<source>Type '{0}' has multiple members annotated with 'JsonExtensionDataAttribute'.</source>
<target state="translated">Typ „{0}“ enthält mehrere Elemente, die mit dem „JsonExtensionDataAttribute“ versehen sind.</target>
<note />
</trans-unit>
<trans-unit id="MultipleJsonExtensionDataAttributeTitle">
<source>Type has multiple members annotated with JsonExtensionDataAttribute.</source>
<target state="translated">Der Typ enthält mehrere Elemente, die mit dem JsonExtensionDataAttribute versehen sind.</target>
<note />
</trans-unit>
<trans-unit id="TypeNotSupportedMessageFormat">
<source>Did not generate serialization metadata for type '{0}'.</source>
<target state="translated">Die Serialisierungsmetadaten für den Typ "{0}" wurden nicht generiert.</target>
<note />
</trans-unit>
<trans-unit id="TypeNotSupportedTitle">
<source>Did not generate serialization metadata for type.</source>
<target state="translated">Serialisierungsmetadaten für den Typ wurden nicht generiert</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/coreclr/pal/src/libunwind/src/ptrace/_UPT_reg_offset.c
|
/* libunwind - a platform-independent unwind library
Copyright (C) 2003-2004 Hewlett-Packard Co
Contributed by David Mosberger-Tang <[email protected]>
Copyright (C) 2013 Linaro Limited
This file is part of libunwind.
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. */
#include "_UPT_internal.h"
#include <stddef.h>
#ifdef HAVE_ASM_PTRACE_H
# include <asm/ptrace.h>
#endif
#ifdef HAVE_ASM_PTRACE_OFFSETS_H
# include <asm/ptrace_offsets.h>
#endif
#if defined(__powerpc64__) && defined(__FreeBSD__)
#define PT_R0 0
#define PT_R1 1
#define PT_R2 2
#define PT_R3 3
#define PT_R4 4
#define PT_R5 5
#define PT_R6 6
#define PT_R7 7
#define PT_R8 8
#define PT_R9 9
#define PT_R10 10
#define PT_R11 11
#define PT_R12 12
#define PT_R13 13
#define PT_R14 14
#define PT_R15 15
#define PT_R16 16
#define PT_R17 17
#define PT_R18 18
#define PT_R19 19
#define PT_R20 20
#define PT_R21 21
#define PT_R22 22
#define PT_R23 23
#define PT_R24 24
#define PT_R25 25
#define PT_R26 26
#define PT_R27 27
#define PT_R28 28
#define PT_R29 29
#define PT_R30 30
#define PT_R31 31
#define PT_NIP 32
#define PT_CTR 35
#define PT_LNK 36
#define PT_XER 37
#define PT_FPR0 48
#define PT_VR0 82
#define PT_VSCR (PT_VR0 + 32*2 + 1)
#define PT_VRSAVE (PT_VR0 + 33*2)
#endif
const int _UPT_reg_offset[UNW_REG_LAST + 1] =
{
#ifdef HAVE_ASM_PTRACE_OFFSETS_H
# ifndef PT_AR_CSD
# define PT_AR_CSD -1 /* this was introduced with rev 2.1 of ia64 */
# endif
[UNW_IA64_GR + 0] = -1, [UNW_IA64_GR + 1] = PT_R1,
[UNW_IA64_GR + 2] = PT_R2, [UNW_IA64_GR + 3] = PT_R3,
[UNW_IA64_GR + 4] = PT_R4, [UNW_IA64_GR + 5] = PT_R5,
[UNW_IA64_GR + 6] = PT_R6, [UNW_IA64_GR + 7] = PT_R7,
[UNW_IA64_GR + 8] = PT_R8, [UNW_IA64_GR + 9] = PT_R9,
[UNW_IA64_GR + 10] = PT_R10, [UNW_IA64_GR + 11] = PT_R11,
[UNW_IA64_GR + 12] = PT_R12, [UNW_IA64_GR + 13] = PT_R13,
[UNW_IA64_GR + 14] = PT_R14, [UNW_IA64_GR + 15] = PT_R15,
[UNW_IA64_GR + 16] = PT_R16, [UNW_IA64_GR + 17] = PT_R17,
[UNW_IA64_GR + 18] = PT_R18, [UNW_IA64_GR + 19] = PT_R19,
[UNW_IA64_GR + 20] = PT_R20, [UNW_IA64_GR + 21] = PT_R21,
[UNW_IA64_GR + 22] = PT_R22, [UNW_IA64_GR + 23] = PT_R23,
[UNW_IA64_GR + 24] = PT_R24, [UNW_IA64_GR + 25] = PT_R25,
[UNW_IA64_GR + 26] = PT_R26, [UNW_IA64_GR + 27] = PT_R27,
[UNW_IA64_GR + 28] = PT_R28, [UNW_IA64_GR + 29] = PT_R29,
[UNW_IA64_GR + 30] = PT_R30, [UNW_IA64_GR + 31] = PT_R31,
[UNW_IA64_NAT+ 0] = -1, [UNW_IA64_NAT+ 1] = PT_NAT_BITS,
[UNW_IA64_NAT+ 2] = PT_NAT_BITS, [UNW_IA64_NAT+ 3] = PT_NAT_BITS,
[UNW_IA64_NAT+ 4] = PT_NAT_BITS, [UNW_IA64_NAT+ 5] = PT_NAT_BITS,
[UNW_IA64_NAT+ 6] = PT_NAT_BITS, [UNW_IA64_NAT+ 7] = PT_NAT_BITS,
[UNW_IA64_NAT+ 8] = PT_NAT_BITS, [UNW_IA64_NAT+ 9] = PT_NAT_BITS,
[UNW_IA64_NAT+ 10] = PT_NAT_BITS, [UNW_IA64_NAT+ 11] = PT_NAT_BITS,
[UNW_IA64_NAT+ 12] = PT_NAT_BITS, [UNW_IA64_NAT+ 13] = PT_NAT_BITS,
[UNW_IA64_NAT+ 14] = PT_NAT_BITS, [UNW_IA64_NAT+ 15] = PT_NAT_BITS,
[UNW_IA64_NAT+ 16] = PT_NAT_BITS, [UNW_IA64_NAT+ 17] = PT_NAT_BITS,
[UNW_IA64_NAT+ 18] = PT_NAT_BITS, [UNW_IA64_NAT+ 19] = PT_NAT_BITS,
[UNW_IA64_NAT+ 20] = PT_NAT_BITS, [UNW_IA64_NAT+ 21] = PT_NAT_BITS,
[UNW_IA64_NAT+ 22] = PT_NAT_BITS, [UNW_IA64_NAT+ 23] = PT_NAT_BITS,
[UNW_IA64_NAT+ 24] = PT_NAT_BITS, [UNW_IA64_NAT+ 25] = PT_NAT_BITS,
[UNW_IA64_NAT+ 26] = PT_NAT_BITS, [UNW_IA64_NAT+ 27] = PT_NAT_BITS,
[UNW_IA64_NAT+ 28] = PT_NAT_BITS, [UNW_IA64_NAT+ 29] = PT_NAT_BITS,
[UNW_IA64_NAT+ 30] = PT_NAT_BITS, [UNW_IA64_NAT+ 31] = PT_NAT_BITS,
[UNW_IA64_FR + 0] = -1, [UNW_IA64_FR + 1] = -1,
[UNW_IA64_FR + 2] = PT_F2, [UNW_IA64_FR + 3] = PT_F3,
[UNW_IA64_FR + 4] = PT_F4, [UNW_IA64_FR + 5] = PT_F5,
[UNW_IA64_FR + 6] = PT_F6, [UNW_IA64_FR + 7] = PT_F7,
[UNW_IA64_FR + 8] = PT_F8, [UNW_IA64_FR + 9] = PT_F9,
[UNW_IA64_FR + 10] = PT_F10, [UNW_IA64_FR + 11] = PT_F11,
[UNW_IA64_FR + 12] = PT_F12, [UNW_IA64_FR + 13] = PT_F13,
[UNW_IA64_FR + 14] = PT_F14, [UNW_IA64_FR + 15] = PT_F15,
[UNW_IA64_FR + 16] = PT_F16, [UNW_IA64_FR + 17] = PT_F17,
[UNW_IA64_FR + 18] = PT_F18, [UNW_IA64_FR + 19] = PT_F19,
[UNW_IA64_FR + 20] = PT_F20, [UNW_IA64_FR + 21] = PT_F21,
[UNW_IA64_FR + 22] = PT_F22, [UNW_IA64_FR + 23] = PT_F23,
[UNW_IA64_FR + 24] = PT_F24, [UNW_IA64_FR + 25] = PT_F25,
[UNW_IA64_FR + 26] = PT_F26, [UNW_IA64_FR + 27] = PT_F27,
[UNW_IA64_FR + 28] = PT_F28, [UNW_IA64_FR + 29] = PT_F29,
[UNW_IA64_FR + 30] = PT_F30, [UNW_IA64_FR + 31] = PT_F31,
[UNW_IA64_FR + 32] = PT_F32, [UNW_IA64_FR + 33] = PT_F33,
[UNW_IA64_FR + 34] = PT_F34, [UNW_IA64_FR + 35] = PT_F35,
[UNW_IA64_FR + 36] = PT_F36, [UNW_IA64_FR + 37] = PT_F37,
[UNW_IA64_FR + 38] = PT_F38, [UNW_IA64_FR + 39] = PT_F39,
[UNW_IA64_FR + 40] = PT_F40, [UNW_IA64_FR + 41] = PT_F41,
[UNW_IA64_FR + 42] = PT_F42, [UNW_IA64_FR + 43] = PT_F43,
[UNW_IA64_FR + 44] = PT_F44, [UNW_IA64_FR + 45] = PT_F45,
[UNW_IA64_FR + 46] = PT_F46, [UNW_IA64_FR + 47] = PT_F47,
[UNW_IA64_FR + 48] = PT_F48, [UNW_IA64_FR + 49] = PT_F49,
[UNW_IA64_FR + 50] = PT_F50, [UNW_IA64_FR + 51] = PT_F51,
[UNW_IA64_FR + 52] = PT_F52, [UNW_IA64_FR + 53] = PT_F53,
[UNW_IA64_FR + 54] = PT_F54, [UNW_IA64_FR + 55] = PT_F55,
[UNW_IA64_FR + 56] = PT_F56, [UNW_IA64_FR + 57] = PT_F57,
[UNW_IA64_FR + 58] = PT_F58, [UNW_IA64_FR + 59] = PT_F59,
[UNW_IA64_FR + 60] = PT_F60, [UNW_IA64_FR + 61] = PT_F61,
[UNW_IA64_FR + 62] = PT_F62, [UNW_IA64_FR + 63] = PT_F63,
[UNW_IA64_FR + 64] = PT_F64, [UNW_IA64_FR + 65] = PT_F65,
[UNW_IA64_FR + 66] = PT_F66, [UNW_IA64_FR + 67] = PT_F67,
[UNW_IA64_FR + 68] = PT_F68, [UNW_IA64_FR + 69] = PT_F69,
[UNW_IA64_FR + 70] = PT_F70, [UNW_IA64_FR + 71] = PT_F71,
[UNW_IA64_FR + 72] = PT_F72, [UNW_IA64_FR + 73] = PT_F73,
[UNW_IA64_FR + 74] = PT_F74, [UNW_IA64_FR + 75] = PT_F75,
[UNW_IA64_FR + 76] = PT_F76, [UNW_IA64_FR + 77] = PT_F77,
[UNW_IA64_FR + 78] = PT_F78, [UNW_IA64_FR + 79] = PT_F79,
[UNW_IA64_FR + 80] = PT_F80, [UNW_IA64_FR + 81] = PT_F81,
[UNW_IA64_FR + 82] = PT_F82, [UNW_IA64_FR + 83] = PT_F83,
[UNW_IA64_FR + 84] = PT_F84, [UNW_IA64_FR + 85] = PT_F85,
[UNW_IA64_FR + 86] = PT_F86, [UNW_IA64_FR + 87] = PT_F87,
[UNW_IA64_FR + 88] = PT_F88, [UNW_IA64_FR + 89] = PT_F89,
[UNW_IA64_FR + 90] = PT_F90, [UNW_IA64_FR + 91] = PT_F91,
[UNW_IA64_FR + 92] = PT_F92, [UNW_IA64_FR + 93] = PT_F93,
[UNW_IA64_FR + 94] = PT_F94, [UNW_IA64_FR + 95] = PT_F95,
[UNW_IA64_FR + 96] = PT_F96, [UNW_IA64_FR + 97] = PT_F97,
[UNW_IA64_FR + 98] = PT_F98, [UNW_IA64_FR + 99] = PT_F99,
[UNW_IA64_FR +100] = PT_F100, [UNW_IA64_FR +101] = PT_F101,
[UNW_IA64_FR +102] = PT_F102, [UNW_IA64_FR +103] = PT_F103,
[UNW_IA64_FR +104] = PT_F104, [UNW_IA64_FR +105] = PT_F105,
[UNW_IA64_FR +106] = PT_F106, [UNW_IA64_FR +107] = PT_F107,
[UNW_IA64_FR +108] = PT_F108, [UNW_IA64_FR +109] = PT_F109,
[UNW_IA64_FR +110] = PT_F110, [UNW_IA64_FR +111] = PT_F111,
[UNW_IA64_FR +112] = PT_F112, [UNW_IA64_FR +113] = PT_F113,
[UNW_IA64_FR +114] = PT_F114, [UNW_IA64_FR +115] = PT_F115,
[UNW_IA64_FR +116] = PT_F116, [UNW_IA64_FR +117] = PT_F117,
[UNW_IA64_FR +118] = PT_F118, [UNW_IA64_FR +119] = PT_F119,
[UNW_IA64_FR +120] = PT_F120, [UNW_IA64_FR +121] = PT_F121,
[UNW_IA64_FR +122] = PT_F122, [UNW_IA64_FR +123] = PT_F123,
[UNW_IA64_FR +124] = PT_F124, [UNW_IA64_FR +125] = PT_F125,
[UNW_IA64_FR +126] = PT_F126, [UNW_IA64_FR +127] = PT_F127,
[UNW_IA64_AR + 0] = -1, [UNW_IA64_AR + 1] = -1,
[UNW_IA64_AR + 2] = -1, [UNW_IA64_AR + 3] = -1,
[UNW_IA64_AR + 4] = -1, [UNW_IA64_AR + 5] = -1,
[UNW_IA64_AR + 6] = -1, [UNW_IA64_AR + 7] = -1,
[UNW_IA64_AR + 8] = -1, [UNW_IA64_AR + 9] = -1,
[UNW_IA64_AR + 10] = -1, [UNW_IA64_AR + 11] = -1,
[UNW_IA64_AR + 12] = -1, [UNW_IA64_AR + 13] = -1,
[UNW_IA64_AR + 14] = -1, [UNW_IA64_AR + 15] = -1,
[UNW_IA64_AR + 16] = PT_AR_RSC, [UNW_IA64_AR + 17] = PT_AR_BSP,
[UNW_IA64_AR + 18] = PT_AR_BSPSTORE,[UNW_IA64_AR + 19] = PT_AR_RNAT,
[UNW_IA64_AR + 20] = -1, [UNW_IA64_AR + 21] = -1,
[UNW_IA64_AR + 22] = -1, [UNW_IA64_AR + 23] = -1,
[UNW_IA64_AR + 24] = -1, [UNW_IA64_AR + 25] = PT_AR_CSD,
[UNW_IA64_AR + 26] = -1, [UNW_IA64_AR + 27] = -1,
[UNW_IA64_AR + 28] = -1, [UNW_IA64_AR + 29] = -1,
[UNW_IA64_AR + 30] = -1, [UNW_IA64_AR + 31] = -1,
[UNW_IA64_AR + 32] = PT_AR_CCV, [UNW_IA64_AR + 33] = -1,
[UNW_IA64_AR + 34] = -1, [UNW_IA64_AR + 35] = -1,
[UNW_IA64_AR + 36] = PT_AR_UNAT, [UNW_IA64_AR + 37] = -1,
[UNW_IA64_AR + 38] = -1, [UNW_IA64_AR + 39] = -1,
[UNW_IA64_AR + 40] = PT_AR_FPSR, [UNW_IA64_AR + 41] = -1,
[UNW_IA64_AR + 42] = -1, [UNW_IA64_AR + 43] = -1,
[UNW_IA64_AR + 44] = -1, [UNW_IA64_AR + 45] = -1,
[UNW_IA64_AR + 46] = -1, [UNW_IA64_AR + 47] = -1,
[UNW_IA64_AR + 48] = -1, [UNW_IA64_AR + 49] = -1,
[UNW_IA64_AR + 50] = -1, [UNW_IA64_AR + 51] = -1,
[UNW_IA64_AR + 52] = -1, [UNW_IA64_AR + 53] = -1,
[UNW_IA64_AR + 54] = -1, [UNW_IA64_AR + 55] = -1,
[UNW_IA64_AR + 56] = -1, [UNW_IA64_AR + 57] = -1,
[UNW_IA64_AR + 58] = -1, [UNW_IA64_AR + 59] = -1,
[UNW_IA64_AR + 60] = -1, [UNW_IA64_AR + 61] = -1,
[UNW_IA64_AR + 62] = -1, [UNW_IA64_AR + 63] = -1,
[UNW_IA64_AR + 64] = PT_AR_PFS, [UNW_IA64_AR + 65] = PT_AR_LC,
[UNW_IA64_AR + 66] = PT_AR_EC, [UNW_IA64_AR + 67] = -1,
[UNW_IA64_AR + 68] = -1, [UNW_IA64_AR + 69] = -1,
[UNW_IA64_AR + 70] = -1, [UNW_IA64_AR + 71] = -1,
[UNW_IA64_AR + 72] = -1, [UNW_IA64_AR + 73] = -1,
[UNW_IA64_AR + 74] = -1, [UNW_IA64_AR + 75] = -1,
[UNW_IA64_AR + 76] = -1, [UNW_IA64_AR + 77] = -1,
[UNW_IA64_AR + 78] = -1, [UNW_IA64_AR + 79] = -1,
[UNW_IA64_AR + 80] = -1, [UNW_IA64_AR + 81] = -1,
[UNW_IA64_AR + 82] = -1, [UNW_IA64_AR + 83] = -1,
[UNW_IA64_AR + 84] = -1, [UNW_IA64_AR + 85] = -1,
[UNW_IA64_AR + 86] = -1, [UNW_IA64_AR + 87] = -1,
[UNW_IA64_AR + 88] = -1, [UNW_IA64_AR + 89] = -1,
[UNW_IA64_AR + 90] = -1, [UNW_IA64_AR + 91] = -1,
[UNW_IA64_AR + 92] = -1, [UNW_IA64_AR + 93] = -1,
[UNW_IA64_AR + 94] = -1, [UNW_IA64_AR + 95] = -1,
[UNW_IA64_AR + 96] = -1, [UNW_IA64_AR + 97] = -1,
[UNW_IA64_AR + 98] = -1, [UNW_IA64_AR + 99] = -1,
[UNW_IA64_AR +100] = -1, [UNW_IA64_AR +101] = -1,
[UNW_IA64_AR +102] = -1, [UNW_IA64_AR +103] = -1,
[UNW_IA64_AR +104] = -1, [UNW_IA64_AR +105] = -1,
[UNW_IA64_AR +106] = -1, [UNW_IA64_AR +107] = -1,
[UNW_IA64_AR +108] = -1, [UNW_IA64_AR +109] = -1,
[UNW_IA64_AR +110] = -1, [UNW_IA64_AR +111] = -1,
[UNW_IA64_AR +112] = -1, [UNW_IA64_AR +113] = -1,
[UNW_IA64_AR +114] = -1, [UNW_IA64_AR +115] = -1,
[UNW_IA64_AR +116] = -1, [UNW_IA64_AR +117] = -1,
[UNW_IA64_AR +118] = -1, [UNW_IA64_AR +119] = -1,
[UNW_IA64_AR +120] = -1, [UNW_IA64_AR +121] = -1,
[UNW_IA64_AR +122] = -1, [UNW_IA64_AR +123] = -1,
[UNW_IA64_AR +124] = -1, [UNW_IA64_AR +125] = -1,
[UNW_IA64_AR +126] = -1, [UNW_IA64_AR +127] = -1,
[UNW_IA64_BR + 0] = PT_B0, [UNW_IA64_BR + 1] = PT_B1,
[UNW_IA64_BR + 2] = PT_B2, [UNW_IA64_BR + 3] = PT_B3,
[UNW_IA64_BR + 4] = PT_B4, [UNW_IA64_BR + 5] = PT_B5,
[UNW_IA64_BR + 6] = PT_B6, [UNW_IA64_BR + 7] = PT_B7,
[UNW_IA64_PR] = PT_PR,
[UNW_IA64_CFM] = PT_CFM,
[UNW_IA64_IP] = PT_CR_IIP
#elif defined(HAVE_TTRACE)
# warning No support for ttrace() yet.
#elif defined(UNW_TARGET_HPPA)
[UNW_HPPA_GR + 0] = 0x000, [UNW_HPPA_GR + 1] = 0x004,
[UNW_HPPA_GR + 2] = 0x008, [UNW_HPPA_GR + 3] = 0x00c,
[UNW_HPPA_GR + 4] = 0x010, [UNW_HPPA_GR + 5] = 0x014,
[UNW_HPPA_GR + 6] = 0x018, [UNW_HPPA_GR + 7] = 0x01c,
[UNW_HPPA_GR + 8] = 0x020, [UNW_HPPA_GR + 9] = 0x024,
[UNW_HPPA_GR + 10] = 0x028, [UNW_HPPA_GR + 11] = 0x02c,
[UNW_HPPA_GR + 12] = 0x030, [UNW_HPPA_GR + 13] = 0x034,
[UNW_HPPA_GR + 14] = 0x038, [UNW_HPPA_GR + 15] = 0x03c,
[UNW_HPPA_GR + 16] = 0x040, [UNW_HPPA_GR + 17] = 0x044,
[UNW_HPPA_GR + 18] = 0x048, [UNW_HPPA_GR + 19] = 0x04c,
[UNW_HPPA_GR + 20] = 0x050, [UNW_HPPA_GR + 21] = 0x054,
[UNW_HPPA_GR + 22] = 0x058, [UNW_HPPA_GR + 23] = 0x05c,
[UNW_HPPA_GR + 24] = 0x060, [UNW_HPPA_GR + 25] = 0x064,
[UNW_HPPA_GR + 26] = 0x068, [UNW_HPPA_GR + 27] = 0x06c,
[UNW_HPPA_GR + 28] = 0x070, [UNW_HPPA_GR + 29] = 0x074,
[UNW_HPPA_GR + 30] = 0x078, [UNW_HPPA_GR + 31] = 0x07c,
[UNW_HPPA_FR + 0] = 0x080, [UNW_HPPA_FR + 1] = 0x088,
[UNW_HPPA_FR + 2] = 0x090, [UNW_HPPA_FR + 3] = 0x098,
[UNW_HPPA_FR + 4] = 0x0a0, [UNW_HPPA_FR + 5] = 0x0a8,
[UNW_HPPA_FR + 6] = 0x0b0, [UNW_HPPA_FR + 7] = 0x0b8,
[UNW_HPPA_FR + 8] = 0x0c0, [UNW_HPPA_FR + 9] = 0x0c8,
[UNW_HPPA_FR + 10] = 0x0d0, [UNW_HPPA_FR + 11] = 0x0d8,
[UNW_HPPA_FR + 12] = 0x0e0, [UNW_HPPA_FR + 13] = 0x0e8,
[UNW_HPPA_FR + 14] = 0x0f0, [UNW_HPPA_FR + 15] = 0x0f8,
[UNW_HPPA_FR + 16] = 0x100, [UNW_HPPA_FR + 17] = 0x108,
[UNW_HPPA_FR + 18] = 0x110, [UNW_HPPA_FR + 19] = 0x118,
[UNW_HPPA_FR + 20] = 0x120, [UNW_HPPA_FR + 21] = 0x128,
[UNW_HPPA_FR + 22] = 0x130, [UNW_HPPA_FR + 23] = 0x138,
[UNW_HPPA_FR + 24] = 0x140, [UNW_HPPA_FR + 25] = 0x148,
[UNW_HPPA_FR + 26] = 0x150, [UNW_HPPA_FR + 27] = 0x158,
[UNW_HPPA_FR + 28] = 0x160, [UNW_HPPA_FR + 29] = 0x168,
[UNW_HPPA_FR + 30] = 0x170, [UNW_HPPA_FR + 31] = 0x178,
[UNW_HPPA_IP] = 0x1a8 /* IAOQ[0] */
#elif defined(UNW_TARGET_X86)
#if defined __FreeBSD__
#define UNW_R_OFF(R, r) \
[UNW_X86_##R] = offsetof(gregset_t, r_##r),
UNW_R_OFF(EAX, eax)
UNW_R_OFF(EDX, edx)
UNW_R_OFF(ECX, ecx)
UNW_R_OFF(EBX, ebx)
UNW_R_OFF(ESI, esi)
UNW_R_OFF(EDI, edi)
UNW_R_OFF(EBP, ebp)
UNW_R_OFF(ESP, esp)
UNW_R_OFF(EIP, eip)
// UNW_R_OFF(CS, cs)
// UNW_R_OFF(EFLAGS, eflags)
// UNW_R_OFF(SS, ss)
#elif defined __linux__
[UNW_X86_EAX] = 0x18,
[UNW_X86_EBX] = 0x00,
[UNW_X86_ECX] = 0x04,
[UNW_X86_EDX] = 0x08,
[UNW_X86_ESI] = 0x0c,
[UNW_X86_EDI] = 0x10,
[UNW_X86_EBP] = 0x14,
[UNW_X86_EIP] = 0x30,
[UNW_X86_ESP] = 0x3c
/* CS = 0x34, */
/* DS = 0x1c, */
/* ES = 0x20, */
/* FS = 0x24, */
/* GS = 0x28, */
/* ORIG_EAX = 0x2c, */
/* EFLAGS = 0x38, */
/* SS = 0x40 */
#else
#error Port me
#endif
#elif defined(UNW_TARGET_X86_64)
#if defined __FreeBSD__
#define UNW_R_OFF(R, r) \
[UNW_X86_64_##R] = offsetof(gregset_t, r_##r),
UNW_R_OFF(RAX, rax)
UNW_R_OFF(RDX, rdx)
UNW_R_OFF(RCX, rcx)
UNW_R_OFF(RBX, rbx)
UNW_R_OFF(RSI, rsi)
UNW_R_OFF(RDI, rdi)
UNW_R_OFF(RBP, rbp)
UNW_R_OFF(RSP, rsp)
UNW_R_OFF(R8, r8)
UNW_R_OFF(R9, r9)
UNW_R_OFF(R10, r10)
UNW_R_OFF(R11, r11)
UNW_R_OFF(R12, r12)
UNW_R_OFF(R13, r13)
UNW_R_OFF(R14, r14)
UNW_R_OFF(R15, r15)
UNW_R_OFF(RIP, rip)
// UNW_R_OFF(CS, cs)
// UNW_R_OFF(EFLAGS, rflags)
// UNW_R_OFF(SS, ss)
#undef UNW_R_OFF
#elif defined __linux__
[UNW_X86_64_RAX] = 0x50,
[UNW_X86_64_RDX] = 0x60,
[UNW_X86_64_RCX] = 0x58,
[UNW_X86_64_RBX] = 0x28,
[UNW_X86_64_RSI] = 0x68,
[UNW_X86_64_RDI] = 0x70,
[UNW_X86_64_RBP] = 0x20,
[UNW_X86_64_RSP] = 0x98,
[UNW_X86_64_R8] = 0x48,
[UNW_X86_64_R9] = 0x40,
[UNW_X86_64_R10] = 0x38,
[UNW_X86_64_R11] = 0x30,
[UNW_X86_64_R12] = 0x18,
[UNW_X86_64_R13] = 0x10,
[UNW_X86_64_R14] = 0x08,
[UNW_X86_64_R15] = 0x00,
[UNW_X86_64_RIP] = 0x80
// [UNW_X86_64_CS] = 0x88,
// [UNW_X86_64_EFLAGS] = 0x90,
// [UNW_X86_64_RSP] = 0x98,
// [UNW_X86_64_SS] = 0xa0
#else
#error Port me
#endif
#elif defined(UNW_TARGET_PPC32) || defined(UNW_TARGET_PPC64)
#define UNW_REG_SLOT_SIZE sizeof(unsigned long)
#define UNW_PPC_R(v) ((v) * UNW_REG_SLOT_SIZE)
#define UNW_PPC_PT(p) UNW_PPC_R(PT_##p)
#define UNW_FP_OFF(b, i) \
[UNW_PPC##b##_F##i] = UNW_PPC_R(PT_FPR0 + i * 8/UNW_REG_SLOT_SIZE)
#define UNW_R_OFF(b, i) \
[UNW_PPC##b##_R##i] = UNW_PPC_R(PT_R##i)
#define UNW_PPC_REGS(b) \
UNW_R_OFF(b, 0), \
UNW_R_OFF(b, 1), \
UNW_R_OFF(b, 2), \
UNW_R_OFF(b, 3), \
UNW_R_OFF(b, 4), \
UNW_R_OFF(b, 5), \
UNW_R_OFF(b, 6), \
UNW_R_OFF(b, 7), \
UNW_R_OFF(b, 8), \
UNW_R_OFF(b, 9), \
UNW_R_OFF(b, 10), \
UNW_R_OFF(b, 11), \
UNW_R_OFF(b, 12), \
UNW_R_OFF(b, 13), \
UNW_R_OFF(b, 14), \
UNW_R_OFF(b, 15), \
UNW_R_OFF(b, 16), \
UNW_R_OFF(b, 17), \
UNW_R_OFF(b, 18), \
UNW_R_OFF(b, 19), \
UNW_R_OFF(b, 20), \
UNW_R_OFF(b, 21), \
UNW_R_OFF(b, 22), \
UNW_R_OFF(b, 23), \
UNW_R_OFF(b, 24), \
UNW_R_OFF(b, 25), \
UNW_R_OFF(b, 26), \
UNW_R_OFF(b, 27), \
UNW_R_OFF(b, 28), \
UNW_R_OFF(b, 29), \
UNW_R_OFF(b, 30), \
UNW_R_OFF(b, 31), \
\
[UNW_PPC##b##_CTR] = UNW_PPC_PT(CTR), \
[UNW_PPC##b##_XER] = UNW_PPC_PT(XER), \
[UNW_PPC##b##_LR] = UNW_PPC_PT(LNK), \
\
UNW_FP_OFF(b, 0), \
UNW_FP_OFF(b, 1), \
UNW_FP_OFF(b, 2), \
UNW_FP_OFF(b, 3), \
UNW_FP_OFF(b, 4), \
UNW_FP_OFF(b, 5), \
UNW_FP_OFF(b, 6), \
UNW_FP_OFF(b, 7), \
UNW_FP_OFF(b, 8), \
UNW_FP_OFF(b, 9), \
UNW_FP_OFF(b, 10), \
UNW_FP_OFF(b, 11), \
UNW_FP_OFF(b, 12), \
UNW_FP_OFF(b, 13), \
UNW_FP_OFF(b, 14), \
UNW_FP_OFF(b, 15), \
UNW_FP_OFF(b, 16), \
UNW_FP_OFF(b, 17), \
UNW_FP_OFF(b, 18), \
UNW_FP_OFF(b, 19), \
UNW_FP_OFF(b, 20), \
UNW_FP_OFF(b, 21), \
UNW_FP_OFF(b, 22), \
UNW_FP_OFF(b, 23), \
UNW_FP_OFF(b, 24), \
UNW_FP_OFF(b, 25), \
UNW_FP_OFF(b, 26), \
UNW_FP_OFF(b, 27), \
UNW_FP_OFF(b, 28), \
UNW_FP_OFF(b, 29), \
UNW_FP_OFF(b, 30), \
UNW_FP_OFF(b, 31)
#define UNW_PPC32_REGS \
[UNW_PPC32_FPSCR] = UNW_PPC_PT(FPSCR), \
[UNW_PPC32_CCR] = UNW_PPC_PT(CCR)
#define UNW_VR_OFF(i) \
[UNW_PPC64_V##i] = UNW_PPC_R(PT_VR0 + i * 2)
#define UNW_PPC64_REGS \
[UNW_PPC64_NIP] = UNW_PPC_PT(NIP), \
[UNW_PPC64_FRAME_POINTER] = -1, \
[UNW_PPC64_ARG_POINTER] = -1, \
[UNW_PPC64_CR0] = -1, \
[UNW_PPC64_CR1] = -1, \
[UNW_PPC64_CR2] = -1, \
[UNW_PPC64_CR3] = -1, \
[UNW_PPC64_CR4] = -1, \
[UNW_PPC64_CR5] = -1, \
[UNW_PPC64_CR6] = -1, \
[UNW_PPC64_CR7] = -1, \
[UNW_PPC64_VRSAVE] = UNW_PPC_PT(VRSAVE), \
[UNW_PPC64_VSCR] = UNW_PPC_PT(VSCR), \
[UNW_PPC64_SPE_ACC] = -1, \
[UNW_PPC64_SPEFSCR] = -1, \
UNW_VR_OFF(0), \
UNW_VR_OFF(1), \
UNW_VR_OFF(2), \
UNW_VR_OFF(3), \
UNW_VR_OFF(4), \
UNW_VR_OFF(5), \
UNW_VR_OFF(6), \
UNW_VR_OFF(7), \
UNW_VR_OFF(8), \
UNW_VR_OFF(9), \
UNW_VR_OFF(10), \
UNW_VR_OFF(11), \
UNW_VR_OFF(12), \
UNW_VR_OFF(13), \
UNW_VR_OFF(14), \
UNW_VR_OFF(15), \
UNW_VR_OFF(16), \
UNW_VR_OFF(17), \
UNW_VR_OFF(18), \
UNW_VR_OFF(19), \
UNW_VR_OFF(20), \
UNW_VR_OFF(21), \
UNW_VR_OFF(22), \
UNW_VR_OFF(23), \
UNW_VR_OFF(24), \
UNW_VR_OFF(25), \
UNW_VR_OFF(26), \
UNW_VR_OFF(27), \
UNW_VR_OFF(28), \
UNW_VR_OFF(29), \
UNW_VR_OFF(30), \
UNW_VR_OFF(31)
#if defined(UNW_TARGET_PPC32)
UNW_PPC_REGS(32),
UNW_PPC32_REGS,
#else
UNW_PPC_REGS(64),
UNW_PPC64_REGS,
#endif
#elif defined(UNW_TARGET_ARM)
#if defined(__linux__) || defined(__FreeBSD__)
[UNW_ARM_R0] = 0x00,
[UNW_ARM_R1] = 0x04,
[UNW_ARM_R2] = 0x08,
[UNW_ARM_R3] = 0x0c,
[UNW_ARM_R4] = 0x10,
[UNW_ARM_R5] = 0x14,
[UNW_ARM_R6] = 0x18,
[UNW_ARM_R7] = 0x1c,
[UNW_ARM_R8] = 0x20,
[UNW_ARM_R9] = 0x24,
[UNW_ARM_R10] = 0x28,
[UNW_ARM_R11] = 0x2c,
[UNW_ARM_R12] = 0x30,
[UNW_ARM_R13] = 0x34,
[UNW_ARM_R14] = 0x38,
[UNW_ARM_R15] = 0x3c,
#else
#error Fix me
#endif
#elif defined(UNW_TARGET_MIPS)
[UNW_MIPS_R0] = 0,
[UNW_MIPS_R1] = 1,
[UNW_MIPS_R2] = 2,
[UNW_MIPS_R3] = 3,
[UNW_MIPS_R4] = 4,
[UNW_MIPS_R5] = 5,
[UNW_MIPS_R6] = 6,
[UNW_MIPS_R7] = 7,
[UNW_MIPS_R8] = 8,
[UNW_MIPS_R9] = 9,
[UNW_MIPS_R10] = 10,
[UNW_MIPS_R11] = 11,
[UNW_MIPS_R12] = 12,
[UNW_MIPS_R13] = 13,
[UNW_MIPS_R14] = 14,
[UNW_MIPS_R15] = 15,
[UNW_MIPS_R16] = 16,
[UNW_MIPS_R17] = 17,
[UNW_MIPS_R18] = 18,
[UNW_MIPS_R19] = 19,
[UNW_MIPS_R20] = 20,
[UNW_MIPS_R21] = 21,
[UNW_MIPS_R22] = 22,
[UNW_MIPS_R23] = 23,
[UNW_MIPS_R24] = 24,
[UNW_MIPS_R25] = 25,
[UNW_MIPS_R26] = 26,
[UNW_MIPS_R27] = 27,
[UNW_MIPS_R28] = 28,
[UNW_MIPS_R29] = 29,
[UNW_MIPS_R30] = 30,
[UNW_MIPS_R31] = 31,
[UNW_MIPS_PC] = 64,
#elif defined(UNW_TARGET_SH)
#elif defined(UNW_TARGET_AARCH64)
[UNW_AARCH64_X0] = 0x00,
[UNW_AARCH64_X1] = 0x08,
[UNW_AARCH64_X2] = 0x10,
[UNW_AARCH64_X3] = 0x18,
[UNW_AARCH64_X4] = 0x20,
[UNW_AARCH64_X5] = 0x28,
[UNW_AARCH64_X6] = 0x30,
[UNW_AARCH64_X7] = 0x38,
[UNW_AARCH64_X8] = 0x40,
[UNW_AARCH64_X9] = 0x48,
[UNW_AARCH64_X10] = 0x50,
[UNW_AARCH64_X11] = 0x58,
[UNW_AARCH64_X12] = 0x60,
[UNW_AARCH64_X13] = 0x68,
[UNW_AARCH64_X14] = 0x70,
[UNW_AARCH64_X15] = 0x78,
[UNW_AARCH64_X16] = 0x80,
[UNW_AARCH64_X17] = 0x88,
[UNW_AARCH64_X18] = 0x90,
[UNW_AARCH64_X19] = 0x98,
[UNW_AARCH64_X20] = 0xa0,
[UNW_AARCH64_X21] = 0xa8,
[UNW_AARCH64_X22] = 0xb0,
[UNW_AARCH64_X23] = 0xb8,
[UNW_AARCH64_X24] = 0xc0,
[UNW_AARCH64_X25] = 0xc8,
[UNW_AARCH64_X26] = 0xd0,
[UNW_AARCH64_X27] = 0xd8,
[UNW_AARCH64_X28] = 0xe0,
[UNW_AARCH64_X29] = 0xe8,
[UNW_AARCH64_X30] = 0xf0,
[UNW_AARCH64_SP] = 0xf8,
[UNW_AARCH64_PC] = 0x100,
[UNW_AARCH64_PSTATE] = 0x108
#elif defined(UNW_TARGET_TILEGX)
[UNW_TILEGX_R0] = 0x00,
[UNW_TILEGX_R1] = 0x08,
[UNW_TILEGX_R2] = 0x10,
[UNW_TILEGX_R3] = 0x08,
[UNW_TILEGX_R4] = 0x20,
[UNW_TILEGX_R5] = 0x28,
[UNW_TILEGX_R6] = 0x30,
[UNW_TILEGX_R7] = 0x38,
[UNW_TILEGX_R8] = 0x40,
[UNW_TILEGX_R9] = 0x48,
[UNW_TILEGX_R10] = 0x50,
[UNW_TILEGX_R11] = 0x58,
[UNW_TILEGX_R12] = 0x60,
[UNW_TILEGX_R13] = 0x68,
[UNW_TILEGX_R14] = 0x70,
[UNW_TILEGX_R15] = 0x78,
[UNW_TILEGX_R16] = 0x80,
[UNW_TILEGX_R17] = 0x88,
[UNW_TILEGX_R18] = 0x90,
[UNW_TILEGX_R19] = 0x98,
[UNW_TILEGX_R20] = 0xa0,
[UNW_TILEGX_R21] = 0xa8,
[UNW_TILEGX_R22] = 0xb0,
[UNW_TILEGX_R23] = 0xb8,
[UNW_TILEGX_R24] = 0xc0,
[UNW_TILEGX_R25] = 0xc8,
[UNW_TILEGX_R26] = 0xd0,
[UNW_TILEGX_R27] = 0xd8,
[UNW_TILEGX_R28] = 0xe0,
[UNW_TILEGX_R29] = 0xe8,
[UNW_TILEGX_R30] = 0xf0,
[UNW_TILEGX_R31] = 0xf8,
[UNW_TILEGX_R32] = 0x100,
[UNW_TILEGX_R33] = 0x108,
[UNW_TILEGX_R34] = 0x110,
[UNW_TILEGX_R35] = 0x118,
[UNW_TILEGX_R36] = 0x120,
[UNW_TILEGX_R37] = 0x128,
[UNW_TILEGX_R38] = 0x130,
[UNW_TILEGX_R39] = 0x138,
[UNW_TILEGX_R40] = 0x140,
[UNW_TILEGX_R41] = 0x148,
[UNW_TILEGX_R42] = 0x150,
[UNW_TILEGX_R43] = 0x158,
[UNW_TILEGX_R44] = 0x160,
[UNW_TILEGX_R45] = 0x168,
[UNW_TILEGX_R46] = 0x170,
[UNW_TILEGX_R47] = 0x178,
[UNW_TILEGX_R48] = 0x180,
[UNW_TILEGX_R49] = 0x188,
[UNW_TILEGX_R50] = 0x190,
[UNW_TILEGX_R51] = 0x198,
[UNW_TILEGX_R52] = 0x1a0,
[UNW_TILEGX_R53] = 0x1a8,
[UNW_TILEGX_R54] = 0x1b0,
[UNW_TILEGX_R55] = 0x1b8,
[UNW_TILEGX_PC] = 0x1a0
#elif defined(UNW_TARGET_S390X)
[UNW_S390X_R0] = 0x10,
[UNW_S390X_R1] = 0x18,
[UNW_S390X_R2] = 0x20,
[UNW_S390X_R3] = 0x28,
[UNW_S390X_R4] = 0x30,
[UNW_S390X_R5] = 0x38,
[UNW_S390X_R6] = 0x40,
[UNW_S390X_R7] = 0x48,
[UNW_S390X_R8] = 0x50,
[UNW_S390X_R9] = 0x58,
[UNW_S390X_R10] = 0x60,
[UNW_S390X_R11] = 0x68,
[UNW_S390X_R12] = 0x70,
[UNW_S390X_R13] = 0x78,
[UNW_S390X_R14] = 0x80,
[UNW_S390X_R15] = 0x88,
[UNW_S390X_F0] = 0xe0,
[UNW_S390X_F1] = 0xe8,
[UNW_S390X_F2] = 0xf0,
[UNW_S390X_F3] = 0xf8,
[UNW_S390X_F4] = 0x100,
[UNW_S390X_F5] = 0x108,
[UNW_S390X_F6] = 0x110,
[UNW_S390X_F7] = 0x118,
[UNW_S390X_F8] = 0x120,
[UNW_S390X_F9] = 0x128,
[UNW_S390X_F10] = 0x130,
[UNW_S390X_F11] = 0x138,
[UNW_S390X_F12] = 0x140,
[UNW_S390X_F13] = 0x148,
[UNW_S390X_F14] = 0x150,
[UNW_S390X_F15] = 0x150,
[UNW_S390X_IP] = 0x08
#elif defined(UNW_TARGET_RISCV)
#if __riscv_xlen == 64
# define RISCV_REG_OFFSET(x) (8*x)
#elif __riscv_xlen == 32
# define RISCV_REG_OFFSET(x) (4*x)
#else
# error "Unsupported address size"
#endif
[UNW_RISCV_PC] = RISCV_REG_OFFSET(0),
[UNW_RISCV_X1] = RISCV_REG_OFFSET(1),
[UNW_RISCV_X2] = RISCV_REG_OFFSET(2),
[UNW_RISCV_X3] = RISCV_REG_OFFSET(3),
[UNW_RISCV_X4] = RISCV_REG_OFFSET(4),
[UNW_RISCV_X5] = RISCV_REG_OFFSET(5),
[UNW_RISCV_X6] = RISCV_REG_OFFSET(6),
[UNW_RISCV_X7] = RISCV_REG_OFFSET(7),
[UNW_RISCV_X8] = RISCV_REG_OFFSET(8),
[UNW_RISCV_X9] = RISCV_REG_OFFSET(9),
[UNW_RISCV_X10] = RISCV_REG_OFFSET(10),
[UNW_RISCV_X11] = RISCV_REG_OFFSET(11),
[UNW_RISCV_X12] = RISCV_REG_OFFSET(12),
[UNW_RISCV_X13] = RISCV_REG_OFFSET(13),
[UNW_RISCV_X14] = RISCV_REG_OFFSET(14),
[UNW_RISCV_X15] = RISCV_REG_OFFSET(15),
[UNW_RISCV_X16] = RISCV_REG_OFFSET(16),
[UNW_RISCV_X17] = RISCV_REG_OFFSET(17),
[UNW_RISCV_X18] = RISCV_REG_OFFSET(18),
[UNW_RISCV_X19] = RISCV_REG_OFFSET(19),
[UNW_RISCV_X20] = RISCV_REG_OFFSET(20),
[UNW_RISCV_X21] = RISCV_REG_OFFSET(21),
[UNW_RISCV_X22] = RISCV_REG_OFFSET(22),
[UNW_RISCV_X23] = RISCV_REG_OFFSET(23),
[UNW_RISCV_X24] = RISCV_REG_OFFSET(24),
[UNW_RISCV_X25] = RISCV_REG_OFFSET(25),
[UNW_RISCV_X26] = RISCV_REG_OFFSET(26),
[UNW_RISCV_X27] = RISCV_REG_OFFSET(27),
[UNW_RISCV_X28] = RISCV_REG_OFFSET(28),
[UNW_RISCV_X29] = RISCV_REG_OFFSET(29),
[UNW_RISCV_X30] = RISCV_REG_OFFSET(30),
[UNW_RISCV_X31] = RISCV_REG_OFFSET(31),
#elif defined(UNW_TARGET_LOONGARCH64)
# include <asm/reg.h>
[UNW_LOONGARCH64_R0] = LOONGARCH64_EF_R0,
[UNW_LOONGARCH64_R1] = LOONGARCH64_EF_R1,
[UNW_LOONGARCH64_R2] = LOONGARCH64_EF_R2,
[UNW_LOONGARCH64_R3] = LOONGARCH64_EF_R3,
[UNW_LOONGARCH64_R4] = LOONGARCH64_EF_R4,
[UNW_LOONGARCH64_R5] = LOONGARCH64_EF_R5,
[UNW_LOONGARCH64_R6] = LOONGARCH64_EF_R6,
[UNW_LOONGARCH64_R7] = LOONGARCH64_EF_R7,
[UNW_LOONGARCH64_R8] = LOONGARCH64_EF_R8,
[UNW_LOONGARCH64_R9] = LOONGARCH64_EF_R9,
[UNW_LOONGARCH64_R10] = LOONGARCH64_EF_R10,
[UNW_LOONGARCH64_R11] = LOONGARCH64_EF_R11,
[UNW_LOONGARCH64_R12] = LOONGARCH64_EF_R12,
[UNW_LOONGARCH64_R13] = LOONGARCH64_EF_R13,
[UNW_LOONGARCH64_R14] = LOONGARCH64_EF_R14,
[UNW_LOONGARCH64_R15] = LOONGARCH64_EF_R15,
[UNW_LOONGARCH64_R16] = LOONGARCH64_EF_R16,
[UNW_LOONGARCH64_R17] = LOONGARCH64_EF_R17,
[UNW_LOONGARCH64_R18] = LOONGARCH64_EF_R18,
[UNW_LOONGARCH64_R19] = LOONGARCH64_EF_R19,
[UNW_LOONGARCH64_R20] = LOONGARCH64_EF_R20,
[UNW_LOONGARCH64_R21] = LOONGARCH64_EF_R21,
[UNW_LOONGARCH64_R22] = LOONGARCH64_EF_R22,
[UNW_LOONGARCH64_R23] = LOONGARCH64_EF_R23,
[UNW_LOONGARCH64_R24] = LOONGARCH64_EF_R24,
[UNW_LOONGARCH64_R25] = LOONGARCH64_EF_R25,
[UNW_LOONGARCH64_R26] = LOONGARCH64_EF_R26,
[UNW_LOONGARCH64_R27] = LOONGARCH64_EF_R27,
[UNW_LOONGARCH64_R28] = LOONGARCH64_EF_R28,
[UNW_LOONGARCH64_R29] = LOONGARCH64_EF_R29,
[UNW_LOONGARCH64_R30] = LOONGARCH64_EF_R30,
[UNW_LOONGARCH64_R31] = LOONGARCH64_EF_R31,
[UNW_LOONGARCH64_PC] = LOONGARCH64_EF_CSR_EPC
#else
# error Fix me.
#endif
};
|
/* libunwind - a platform-independent unwind library
Copyright (C) 2003-2004 Hewlett-Packard Co
Contributed by David Mosberger-Tang <[email protected]>
Copyright (C) 2013 Linaro Limited
This file is part of libunwind.
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. */
#include "_UPT_internal.h"
#include <stddef.h>
#ifdef HAVE_ASM_PTRACE_H
# include <asm/ptrace.h>
#endif
#ifdef HAVE_ASM_PTRACE_OFFSETS_H
# include <asm/ptrace_offsets.h>
#endif
#if defined(__powerpc64__) && defined(__FreeBSD__)
#define PT_R0 0
#define PT_R1 1
#define PT_R2 2
#define PT_R3 3
#define PT_R4 4
#define PT_R5 5
#define PT_R6 6
#define PT_R7 7
#define PT_R8 8
#define PT_R9 9
#define PT_R10 10
#define PT_R11 11
#define PT_R12 12
#define PT_R13 13
#define PT_R14 14
#define PT_R15 15
#define PT_R16 16
#define PT_R17 17
#define PT_R18 18
#define PT_R19 19
#define PT_R20 20
#define PT_R21 21
#define PT_R22 22
#define PT_R23 23
#define PT_R24 24
#define PT_R25 25
#define PT_R26 26
#define PT_R27 27
#define PT_R28 28
#define PT_R29 29
#define PT_R30 30
#define PT_R31 31
#define PT_NIP 32
#define PT_CTR 35
#define PT_LNK 36
#define PT_XER 37
#define PT_FPR0 48
#define PT_VR0 82
#define PT_VSCR (PT_VR0 + 32*2 + 1)
#define PT_VRSAVE (PT_VR0 + 33*2)
#endif
const int _UPT_reg_offset[UNW_REG_LAST + 1] =
{
#ifdef HAVE_ASM_PTRACE_OFFSETS_H
# ifndef PT_AR_CSD
# define PT_AR_CSD -1 /* this was introduced with rev 2.1 of ia64 */
# endif
[UNW_IA64_GR + 0] = -1, [UNW_IA64_GR + 1] = PT_R1,
[UNW_IA64_GR + 2] = PT_R2, [UNW_IA64_GR + 3] = PT_R3,
[UNW_IA64_GR + 4] = PT_R4, [UNW_IA64_GR + 5] = PT_R5,
[UNW_IA64_GR + 6] = PT_R6, [UNW_IA64_GR + 7] = PT_R7,
[UNW_IA64_GR + 8] = PT_R8, [UNW_IA64_GR + 9] = PT_R9,
[UNW_IA64_GR + 10] = PT_R10, [UNW_IA64_GR + 11] = PT_R11,
[UNW_IA64_GR + 12] = PT_R12, [UNW_IA64_GR + 13] = PT_R13,
[UNW_IA64_GR + 14] = PT_R14, [UNW_IA64_GR + 15] = PT_R15,
[UNW_IA64_GR + 16] = PT_R16, [UNW_IA64_GR + 17] = PT_R17,
[UNW_IA64_GR + 18] = PT_R18, [UNW_IA64_GR + 19] = PT_R19,
[UNW_IA64_GR + 20] = PT_R20, [UNW_IA64_GR + 21] = PT_R21,
[UNW_IA64_GR + 22] = PT_R22, [UNW_IA64_GR + 23] = PT_R23,
[UNW_IA64_GR + 24] = PT_R24, [UNW_IA64_GR + 25] = PT_R25,
[UNW_IA64_GR + 26] = PT_R26, [UNW_IA64_GR + 27] = PT_R27,
[UNW_IA64_GR + 28] = PT_R28, [UNW_IA64_GR + 29] = PT_R29,
[UNW_IA64_GR + 30] = PT_R30, [UNW_IA64_GR + 31] = PT_R31,
[UNW_IA64_NAT+ 0] = -1, [UNW_IA64_NAT+ 1] = PT_NAT_BITS,
[UNW_IA64_NAT+ 2] = PT_NAT_BITS, [UNW_IA64_NAT+ 3] = PT_NAT_BITS,
[UNW_IA64_NAT+ 4] = PT_NAT_BITS, [UNW_IA64_NAT+ 5] = PT_NAT_BITS,
[UNW_IA64_NAT+ 6] = PT_NAT_BITS, [UNW_IA64_NAT+ 7] = PT_NAT_BITS,
[UNW_IA64_NAT+ 8] = PT_NAT_BITS, [UNW_IA64_NAT+ 9] = PT_NAT_BITS,
[UNW_IA64_NAT+ 10] = PT_NAT_BITS, [UNW_IA64_NAT+ 11] = PT_NAT_BITS,
[UNW_IA64_NAT+ 12] = PT_NAT_BITS, [UNW_IA64_NAT+ 13] = PT_NAT_BITS,
[UNW_IA64_NAT+ 14] = PT_NAT_BITS, [UNW_IA64_NAT+ 15] = PT_NAT_BITS,
[UNW_IA64_NAT+ 16] = PT_NAT_BITS, [UNW_IA64_NAT+ 17] = PT_NAT_BITS,
[UNW_IA64_NAT+ 18] = PT_NAT_BITS, [UNW_IA64_NAT+ 19] = PT_NAT_BITS,
[UNW_IA64_NAT+ 20] = PT_NAT_BITS, [UNW_IA64_NAT+ 21] = PT_NAT_BITS,
[UNW_IA64_NAT+ 22] = PT_NAT_BITS, [UNW_IA64_NAT+ 23] = PT_NAT_BITS,
[UNW_IA64_NAT+ 24] = PT_NAT_BITS, [UNW_IA64_NAT+ 25] = PT_NAT_BITS,
[UNW_IA64_NAT+ 26] = PT_NAT_BITS, [UNW_IA64_NAT+ 27] = PT_NAT_BITS,
[UNW_IA64_NAT+ 28] = PT_NAT_BITS, [UNW_IA64_NAT+ 29] = PT_NAT_BITS,
[UNW_IA64_NAT+ 30] = PT_NAT_BITS, [UNW_IA64_NAT+ 31] = PT_NAT_BITS,
[UNW_IA64_FR + 0] = -1, [UNW_IA64_FR + 1] = -1,
[UNW_IA64_FR + 2] = PT_F2, [UNW_IA64_FR + 3] = PT_F3,
[UNW_IA64_FR + 4] = PT_F4, [UNW_IA64_FR + 5] = PT_F5,
[UNW_IA64_FR + 6] = PT_F6, [UNW_IA64_FR + 7] = PT_F7,
[UNW_IA64_FR + 8] = PT_F8, [UNW_IA64_FR + 9] = PT_F9,
[UNW_IA64_FR + 10] = PT_F10, [UNW_IA64_FR + 11] = PT_F11,
[UNW_IA64_FR + 12] = PT_F12, [UNW_IA64_FR + 13] = PT_F13,
[UNW_IA64_FR + 14] = PT_F14, [UNW_IA64_FR + 15] = PT_F15,
[UNW_IA64_FR + 16] = PT_F16, [UNW_IA64_FR + 17] = PT_F17,
[UNW_IA64_FR + 18] = PT_F18, [UNW_IA64_FR + 19] = PT_F19,
[UNW_IA64_FR + 20] = PT_F20, [UNW_IA64_FR + 21] = PT_F21,
[UNW_IA64_FR + 22] = PT_F22, [UNW_IA64_FR + 23] = PT_F23,
[UNW_IA64_FR + 24] = PT_F24, [UNW_IA64_FR + 25] = PT_F25,
[UNW_IA64_FR + 26] = PT_F26, [UNW_IA64_FR + 27] = PT_F27,
[UNW_IA64_FR + 28] = PT_F28, [UNW_IA64_FR + 29] = PT_F29,
[UNW_IA64_FR + 30] = PT_F30, [UNW_IA64_FR + 31] = PT_F31,
[UNW_IA64_FR + 32] = PT_F32, [UNW_IA64_FR + 33] = PT_F33,
[UNW_IA64_FR + 34] = PT_F34, [UNW_IA64_FR + 35] = PT_F35,
[UNW_IA64_FR + 36] = PT_F36, [UNW_IA64_FR + 37] = PT_F37,
[UNW_IA64_FR + 38] = PT_F38, [UNW_IA64_FR + 39] = PT_F39,
[UNW_IA64_FR + 40] = PT_F40, [UNW_IA64_FR + 41] = PT_F41,
[UNW_IA64_FR + 42] = PT_F42, [UNW_IA64_FR + 43] = PT_F43,
[UNW_IA64_FR + 44] = PT_F44, [UNW_IA64_FR + 45] = PT_F45,
[UNW_IA64_FR + 46] = PT_F46, [UNW_IA64_FR + 47] = PT_F47,
[UNW_IA64_FR + 48] = PT_F48, [UNW_IA64_FR + 49] = PT_F49,
[UNW_IA64_FR + 50] = PT_F50, [UNW_IA64_FR + 51] = PT_F51,
[UNW_IA64_FR + 52] = PT_F52, [UNW_IA64_FR + 53] = PT_F53,
[UNW_IA64_FR + 54] = PT_F54, [UNW_IA64_FR + 55] = PT_F55,
[UNW_IA64_FR + 56] = PT_F56, [UNW_IA64_FR + 57] = PT_F57,
[UNW_IA64_FR + 58] = PT_F58, [UNW_IA64_FR + 59] = PT_F59,
[UNW_IA64_FR + 60] = PT_F60, [UNW_IA64_FR + 61] = PT_F61,
[UNW_IA64_FR + 62] = PT_F62, [UNW_IA64_FR + 63] = PT_F63,
[UNW_IA64_FR + 64] = PT_F64, [UNW_IA64_FR + 65] = PT_F65,
[UNW_IA64_FR + 66] = PT_F66, [UNW_IA64_FR + 67] = PT_F67,
[UNW_IA64_FR + 68] = PT_F68, [UNW_IA64_FR + 69] = PT_F69,
[UNW_IA64_FR + 70] = PT_F70, [UNW_IA64_FR + 71] = PT_F71,
[UNW_IA64_FR + 72] = PT_F72, [UNW_IA64_FR + 73] = PT_F73,
[UNW_IA64_FR + 74] = PT_F74, [UNW_IA64_FR + 75] = PT_F75,
[UNW_IA64_FR + 76] = PT_F76, [UNW_IA64_FR + 77] = PT_F77,
[UNW_IA64_FR + 78] = PT_F78, [UNW_IA64_FR + 79] = PT_F79,
[UNW_IA64_FR + 80] = PT_F80, [UNW_IA64_FR + 81] = PT_F81,
[UNW_IA64_FR + 82] = PT_F82, [UNW_IA64_FR + 83] = PT_F83,
[UNW_IA64_FR + 84] = PT_F84, [UNW_IA64_FR + 85] = PT_F85,
[UNW_IA64_FR + 86] = PT_F86, [UNW_IA64_FR + 87] = PT_F87,
[UNW_IA64_FR + 88] = PT_F88, [UNW_IA64_FR + 89] = PT_F89,
[UNW_IA64_FR + 90] = PT_F90, [UNW_IA64_FR + 91] = PT_F91,
[UNW_IA64_FR + 92] = PT_F92, [UNW_IA64_FR + 93] = PT_F93,
[UNW_IA64_FR + 94] = PT_F94, [UNW_IA64_FR + 95] = PT_F95,
[UNW_IA64_FR + 96] = PT_F96, [UNW_IA64_FR + 97] = PT_F97,
[UNW_IA64_FR + 98] = PT_F98, [UNW_IA64_FR + 99] = PT_F99,
[UNW_IA64_FR +100] = PT_F100, [UNW_IA64_FR +101] = PT_F101,
[UNW_IA64_FR +102] = PT_F102, [UNW_IA64_FR +103] = PT_F103,
[UNW_IA64_FR +104] = PT_F104, [UNW_IA64_FR +105] = PT_F105,
[UNW_IA64_FR +106] = PT_F106, [UNW_IA64_FR +107] = PT_F107,
[UNW_IA64_FR +108] = PT_F108, [UNW_IA64_FR +109] = PT_F109,
[UNW_IA64_FR +110] = PT_F110, [UNW_IA64_FR +111] = PT_F111,
[UNW_IA64_FR +112] = PT_F112, [UNW_IA64_FR +113] = PT_F113,
[UNW_IA64_FR +114] = PT_F114, [UNW_IA64_FR +115] = PT_F115,
[UNW_IA64_FR +116] = PT_F116, [UNW_IA64_FR +117] = PT_F117,
[UNW_IA64_FR +118] = PT_F118, [UNW_IA64_FR +119] = PT_F119,
[UNW_IA64_FR +120] = PT_F120, [UNW_IA64_FR +121] = PT_F121,
[UNW_IA64_FR +122] = PT_F122, [UNW_IA64_FR +123] = PT_F123,
[UNW_IA64_FR +124] = PT_F124, [UNW_IA64_FR +125] = PT_F125,
[UNW_IA64_FR +126] = PT_F126, [UNW_IA64_FR +127] = PT_F127,
[UNW_IA64_AR + 0] = -1, [UNW_IA64_AR + 1] = -1,
[UNW_IA64_AR + 2] = -1, [UNW_IA64_AR + 3] = -1,
[UNW_IA64_AR + 4] = -1, [UNW_IA64_AR + 5] = -1,
[UNW_IA64_AR + 6] = -1, [UNW_IA64_AR + 7] = -1,
[UNW_IA64_AR + 8] = -1, [UNW_IA64_AR + 9] = -1,
[UNW_IA64_AR + 10] = -1, [UNW_IA64_AR + 11] = -1,
[UNW_IA64_AR + 12] = -1, [UNW_IA64_AR + 13] = -1,
[UNW_IA64_AR + 14] = -1, [UNW_IA64_AR + 15] = -1,
[UNW_IA64_AR + 16] = PT_AR_RSC, [UNW_IA64_AR + 17] = PT_AR_BSP,
[UNW_IA64_AR + 18] = PT_AR_BSPSTORE,[UNW_IA64_AR + 19] = PT_AR_RNAT,
[UNW_IA64_AR + 20] = -1, [UNW_IA64_AR + 21] = -1,
[UNW_IA64_AR + 22] = -1, [UNW_IA64_AR + 23] = -1,
[UNW_IA64_AR + 24] = -1, [UNW_IA64_AR + 25] = PT_AR_CSD,
[UNW_IA64_AR + 26] = -1, [UNW_IA64_AR + 27] = -1,
[UNW_IA64_AR + 28] = -1, [UNW_IA64_AR + 29] = -1,
[UNW_IA64_AR + 30] = -1, [UNW_IA64_AR + 31] = -1,
[UNW_IA64_AR + 32] = PT_AR_CCV, [UNW_IA64_AR + 33] = -1,
[UNW_IA64_AR + 34] = -1, [UNW_IA64_AR + 35] = -1,
[UNW_IA64_AR + 36] = PT_AR_UNAT, [UNW_IA64_AR + 37] = -1,
[UNW_IA64_AR + 38] = -1, [UNW_IA64_AR + 39] = -1,
[UNW_IA64_AR + 40] = PT_AR_FPSR, [UNW_IA64_AR + 41] = -1,
[UNW_IA64_AR + 42] = -1, [UNW_IA64_AR + 43] = -1,
[UNW_IA64_AR + 44] = -1, [UNW_IA64_AR + 45] = -1,
[UNW_IA64_AR + 46] = -1, [UNW_IA64_AR + 47] = -1,
[UNW_IA64_AR + 48] = -1, [UNW_IA64_AR + 49] = -1,
[UNW_IA64_AR + 50] = -1, [UNW_IA64_AR + 51] = -1,
[UNW_IA64_AR + 52] = -1, [UNW_IA64_AR + 53] = -1,
[UNW_IA64_AR + 54] = -1, [UNW_IA64_AR + 55] = -1,
[UNW_IA64_AR + 56] = -1, [UNW_IA64_AR + 57] = -1,
[UNW_IA64_AR + 58] = -1, [UNW_IA64_AR + 59] = -1,
[UNW_IA64_AR + 60] = -1, [UNW_IA64_AR + 61] = -1,
[UNW_IA64_AR + 62] = -1, [UNW_IA64_AR + 63] = -1,
[UNW_IA64_AR + 64] = PT_AR_PFS, [UNW_IA64_AR + 65] = PT_AR_LC,
[UNW_IA64_AR + 66] = PT_AR_EC, [UNW_IA64_AR + 67] = -1,
[UNW_IA64_AR + 68] = -1, [UNW_IA64_AR + 69] = -1,
[UNW_IA64_AR + 70] = -1, [UNW_IA64_AR + 71] = -1,
[UNW_IA64_AR + 72] = -1, [UNW_IA64_AR + 73] = -1,
[UNW_IA64_AR + 74] = -1, [UNW_IA64_AR + 75] = -1,
[UNW_IA64_AR + 76] = -1, [UNW_IA64_AR + 77] = -1,
[UNW_IA64_AR + 78] = -1, [UNW_IA64_AR + 79] = -1,
[UNW_IA64_AR + 80] = -1, [UNW_IA64_AR + 81] = -1,
[UNW_IA64_AR + 82] = -1, [UNW_IA64_AR + 83] = -1,
[UNW_IA64_AR + 84] = -1, [UNW_IA64_AR + 85] = -1,
[UNW_IA64_AR + 86] = -1, [UNW_IA64_AR + 87] = -1,
[UNW_IA64_AR + 88] = -1, [UNW_IA64_AR + 89] = -1,
[UNW_IA64_AR + 90] = -1, [UNW_IA64_AR + 91] = -1,
[UNW_IA64_AR + 92] = -1, [UNW_IA64_AR + 93] = -1,
[UNW_IA64_AR + 94] = -1, [UNW_IA64_AR + 95] = -1,
[UNW_IA64_AR + 96] = -1, [UNW_IA64_AR + 97] = -1,
[UNW_IA64_AR + 98] = -1, [UNW_IA64_AR + 99] = -1,
[UNW_IA64_AR +100] = -1, [UNW_IA64_AR +101] = -1,
[UNW_IA64_AR +102] = -1, [UNW_IA64_AR +103] = -1,
[UNW_IA64_AR +104] = -1, [UNW_IA64_AR +105] = -1,
[UNW_IA64_AR +106] = -1, [UNW_IA64_AR +107] = -1,
[UNW_IA64_AR +108] = -1, [UNW_IA64_AR +109] = -1,
[UNW_IA64_AR +110] = -1, [UNW_IA64_AR +111] = -1,
[UNW_IA64_AR +112] = -1, [UNW_IA64_AR +113] = -1,
[UNW_IA64_AR +114] = -1, [UNW_IA64_AR +115] = -1,
[UNW_IA64_AR +116] = -1, [UNW_IA64_AR +117] = -1,
[UNW_IA64_AR +118] = -1, [UNW_IA64_AR +119] = -1,
[UNW_IA64_AR +120] = -1, [UNW_IA64_AR +121] = -1,
[UNW_IA64_AR +122] = -1, [UNW_IA64_AR +123] = -1,
[UNW_IA64_AR +124] = -1, [UNW_IA64_AR +125] = -1,
[UNW_IA64_AR +126] = -1, [UNW_IA64_AR +127] = -1,
[UNW_IA64_BR + 0] = PT_B0, [UNW_IA64_BR + 1] = PT_B1,
[UNW_IA64_BR + 2] = PT_B2, [UNW_IA64_BR + 3] = PT_B3,
[UNW_IA64_BR + 4] = PT_B4, [UNW_IA64_BR + 5] = PT_B5,
[UNW_IA64_BR + 6] = PT_B6, [UNW_IA64_BR + 7] = PT_B7,
[UNW_IA64_PR] = PT_PR,
[UNW_IA64_CFM] = PT_CFM,
[UNW_IA64_IP] = PT_CR_IIP
#elif defined(HAVE_TTRACE)
# warning No support for ttrace() yet.
#elif defined(UNW_TARGET_HPPA)
[UNW_HPPA_GR + 0] = 0x000, [UNW_HPPA_GR + 1] = 0x004,
[UNW_HPPA_GR + 2] = 0x008, [UNW_HPPA_GR + 3] = 0x00c,
[UNW_HPPA_GR + 4] = 0x010, [UNW_HPPA_GR + 5] = 0x014,
[UNW_HPPA_GR + 6] = 0x018, [UNW_HPPA_GR + 7] = 0x01c,
[UNW_HPPA_GR + 8] = 0x020, [UNW_HPPA_GR + 9] = 0x024,
[UNW_HPPA_GR + 10] = 0x028, [UNW_HPPA_GR + 11] = 0x02c,
[UNW_HPPA_GR + 12] = 0x030, [UNW_HPPA_GR + 13] = 0x034,
[UNW_HPPA_GR + 14] = 0x038, [UNW_HPPA_GR + 15] = 0x03c,
[UNW_HPPA_GR + 16] = 0x040, [UNW_HPPA_GR + 17] = 0x044,
[UNW_HPPA_GR + 18] = 0x048, [UNW_HPPA_GR + 19] = 0x04c,
[UNW_HPPA_GR + 20] = 0x050, [UNW_HPPA_GR + 21] = 0x054,
[UNW_HPPA_GR + 22] = 0x058, [UNW_HPPA_GR + 23] = 0x05c,
[UNW_HPPA_GR + 24] = 0x060, [UNW_HPPA_GR + 25] = 0x064,
[UNW_HPPA_GR + 26] = 0x068, [UNW_HPPA_GR + 27] = 0x06c,
[UNW_HPPA_GR + 28] = 0x070, [UNW_HPPA_GR + 29] = 0x074,
[UNW_HPPA_GR + 30] = 0x078, [UNW_HPPA_GR + 31] = 0x07c,
[UNW_HPPA_FR + 0] = 0x080, [UNW_HPPA_FR + 1] = 0x088,
[UNW_HPPA_FR + 2] = 0x090, [UNW_HPPA_FR + 3] = 0x098,
[UNW_HPPA_FR + 4] = 0x0a0, [UNW_HPPA_FR + 5] = 0x0a8,
[UNW_HPPA_FR + 6] = 0x0b0, [UNW_HPPA_FR + 7] = 0x0b8,
[UNW_HPPA_FR + 8] = 0x0c0, [UNW_HPPA_FR + 9] = 0x0c8,
[UNW_HPPA_FR + 10] = 0x0d0, [UNW_HPPA_FR + 11] = 0x0d8,
[UNW_HPPA_FR + 12] = 0x0e0, [UNW_HPPA_FR + 13] = 0x0e8,
[UNW_HPPA_FR + 14] = 0x0f0, [UNW_HPPA_FR + 15] = 0x0f8,
[UNW_HPPA_FR + 16] = 0x100, [UNW_HPPA_FR + 17] = 0x108,
[UNW_HPPA_FR + 18] = 0x110, [UNW_HPPA_FR + 19] = 0x118,
[UNW_HPPA_FR + 20] = 0x120, [UNW_HPPA_FR + 21] = 0x128,
[UNW_HPPA_FR + 22] = 0x130, [UNW_HPPA_FR + 23] = 0x138,
[UNW_HPPA_FR + 24] = 0x140, [UNW_HPPA_FR + 25] = 0x148,
[UNW_HPPA_FR + 26] = 0x150, [UNW_HPPA_FR + 27] = 0x158,
[UNW_HPPA_FR + 28] = 0x160, [UNW_HPPA_FR + 29] = 0x168,
[UNW_HPPA_FR + 30] = 0x170, [UNW_HPPA_FR + 31] = 0x178,
[UNW_HPPA_IP] = 0x1a8 /* IAOQ[0] */
#elif defined(UNW_TARGET_X86)
#if defined __FreeBSD__
#define UNW_R_OFF(R, r) \
[UNW_X86_##R] = offsetof(gregset_t, r_##r),
UNW_R_OFF(EAX, eax)
UNW_R_OFF(EDX, edx)
UNW_R_OFF(ECX, ecx)
UNW_R_OFF(EBX, ebx)
UNW_R_OFF(ESI, esi)
UNW_R_OFF(EDI, edi)
UNW_R_OFF(EBP, ebp)
UNW_R_OFF(ESP, esp)
UNW_R_OFF(EIP, eip)
// UNW_R_OFF(CS, cs)
// UNW_R_OFF(EFLAGS, eflags)
// UNW_R_OFF(SS, ss)
#elif defined __linux__
[UNW_X86_EAX] = 0x18,
[UNW_X86_EBX] = 0x00,
[UNW_X86_ECX] = 0x04,
[UNW_X86_EDX] = 0x08,
[UNW_X86_ESI] = 0x0c,
[UNW_X86_EDI] = 0x10,
[UNW_X86_EBP] = 0x14,
[UNW_X86_EIP] = 0x30,
[UNW_X86_ESP] = 0x3c
/* CS = 0x34, */
/* DS = 0x1c, */
/* ES = 0x20, */
/* FS = 0x24, */
/* GS = 0x28, */
/* ORIG_EAX = 0x2c, */
/* EFLAGS = 0x38, */
/* SS = 0x40 */
#else
#error Port me
#endif
#elif defined(UNW_TARGET_X86_64)
#if defined __FreeBSD__
#define UNW_R_OFF(R, r) \
[UNW_X86_64_##R] = offsetof(gregset_t, r_##r),
UNW_R_OFF(RAX, rax)
UNW_R_OFF(RDX, rdx)
UNW_R_OFF(RCX, rcx)
UNW_R_OFF(RBX, rbx)
UNW_R_OFF(RSI, rsi)
UNW_R_OFF(RDI, rdi)
UNW_R_OFF(RBP, rbp)
UNW_R_OFF(RSP, rsp)
UNW_R_OFF(R8, r8)
UNW_R_OFF(R9, r9)
UNW_R_OFF(R10, r10)
UNW_R_OFF(R11, r11)
UNW_R_OFF(R12, r12)
UNW_R_OFF(R13, r13)
UNW_R_OFF(R14, r14)
UNW_R_OFF(R15, r15)
UNW_R_OFF(RIP, rip)
// UNW_R_OFF(CS, cs)
// UNW_R_OFF(EFLAGS, rflags)
// UNW_R_OFF(SS, ss)
#undef UNW_R_OFF
#elif defined __linux__
[UNW_X86_64_RAX] = 0x50,
[UNW_X86_64_RDX] = 0x60,
[UNW_X86_64_RCX] = 0x58,
[UNW_X86_64_RBX] = 0x28,
[UNW_X86_64_RSI] = 0x68,
[UNW_X86_64_RDI] = 0x70,
[UNW_X86_64_RBP] = 0x20,
[UNW_X86_64_RSP] = 0x98,
[UNW_X86_64_R8] = 0x48,
[UNW_X86_64_R9] = 0x40,
[UNW_X86_64_R10] = 0x38,
[UNW_X86_64_R11] = 0x30,
[UNW_X86_64_R12] = 0x18,
[UNW_X86_64_R13] = 0x10,
[UNW_X86_64_R14] = 0x08,
[UNW_X86_64_R15] = 0x00,
[UNW_X86_64_RIP] = 0x80
// [UNW_X86_64_CS] = 0x88,
// [UNW_X86_64_EFLAGS] = 0x90,
// [UNW_X86_64_RSP] = 0x98,
// [UNW_X86_64_SS] = 0xa0
#else
#error Port me
#endif
#elif defined(UNW_TARGET_PPC32) || defined(UNW_TARGET_PPC64)
#define UNW_REG_SLOT_SIZE sizeof(unsigned long)
#define UNW_PPC_R(v) ((v) * UNW_REG_SLOT_SIZE)
#define UNW_PPC_PT(p) UNW_PPC_R(PT_##p)
#define UNW_FP_OFF(b, i) \
[UNW_PPC##b##_F##i] = UNW_PPC_R(PT_FPR0 + i * 8/UNW_REG_SLOT_SIZE)
#define UNW_R_OFF(b, i) \
[UNW_PPC##b##_R##i] = UNW_PPC_R(PT_R##i)
#define UNW_PPC_REGS(b) \
UNW_R_OFF(b, 0), \
UNW_R_OFF(b, 1), \
UNW_R_OFF(b, 2), \
UNW_R_OFF(b, 3), \
UNW_R_OFF(b, 4), \
UNW_R_OFF(b, 5), \
UNW_R_OFF(b, 6), \
UNW_R_OFF(b, 7), \
UNW_R_OFF(b, 8), \
UNW_R_OFF(b, 9), \
UNW_R_OFF(b, 10), \
UNW_R_OFF(b, 11), \
UNW_R_OFF(b, 12), \
UNW_R_OFF(b, 13), \
UNW_R_OFF(b, 14), \
UNW_R_OFF(b, 15), \
UNW_R_OFF(b, 16), \
UNW_R_OFF(b, 17), \
UNW_R_OFF(b, 18), \
UNW_R_OFF(b, 19), \
UNW_R_OFF(b, 20), \
UNW_R_OFF(b, 21), \
UNW_R_OFF(b, 22), \
UNW_R_OFF(b, 23), \
UNW_R_OFF(b, 24), \
UNW_R_OFF(b, 25), \
UNW_R_OFF(b, 26), \
UNW_R_OFF(b, 27), \
UNW_R_OFF(b, 28), \
UNW_R_OFF(b, 29), \
UNW_R_OFF(b, 30), \
UNW_R_OFF(b, 31), \
\
[UNW_PPC##b##_CTR] = UNW_PPC_PT(CTR), \
[UNW_PPC##b##_XER] = UNW_PPC_PT(XER), \
[UNW_PPC##b##_LR] = UNW_PPC_PT(LNK), \
\
UNW_FP_OFF(b, 0), \
UNW_FP_OFF(b, 1), \
UNW_FP_OFF(b, 2), \
UNW_FP_OFF(b, 3), \
UNW_FP_OFF(b, 4), \
UNW_FP_OFF(b, 5), \
UNW_FP_OFF(b, 6), \
UNW_FP_OFF(b, 7), \
UNW_FP_OFF(b, 8), \
UNW_FP_OFF(b, 9), \
UNW_FP_OFF(b, 10), \
UNW_FP_OFF(b, 11), \
UNW_FP_OFF(b, 12), \
UNW_FP_OFF(b, 13), \
UNW_FP_OFF(b, 14), \
UNW_FP_OFF(b, 15), \
UNW_FP_OFF(b, 16), \
UNW_FP_OFF(b, 17), \
UNW_FP_OFF(b, 18), \
UNW_FP_OFF(b, 19), \
UNW_FP_OFF(b, 20), \
UNW_FP_OFF(b, 21), \
UNW_FP_OFF(b, 22), \
UNW_FP_OFF(b, 23), \
UNW_FP_OFF(b, 24), \
UNW_FP_OFF(b, 25), \
UNW_FP_OFF(b, 26), \
UNW_FP_OFF(b, 27), \
UNW_FP_OFF(b, 28), \
UNW_FP_OFF(b, 29), \
UNW_FP_OFF(b, 30), \
UNW_FP_OFF(b, 31)
#define UNW_PPC32_REGS \
[UNW_PPC32_FPSCR] = UNW_PPC_PT(FPSCR), \
[UNW_PPC32_CCR] = UNW_PPC_PT(CCR)
#define UNW_VR_OFF(i) \
[UNW_PPC64_V##i] = UNW_PPC_R(PT_VR0 + i * 2)
#define UNW_PPC64_REGS \
[UNW_PPC64_NIP] = UNW_PPC_PT(NIP), \
[UNW_PPC64_FRAME_POINTER] = -1, \
[UNW_PPC64_ARG_POINTER] = -1, \
[UNW_PPC64_CR0] = -1, \
[UNW_PPC64_CR1] = -1, \
[UNW_PPC64_CR2] = -1, \
[UNW_PPC64_CR3] = -1, \
[UNW_PPC64_CR4] = -1, \
[UNW_PPC64_CR5] = -1, \
[UNW_PPC64_CR6] = -1, \
[UNW_PPC64_CR7] = -1, \
[UNW_PPC64_VRSAVE] = UNW_PPC_PT(VRSAVE), \
[UNW_PPC64_VSCR] = UNW_PPC_PT(VSCR), \
[UNW_PPC64_SPE_ACC] = -1, \
[UNW_PPC64_SPEFSCR] = -1, \
UNW_VR_OFF(0), \
UNW_VR_OFF(1), \
UNW_VR_OFF(2), \
UNW_VR_OFF(3), \
UNW_VR_OFF(4), \
UNW_VR_OFF(5), \
UNW_VR_OFF(6), \
UNW_VR_OFF(7), \
UNW_VR_OFF(8), \
UNW_VR_OFF(9), \
UNW_VR_OFF(10), \
UNW_VR_OFF(11), \
UNW_VR_OFF(12), \
UNW_VR_OFF(13), \
UNW_VR_OFF(14), \
UNW_VR_OFF(15), \
UNW_VR_OFF(16), \
UNW_VR_OFF(17), \
UNW_VR_OFF(18), \
UNW_VR_OFF(19), \
UNW_VR_OFF(20), \
UNW_VR_OFF(21), \
UNW_VR_OFF(22), \
UNW_VR_OFF(23), \
UNW_VR_OFF(24), \
UNW_VR_OFF(25), \
UNW_VR_OFF(26), \
UNW_VR_OFF(27), \
UNW_VR_OFF(28), \
UNW_VR_OFF(29), \
UNW_VR_OFF(30), \
UNW_VR_OFF(31)
#if defined(UNW_TARGET_PPC32)
UNW_PPC_REGS(32),
UNW_PPC32_REGS,
#else
UNW_PPC_REGS(64),
UNW_PPC64_REGS,
#endif
#elif defined(UNW_TARGET_ARM)
#if defined(__linux__) || defined(__FreeBSD__)
[UNW_ARM_R0] = 0x00,
[UNW_ARM_R1] = 0x04,
[UNW_ARM_R2] = 0x08,
[UNW_ARM_R3] = 0x0c,
[UNW_ARM_R4] = 0x10,
[UNW_ARM_R5] = 0x14,
[UNW_ARM_R6] = 0x18,
[UNW_ARM_R7] = 0x1c,
[UNW_ARM_R8] = 0x20,
[UNW_ARM_R9] = 0x24,
[UNW_ARM_R10] = 0x28,
[UNW_ARM_R11] = 0x2c,
[UNW_ARM_R12] = 0x30,
[UNW_ARM_R13] = 0x34,
[UNW_ARM_R14] = 0x38,
[UNW_ARM_R15] = 0x3c,
#else
#error Fix me
#endif
#elif defined(UNW_TARGET_MIPS)
[UNW_MIPS_R0] = 0,
[UNW_MIPS_R1] = 1,
[UNW_MIPS_R2] = 2,
[UNW_MIPS_R3] = 3,
[UNW_MIPS_R4] = 4,
[UNW_MIPS_R5] = 5,
[UNW_MIPS_R6] = 6,
[UNW_MIPS_R7] = 7,
[UNW_MIPS_R8] = 8,
[UNW_MIPS_R9] = 9,
[UNW_MIPS_R10] = 10,
[UNW_MIPS_R11] = 11,
[UNW_MIPS_R12] = 12,
[UNW_MIPS_R13] = 13,
[UNW_MIPS_R14] = 14,
[UNW_MIPS_R15] = 15,
[UNW_MIPS_R16] = 16,
[UNW_MIPS_R17] = 17,
[UNW_MIPS_R18] = 18,
[UNW_MIPS_R19] = 19,
[UNW_MIPS_R20] = 20,
[UNW_MIPS_R21] = 21,
[UNW_MIPS_R22] = 22,
[UNW_MIPS_R23] = 23,
[UNW_MIPS_R24] = 24,
[UNW_MIPS_R25] = 25,
[UNW_MIPS_R26] = 26,
[UNW_MIPS_R27] = 27,
[UNW_MIPS_R28] = 28,
[UNW_MIPS_R29] = 29,
[UNW_MIPS_R30] = 30,
[UNW_MIPS_R31] = 31,
[UNW_MIPS_PC] = 64,
#elif defined(UNW_TARGET_SH)
#elif defined(UNW_TARGET_AARCH64)
[UNW_AARCH64_X0] = 0x00,
[UNW_AARCH64_X1] = 0x08,
[UNW_AARCH64_X2] = 0x10,
[UNW_AARCH64_X3] = 0x18,
[UNW_AARCH64_X4] = 0x20,
[UNW_AARCH64_X5] = 0x28,
[UNW_AARCH64_X6] = 0x30,
[UNW_AARCH64_X7] = 0x38,
[UNW_AARCH64_X8] = 0x40,
[UNW_AARCH64_X9] = 0x48,
[UNW_AARCH64_X10] = 0x50,
[UNW_AARCH64_X11] = 0x58,
[UNW_AARCH64_X12] = 0x60,
[UNW_AARCH64_X13] = 0x68,
[UNW_AARCH64_X14] = 0x70,
[UNW_AARCH64_X15] = 0x78,
[UNW_AARCH64_X16] = 0x80,
[UNW_AARCH64_X17] = 0x88,
[UNW_AARCH64_X18] = 0x90,
[UNW_AARCH64_X19] = 0x98,
[UNW_AARCH64_X20] = 0xa0,
[UNW_AARCH64_X21] = 0xa8,
[UNW_AARCH64_X22] = 0xb0,
[UNW_AARCH64_X23] = 0xb8,
[UNW_AARCH64_X24] = 0xc0,
[UNW_AARCH64_X25] = 0xc8,
[UNW_AARCH64_X26] = 0xd0,
[UNW_AARCH64_X27] = 0xd8,
[UNW_AARCH64_X28] = 0xe0,
[UNW_AARCH64_X29] = 0xe8,
[UNW_AARCH64_X30] = 0xf0,
[UNW_AARCH64_SP] = 0xf8,
[UNW_AARCH64_PC] = 0x100,
[UNW_AARCH64_PSTATE] = 0x108
#elif defined(UNW_TARGET_TILEGX)
[UNW_TILEGX_R0] = 0x00,
[UNW_TILEGX_R1] = 0x08,
[UNW_TILEGX_R2] = 0x10,
[UNW_TILEGX_R3] = 0x08,
[UNW_TILEGX_R4] = 0x20,
[UNW_TILEGX_R5] = 0x28,
[UNW_TILEGX_R6] = 0x30,
[UNW_TILEGX_R7] = 0x38,
[UNW_TILEGX_R8] = 0x40,
[UNW_TILEGX_R9] = 0x48,
[UNW_TILEGX_R10] = 0x50,
[UNW_TILEGX_R11] = 0x58,
[UNW_TILEGX_R12] = 0x60,
[UNW_TILEGX_R13] = 0x68,
[UNW_TILEGX_R14] = 0x70,
[UNW_TILEGX_R15] = 0x78,
[UNW_TILEGX_R16] = 0x80,
[UNW_TILEGX_R17] = 0x88,
[UNW_TILEGX_R18] = 0x90,
[UNW_TILEGX_R19] = 0x98,
[UNW_TILEGX_R20] = 0xa0,
[UNW_TILEGX_R21] = 0xa8,
[UNW_TILEGX_R22] = 0xb0,
[UNW_TILEGX_R23] = 0xb8,
[UNW_TILEGX_R24] = 0xc0,
[UNW_TILEGX_R25] = 0xc8,
[UNW_TILEGX_R26] = 0xd0,
[UNW_TILEGX_R27] = 0xd8,
[UNW_TILEGX_R28] = 0xe0,
[UNW_TILEGX_R29] = 0xe8,
[UNW_TILEGX_R30] = 0xf0,
[UNW_TILEGX_R31] = 0xf8,
[UNW_TILEGX_R32] = 0x100,
[UNW_TILEGX_R33] = 0x108,
[UNW_TILEGX_R34] = 0x110,
[UNW_TILEGX_R35] = 0x118,
[UNW_TILEGX_R36] = 0x120,
[UNW_TILEGX_R37] = 0x128,
[UNW_TILEGX_R38] = 0x130,
[UNW_TILEGX_R39] = 0x138,
[UNW_TILEGX_R40] = 0x140,
[UNW_TILEGX_R41] = 0x148,
[UNW_TILEGX_R42] = 0x150,
[UNW_TILEGX_R43] = 0x158,
[UNW_TILEGX_R44] = 0x160,
[UNW_TILEGX_R45] = 0x168,
[UNW_TILEGX_R46] = 0x170,
[UNW_TILEGX_R47] = 0x178,
[UNW_TILEGX_R48] = 0x180,
[UNW_TILEGX_R49] = 0x188,
[UNW_TILEGX_R50] = 0x190,
[UNW_TILEGX_R51] = 0x198,
[UNW_TILEGX_R52] = 0x1a0,
[UNW_TILEGX_R53] = 0x1a8,
[UNW_TILEGX_R54] = 0x1b0,
[UNW_TILEGX_R55] = 0x1b8,
[UNW_TILEGX_PC] = 0x1a0
#elif defined(UNW_TARGET_S390X)
[UNW_S390X_R0] = 0x10,
[UNW_S390X_R1] = 0x18,
[UNW_S390X_R2] = 0x20,
[UNW_S390X_R3] = 0x28,
[UNW_S390X_R4] = 0x30,
[UNW_S390X_R5] = 0x38,
[UNW_S390X_R6] = 0x40,
[UNW_S390X_R7] = 0x48,
[UNW_S390X_R8] = 0x50,
[UNW_S390X_R9] = 0x58,
[UNW_S390X_R10] = 0x60,
[UNW_S390X_R11] = 0x68,
[UNW_S390X_R12] = 0x70,
[UNW_S390X_R13] = 0x78,
[UNW_S390X_R14] = 0x80,
[UNW_S390X_R15] = 0x88,
[UNW_S390X_F0] = 0xe0,
[UNW_S390X_F1] = 0xe8,
[UNW_S390X_F2] = 0xf0,
[UNW_S390X_F3] = 0xf8,
[UNW_S390X_F4] = 0x100,
[UNW_S390X_F5] = 0x108,
[UNW_S390X_F6] = 0x110,
[UNW_S390X_F7] = 0x118,
[UNW_S390X_F8] = 0x120,
[UNW_S390X_F9] = 0x128,
[UNW_S390X_F10] = 0x130,
[UNW_S390X_F11] = 0x138,
[UNW_S390X_F12] = 0x140,
[UNW_S390X_F13] = 0x148,
[UNW_S390X_F14] = 0x150,
[UNW_S390X_F15] = 0x150,
[UNW_S390X_IP] = 0x08
#elif defined(UNW_TARGET_RISCV)
#if __riscv_xlen == 64
# define RISCV_REG_OFFSET(x) (8*x)
#elif __riscv_xlen == 32
# define RISCV_REG_OFFSET(x) (4*x)
#else
# error "Unsupported address size"
#endif
[UNW_RISCV_PC] = RISCV_REG_OFFSET(0),
[UNW_RISCV_X1] = RISCV_REG_OFFSET(1),
[UNW_RISCV_X2] = RISCV_REG_OFFSET(2),
[UNW_RISCV_X3] = RISCV_REG_OFFSET(3),
[UNW_RISCV_X4] = RISCV_REG_OFFSET(4),
[UNW_RISCV_X5] = RISCV_REG_OFFSET(5),
[UNW_RISCV_X6] = RISCV_REG_OFFSET(6),
[UNW_RISCV_X7] = RISCV_REG_OFFSET(7),
[UNW_RISCV_X8] = RISCV_REG_OFFSET(8),
[UNW_RISCV_X9] = RISCV_REG_OFFSET(9),
[UNW_RISCV_X10] = RISCV_REG_OFFSET(10),
[UNW_RISCV_X11] = RISCV_REG_OFFSET(11),
[UNW_RISCV_X12] = RISCV_REG_OFFSET(12),
[UNW_RISCV_X13] = RISCV_REG_OFFSET(13),
[UNW_RISCV_X14] = RISCV_REG_OFFSET(14),
[UNW_RISCV_X15] = RISCV_REG_OFFSET(15),
[UNW_RISCV_X16] = RISCV_REG_OFFSET(16),
[UNW_RISCV_X17] = RISCV_REG_OFFSET(17),
[UNW_RISCV_X18] = RISCV_REG_OFFSET(18),
[UNW_RISCV_X19] = RISCV_REG_OFFSET(19),
[UNW_RISCV_X20] = RISCV_REG_OFFSET(20),
[UNW_RISCV_X21] = RISCV_REG_OFFSET(21),
[UNW_RISCV_X22] = RISCV_REG_OFFSET(22),
[UNW_RISCV_X23] = RISCV_REG_OFFSET(23),
[UNW_RISCV_X24] = RISCV_REG_OFFSET(24),
[UNW_RISCV_X25] = RISCV_REG_OFFSET(25),
[UNW_RISCV_X26] = RISCV_REG_OFFSET(26),
[UNW_RISCV_X27] = RISCV_REG_OFFSET(27),
[UNW_RISCV_X28] = RISCV_REG_OFFSET(28),
[UNW_RISCV_X29] = RISCV_REG_OFFSET(29),
[UNW_RISCV_X30] = RISCV_REG_OFFSET(30),
[UNW_RISCV_X31] = RISCV_REG_OFFSET(31),
#elif defined(UNW_TARGET_LOONGARCH64)
# include <asm/reg.h>
[UNW_LOONGARCH64_R0] = LOONGARCH64_EF_R0,
[UNW_LOONGARCH64_R1] = LOONGARCH64_EF_R1,
[UNW_LOONGARCH64_R2] = LOONGARCH64_EF_R2,
[UNW_LOONGARCH64_R3] = LOONGARCH64_EF_R3,
[UNW_LOONGARCH64_R4] = LOONGARCH64_EF_R4,
[UNW_LOONGARCH64_R5] = LOONGARCH64_EF_R5,
[UNW_LOONGARCH64_R6] = LOONGARCH64_EF_R6,
[UNW_LOONGARCH64_R7] = LOONGARCH64_EF_R7,
[UNW_LOONGARCH64_R8] = LOONGARCH64_EF_R8,
[UNW_LOONGARCH64_R9] = LOONGARCH64_EF_R9,
[UNW_LOONGARCH64_R10] = LOONGARCH64_EF_R10,
[UNW_LOONGARCH64_R11] = LOONGARCH64_EF_R11,
[UNW_LOONGARCH64_R12] = LOONGARCH64_EF_R12,
[UNW_LOONGARCH64_R13] = LOONGARCH64_EF_R13,
[UNW_LOONGARCH64_R14] = LOONGARCH64_EF_R14,
[UNW_LOONGARCH64_R15] = LOONGARCH64_EF_R15,
[UNW_LOONGARCH64_R16] = LOONGARCH64_EF_R16,
[UNW_LOONGARCH64_R17] = LOONGARCH64_EF_R17,
[UNW_LOONGARCH64_R18] = LOONGARCH64_EF_R18,
[UNW_LOONGARCH64_R19] = LOONGARCH64_EF_R19,
[UNW_LOONGARCH64_R20] = LOONGARCH64_EF_R20,
[UNW_LOONGARCH64_R21] = LOONGARCH64_EF_R21,
[UNW_LOONGARCH64_R22] = LOONGARCH64_EF_R22,
[UNW_LOONGARCH64_R23] = LOONGARCH64_EF_R23,
[UNW_LOONGARCH64_R24] = LOONGARCH64_EF_R24,
[UNW_LOONGARCH64_R25] = LOONGARCH64_EF_R25,
[UNW_LOONGARCH64_R26] = LOONGARCH64_EF_R26,
[UNW_LOONGARCH64_R27] = LOONGARCH64_EF_R27,
[UNW_LOONGARCH64_R28] = LOONGARCH64_EF_R28,
[UNW_LOONGARCH64_R29] = LOONGARCH64_EF_R29,
[UNW_LOONGARCH64_R30] = LOONGARCH64_EF_R30,
[UNW_LOONGARCH64_R31] = LOONGARCH64_EF_R31,
[UNW_LOONGARCH64_PC] = LOONGARCH64_EF_CSR_EPC
#else
# error Fix me.
#endif
};
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/coreclr/pal/src/arch/loongarch64/signalhandlerhelper.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "pal/dbgmsg.h"
SET_DEFAULT_DEBUG_CHANNEL(EXCEPT); // some headers have code with asserts, so do this first
#include "pal/palinternal.h"
#include "pal/context.h"
#include "pal/signal.hpp"
#include "pal/utils.h"
#include <sys/ucontext.h>
/*++
Function :
ExecuteHandlerOnCustomStack
Execute signal handler on a custom stack, the current stack pointer is specified by the customSp
If the customSp is 0, then the handler is executed on the original stack where the signal was fired.
It installs a fake stack frame to enable stack unwinding to the signal source location.
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
returnPoint - context to which the function returns if the common_signal_handler returns
(no return value)
--*/
void ExecuteHandlerOnCustomStack(int code, siginfo_t *siginfo, void *context, size_t customSp, SignalHandlerWorkerReturnPoint* returnPoint)
{
ucontext_t *ucontext = (ucontext_t *)context;
size_t faultSp = (size_t)MCREG_Sp(ucontext->uc_mcontext);
_ASSERTE(IS_ALIGNED(faultSp, 8));
if (customSp == 0)
{
// preserve 128 bytes long red zone and align stack pointer
customSp = ALIGN_DOWN(faultSp - 128, 16);
}
size_t fakeFrameReturnAddress;
if (IS_ALIGNED(faultSp, 16))
{
fakeFrameReturnAddress = (size_t)SignalHandlerWorkerReturnOffset0 + (size_t)CallSignalHandlerWrapper0;
}
else
{
fakeFrameReturnAddress = (size_t)SignalHandlerWorkerReturnOffset8 + (size_t)CallSignalHandlerWrapper8;
}
// preserve 128 bytes long red zone and align stack pointer
size_t* sp = (size_t*)customSp;
// Build fake stack frame to enable the stack unwinder to unwind from signal_handler_worker to the faulting instruction
// pushed RA
*--sp = (size_t)MCREG_Pc(ucontext->uc_mcontext);
// pushed frame pointer
*--sp = (size_t)MCREG_Fp(ucontext->uc_mcontext);
// Switch the current context to the signal_handler_worker and the original stack
CONTEXT context2;
RtlCaptureContext(&context2);
context2.Sp = (size_t)sp;
context2.Fp = (size_t)sp;
context2.Ra = fakeFrameReturnAddress;
context2.Pc = (size_t)signal_handler_worker;
context2.A0 = code;
context2.A1 = (size_t)siginfo;
context2.A2 = (size_t)context;
context2.A3 = (size_t)returnPoint;
RtlRestoreContext(&context2, NULL);
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "pal/dbgmsg.h"
SET_DEFAULT_DEBUG_CHANNEL(EXCEPT); // some headers have code with asserts, so do this first
#include "pal/palinternal.h"
#include "pal/context.h"
#include "pal/signal.hpp"
#include "pal/utils.h"
#include <sys/ucontext.h>
/*++
Function :
ExecuteHandlerOnCustomStack
Execute signal handler on a custom stack, the current stack pointer is specified by the customSp
If the customSp is 0, then the handler is executed on the original stack where the signal was fired.
It installs a fake stack frame to enable stack unwinding to the signal source location.
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
returnPoint - context to which the function returns if the common_signal_handler returns
(no return value)
--*/
void ExecuteHandlerOnCustomStack(int code, siginfo_t *siginfo, void *context, size_t customSp, SignalHandlerWorkerReturnPoint* returnPoint)
{
ucontext_t *ucontext = (ucontext_t *)context;
size_t faultSp = (size_t)MCREG_Sp(ucontext->uc_mcontext);
_ASSERTE(IS_ALIGNED(faultSp, 8));
if (customSp == 0)
{
// preserve 128 bytes long red zone and align stack pointer
customSp = ALIGN_DOWN(faultSp - 128, 16);
}
size_t fakeFrameReturnAddress;
if (IS_ALIGNED(faultSp, 16))
{
fakeFrameReturnAddress = (size_t)SignalHandlerWorkerReturnOffset0 + (size_t)CallSignalHandlerWrapper0;
}
else
{
fakeFrameReturnAddress = (size_t)SignalHandlerWorkerReturnOffset8 + (size_t)CallSignalHandlerWrapper8;
}
// preserve 128 bytes long red zone and align stack pointer
size_t* sp = (size_t*)customSp;
// Build fake stack frame to enable the stack unwinder to unwind from signal_handler_worker to the faulting instruction
// pushed RA
*--sp = (size_t)MCREG_Pc(ucontext->uc_mcontext);
// pushed frame pointer
*--sp = (size_t)MCREG_Fp(ucontext->uc_mcontext);
// Switch the current context to the signal_handler_worker and the original stack
CONTEXT context2;
RtlCaptureContext(&context2);
context2.Sp = (size_t)sp;
context2.Fp = (size_t)sp;
context2.Ra = fakeFrameReturnAddress;
context2.Pc = (size_t)signal_handler_worker;
context2.A0 = code;
context2.A1 = (size_t)siginfo;
context2.A2 = (size_t)context;
context2.A3 = (size_t)returnPoint;
RtlRestoreContext(&context2, NULL);
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/coreclr/pal/src/libunwind/doc/unw_reg_states_iterate.man
|
'\" t
.\" Manual page created with latex2man on Wed Aug 16 11:09:44 PDT 2017
.\" NOTE: This file is generated, DO NOT EDIT.
.de Vb
.ft CW
.nf
..
.de Ve
.ft R
.fi
..
.TH "UNW\\_REG\\_STATES\\_ITERATE" "3" "16 August 2017" "Programming Library " "Programming Library "
.SH NAME
unw_reg_states_iterate
\-\- get register state info on current procedure
.PP
.SH SYNOPSIS
.PP
#include <libunwind.h>
.br
.PP
int
unw_reg_states_iterate(unw_cursor_t *cp,
unw_reg_states_callbackcb,
void *token);
.br
.PP
.SH DESCRIPTION
.PP
The unw_reg_states_iterate()
routine provides
information about the procedure that created the stack frame
identified by argument cp\&.
The cb
argument is a pointer
to a function of type unw_reg_states_callback
which is used to
return the information. The function unw_reg_states_callback
has the
following definition:
.PP
int
( *unw_reg_states_callback)(void *token,
void *reg_states_data,
size_t
reg_states_data_size,
unw_word_t
start_ip,
unw_word_t
end_ip);
.PP
The callback function may be invoked several times for each call of unw_reg_states_iterate\&.
Each call is associcated with a instruction address range and a set of instructions on how to update register values when returning from the procedure in that address range. For each invocation, the arguments to the callback function are:
.TP
void * token
The token value passed to unw_reg_states_callback\&.
.br
.TP
void * reg_states_data
A pointer to data about
updating register values. This data, or a copy of it, can be passed
to unw_apply_reg_state\&.
.br
.TP
int reg_states_data_size
The size of the register update data.
.br
.TP
unw_word_t start_ip
The address of the first
instruction of the address range.
.br
.TP
unw_word_t end_ip
The address of the first
instruction \fIbeyond\fP
the end of the address range.
.br
.PP
.SH RETURN VALUE
.PP
On successful completion, unw_reg_states_iterate()
returns
0. If the callback function returns a nonzero value, that indicates
failure and the function returns immediately. Otherwise the negative
value of one of the error\-codes below is returned.
.PP
.SH THREAD AND SIGNAL SAFETY
.PP
unw_reg_states_iterate()
is thread\-safe. If cursor cp
is
in the local address\-space, this routine is also safe to use from a
signal handler.
.PP
.SH ERRORS
.PP
.TP
UNW_EUNSPEC
An unspecified error occurred.
.TP
UNW_ENOINFO
Libunwind
was unable to locate
unwind\-info for the procedure.
.TP
UNW_EBADVERSION
The unwind\-info for the procedure has
version or format that is not understood by libunwind\&.
.PP
In addition, unw_reg_states_iterate()
may return any error
returned by the access_mem()
call\-back (see
unw_create_addr_space(3)).
.PP
.SH SEE ALSO
.PP
libunwind(3),
unw_apply_reg_state(3)
.PP
.SH AUTHOR
.PP
David Mosberger\-Tang
.br
Email: \[email protected]\fP
.br
WWW: \fBhttp://www.nongnu.org/libunwind/\fP\&.
.\" NOTE: This file is generated, DO NOT EDIT.
|
'\" t
.\" Manual page created with latex2man on Wed Aug 16 11:09:44 PDT 2017
.\" NOTE: This file is generated, DO NOT EDIT.
.de Vb
.ft CW
.nf
..
.de Ve
.ft R
.fi
..
.TH "UNW\\_REG\\_STATES\\_ITERATE" "3" "16 August 2017" "Programming Library " "Programming Library "
.SH NAME
unw_reg_states_iterate
\-\- get register state info on current procedure
.PP
.SH SYNOPSIS
.PP
#include <libunwind.h>
.br
.PP
int
unw_reg_states_iterate(unw_cursor_t *cp,
unw_reg_states_callbackcb,
void *token);
.br
.PP
.SH DESCRIPTION
.PP
The unw_reg_states_iterate()
routine provides
information about the procedure that created the stack frame
identified by argument cp\&.
The cb
argument is a pointer
to a function of type unw_reg_states_callback
which is used to
return the information. The function unw_reg_states_callback
has the
following definition:
.PP
int
( *unw_reg_states_callback)(void *token,
void *reg_states_data,
size_t
reg_states_data_size,
unw_word_t
start_ip,
unw_word_t
end_ip);
.PP
The callback function may be invoked several times for each call of unw_reg_states_iterate\&.
Each call is associcated with a instruction address range and a set of instructions on how to update register values when returning from the procedure in that address range. For each invocation, the arguments to the callback function are:
.TP
void * token
The token value passed to unw_reg_states_callback\&.
.br
.TP
void * reg_states_data
A pointer to data about
updating register values. This data, or a copy of it, can be passed
to unw_apply_reg_state\&.
.br
.TP
int reg_states_data_size
The size of the register update data.
.br
.TP
unw_word_t start_ip
The address of the first
instruction of the address range.
.br
.TP
unw_word_t end_ip
The address of the first
instruction \fIbeyond\fP
the end of the address range.
.br
.PP
.SH RETURN VALUE
.PP
On successful completion, unw_reg_states_iterate()
returns
0. If the callback function returns a nonzero value, that indicates
failure and the function returns immediately. Otherwise the negative
value of one of the error\-codes below is returned.
.PP
.SH THREAD AND SIGNAL SAFETY
.PP
unw_reg_states_iterate()
is thread\-safe. If cursor cp
is
in the local address\-space, this routine is also safe to use from a
signal handler.
.PP
.SH ERRORS
.PP
.TP
UNW_EUNSPEC
An unspecified error occurred.
.TP
UNW_ENOINFO
Libunwind
was unable to locate
unwind\-info for the procedure.
.TP
UNW_EBADVERSION
The unwind\-info for the procedure has
version or format that is not understood by libunwind\&.
.PP
In addition, unw_reg_states_iterate()
may return any error
returned by the access_mem()
call\-back (see
unw_create_addr_space(3)).
.PP
.SH SEE ALSO
.PP
libunwind(3),
unw_apply_reg_state(3)
.PP
.SH AUTHOR
.PP
David Mosberger\-Tang
.br
Email: \[email protected]\fP
.br
WWW: \fBhttp://www.nongnu.org/libunwind/\fP\&.
.\" NOTE: This file is generated, DO NOT EDIT.
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/tracing/eventpipe/common/Microsoft.Diagnostics.NETCore.Client/DiagnosticsClient/DumpType.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.Diagnostics.NETCore.Client
{
public enum DumpType
{
Normal = 1,
WithHeap = 2,
Triage = 3,
Full = 4
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Microsoft.Diagnostics.NETCore.Client
{
public enum DumpType
{
Normal = 1,
WithHeap = 2,
Triage = 3,
Full = 4
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.ComponentModel.TypeConverter/tests/System.ComponentModel.TypeConverter.Tests.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<DefineConstants>$(DefineConstants);FUNCTIONAL_TESTS</DefineConstants>
<IncludeRemoteExecutor>true</IncludeRemoteExecutor>
<RootNamespace />
<AssemblyVersion>9.9.9.9</AssemblyVersion>
<TargetFramework>$(NetCoreAppCurrent)</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Include="Drawing\ColorConverterTests.cs" />
<Compile Include="Drawing\PointConverterTests.cs" />
<Compile Include="Drawing\RectangleConverterTests.cs" />
<Compile Include="Drawing\SizeConverterTests.cs" />
<Compile Include="Drawing\SizeFConverterTests.cs" />
<Compile Include="Design\Serialization\ComponentSerializationServiceTests.cs" />
<Compile Include="Design\StandardCommandsTests.cs" />
<Compile Include="Extensions\EnumeratorExtensions.cs" />
<Compile Include="MaskedTextProviderTests.cs" />
<Compile Include="Mocks\MockDesigner.cs" />
<Compile Include="Mocks\MockDesignerHost.cs" />
<Compile Include="NestedContainerTests.cs" />
<Compile Include="PasswordPropertyTextAttributeTests.cs" />
<Compile Include="MarshalByValueComponentTests.cs" />
<Compile Include="ReflectTypeDescriptionProviderTests.cs" />
<Compile Include="ToolboxItemAttributeTests.cs" />
<Compile Include="ToolboxItemFilterAttributeTests.cs" />
<Compile Include="WarningExceptionTests.cs" />
<Compile Include="RecommendedAsConfigurableAttributeTests.cs" />
<Compile Include="SyntaxCheckTests.cs" />
<Compile Include="RunInstallerAttributeTests.cs" />
<Compile Include="SettingsBindableAttributeTests.cs" />
<Compile Include="RefreshEventArgsTests.cs" />
<Compile Include="LookupBindingPropertiesAttributeTests.cs" />
<Compile Include="ListSortDescriptionTests.cs" />
<Compile Include="ListBindableAttributeTests.cs" />
<Compile Include="ListChangedEventArgsTests.cs" />
<Compile Include="LicenseProviderAttributeTests.cs" />
<Compile Include="LicenseExceptionTests.cs" />
<Compile Include="ExtenderProvidedPropertyAttributeTests.cs" />
<Compile Include="InstanceCreationEditorTests.cs" />
<Compile Include="InstallerTypeAttributeTests.cs" />
<Compile Include="InheritanceAttributeTests.cs" />
<Compile Include="HandledEventArgsTests.cs" />
<Compile Include="BindableAttributeTests.cs" />
<Compile Include="AmbientValueAttributeTests.cs" />
<Compile Include="AddingNewEventArgsTests.cs" />
<Compile Include="ArrayConverterTests.cs" />
<Compile Include="AttributeCollectionTests.cs" />
<Compile Include="AttributeProviderAttributeTests.cs" />
<Compile Include="BaseNumberConverterTests.cs" />
<Compile Include="BindingListTests.cs" />
<Compile Include="BooleanConverterTests.cs" />
<Compile Include="ByteConvertersTests.cs" />
<Compile Include="CharConverterTests.cs" />
<Compile Include="CollectionChangedEventArgsTests.cs" />
<Compile Include="CollectionConverterTests.cs" />
<Compile Include="ComponentConverterTests.cs" />
<Compile Include="ComplexBindingPropertiesAttributeTests.cs" />
<Compile Include="ComponentResourceManagerTests.cs" />
<Compile Include="ComponentEditorTests.cs" />
<Compile Include="ContainerFilterServiceTests.cs" />
<Compile Include="ConverterTestBase.cs" />
<Compile Include="CustomTypeDescriptorTests.cs" />
<Compile Include="DefaultBindingPropertyAttributeTests.cs" />
<Compile Include="DataObjectMethodAttributeTests.cs" />
<Compile Include="DataObjectFieldAttributeTests.cs" />
<Compile Include="DataObjectAttributeTests.cs" />
<Compile Include="DateTimeConverterTests.cs" />
<Compile Include="DateTimeOffsetConverterTests.cs" />
<Compile Include="DecimalConverterTests.cs" />
<Compile Include="DefaultEventAttributeTests.cs" />
<Compile Include="DesignTimeVisibleAttributeTests.cs" />
<Compile Include="DefaultPropertyAttributeTests.cs" />
<Compile Include="Design\DesignerTransactionCloseEventArgsTests.cs" />
<Compile Include="Design\DesignerVerbTests.cs" />
<Compile Include="Design\DesignerVerbCollectionTests.cs" />
<Compile Include="Design\DesigntimeLicenseContextTests.cs" />
<Compile Include="Design\DesigntimeLicenseContextSerializerTests.cs" />
<Compile Include="Design\HelpKeywordAttributeTests.cs" />
<Compile Include="Design\Serialization\MemberRelationshipServiceTests.cs" />
<Compile Include="Design\ServiceContainerTests.cs" />
<Compile Include="Design\StandardToolWindowsTests.cs" />
<Compile Include="Design\Serialization\SerializationStoreTests.cs" />
<Compile Include="Design\Serialization\RootDesignerSerializerAttributeTests.cs" />
<Compile Include="Design\Serialization\ResolveNameEventArgsTests.cs" />
<Compile Include="Design\Serialization\MemberRelationshipTests.cs" />
<Compile Include="Design\Serialization\DesignerLoaderTests.cs" />
<Compile Include="Design\Serialization\DefaultSerializationProviderAttributeTests.cs" />
<Compile Include="Design\MenuCommandTests.cs" />
<Compile Include="LicenseContextTests.cs" />
<Compile Include="TestDesignerHost.cs" />
<Compile Include="DoubleConverterTests.cs" />
<Compile Include="EnumConverterTest.cs" />
<Compile Include="EventDescriptorCollectionTests.cs" />
<Compile Include="EventDescriptorTests.cs" />
<Compile Include="GuidConverterTests.cs" />
<Compile Include="Int16ConverterTests.cs" />
<Compile Include="Int32ConverterTests.cs" />
<Compile Include="Int64ConverterTests.cs" />
<Compile Include="MemberDescriptorTests.cs" />
<Compile Include="DescriptorTestAttribute.cs" />
<Compile Include="DescriptorTestComponent.cs" />
<Compile Include="Mocks\MockEventDescriptor.cs" />
<Compile Include="Mocks\MockPropertyDescriptor.cs" />
<Compile Include="Mocks\MockServiceProvider.cs" />
<Compile Include="MultilineStringConverterTests.cs" />
<Compile Include="NullableConverterTests.cs" />
<Compile Include="ReflectionCachesUpdateHandlerTests.cs" />
<Compile Include="PropertyDescriptorCollectionTests.cs" />
<Compile Include="PropertyDescriptorTests.cs" />
<Compile Include="ProvidePropertyAttributeTests.cs" />
<Compile Include="Resources\TestResx.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>TestResx.resx</DependentUpon>
</Compile>
<Compile Include="SampleClasses.cs" />
<Compile Include="SByteConverterTests.cs" />
<Compile Include="SingleConverterTests.cs" />
<Compile Include="StringConverterTests.cs" />
<Compile Include="Timers\TimersDescriptionAttributeTests.cs" />
<Compile Include="TimeSpanConverterTests.cs" />
<Compile Include="TypeConverterAttributeTests.cs" />
<Compile Include="TypeConverterTests.cs" />
<Compile Include="TypeConverterTestBase.cs" />
<Compile Include="TypeDescriptionProviderTests.cs" />
<Compile Include="TypeDescriptionProviderAttributeTests.cs" />
<Compile Include="TypeDescriptorTests.cs" />
<Compile Include="TypeListConverterTests.cs" />
<Compile Include="UInt16ConverterTests.cs" />
<Compile Include="UInt32ConverterTests.cs" />
<Compile Include="UInt64ConverterTests.cs" />
<Compile Include="UriTypeConverterTests.cs" />
<Compile Include="VersionConverterTests.cs" />
<Compile Include="Drawing\StringTypeConverterTestBase.cs" />
<Compile Include="TimerTests.cs" />
<Compile Include="ContainerTests.cs" />
<Compile Include="CultureInfoConverterTests.cs" />
<Compile Include="LicenseManagerTests.cs" />
<Compile Include="ReferenceConverterTests.cs" />
<Compile Include="ContextStackTests.cs" />
<Compile Include="Design\Serialization\InstanceDescriptorTests.cs" />
<Compile Include="Design\ActiveDesignerEventArgsTests.cs" />
<Compile Include="Design\CheckoutExceptionTests.cs" />
<Compile Include="Design\CommandIDTests.cs" />
<Compile Include="Design\ComponentChangedEventArgsTests.cs" />
<Compile Include="Design\ComponentChangingEventArgsTests.cs" />
<Compile Include="Design\ComponentEventArgsTests.cs" />
<Compile Include="Design\ComponentRenameEventArgsTests.cs" />
<Compile Include="Design\DesignerCollectionTests.cs" />
<Compile Include="Design\DesignerEventArgsTests.cs" />
<Compile Include="Design\DesignerOptionServiceTests.cs" />
<Compile Include="Design\DesignerTransactionTests.cs" />
<Compile Include="Security\Authentication\ExtendedProtection\ExtendedProtectionPolicyTypeConverterTests.cs" />
<Compile Include="XTypeDescriptionProviderTests.cs" />
<Compile Include="$(CommonTestPath)TestUtilities\System\DisableParallelization.cs"
Link="Common\TestUtilities\System\DisableParallelization.cs" />
<TrimmerRootDescriptor Include="$(ILLinkDescriptorsPath)ILLink.Descriptors.Castle.xml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="System.ComponentModel.TypeConverter.TestData" Version="$(SystemComponentModelTypeConverterTestDataVersion)" />
<PackageReference Include="Moq" Version="$(MoqVersion)" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\TestResx.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>TestResx.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<TrimmerRootDescriptor Include="$(MSBuildThisFileDirectory)ILLink.Descriptors.xml" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<DefineConstants>$(DefineConstants);FUNCTIONAL_TESTS</DefineConstants>
<IncludeRemoteExecutor>true</IncludeRemoteExecutor>
<RootNamespace />
<AssemblyVersion>9.9.9.9</AssemblyVersion>
<TargetFramework>$(NetCoreAppCurrent)</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Include="Drawing\ColorConverterTests.cs" />
<Compile Include="Drawing\PointConverterTests.cs" />
<Compile Include="Drawing\RectangleConverterTests.cs" />
<Compile Include="Drawing\SizeConverterTests.cs" />
<Compile Include="Drawing\SizeFConverterTests.cs" />
<Compile Include="Design\Serialization\ComponentSerializationServiceTests.cs" />
<Compile Include="Design\StandardCommandsTests.cs" />
<Compile Include="Extensions\EnumeratorExtensions.cs" />
<Compile Include="MaskedTextProviderTests.cs" />
<Compile Include="Mocks\MockDesigner.cs" />
<Compile Include="Mocks\MockDesignerHost.cs" />
<Compile Include="NestedContainerTests.cs" />
<Compile Include="PasswordPropertyTextAttributeTests.cs" />
<Compile Include="MarshalByValueComponentTests.cs" />
<Compile Include="ReflectTypeDescriptionProviderTests.cs" />
<Compile Include="ToolboxItemAttributeTests.cs" />
<Compile Include="ToolboxItemFilterAttributeTests.cs" />
<Compile Include="WarningExceptionTests.cs" />
<Compile Include="RecommendedAsConfigurableAttributeTests.cs" />
<Compile Include="SyntaxCheckTests.cs" />
<Compile Include="RunInstallerAttributeTests.cs" />
<Compile Include="SettingsBindableAttributeTests.cs" />
<Compile Include="RefreshEventArgsTests.cs" />
<Compile Include="LookupBindingPropertiesAttributeTests.cs" />
<Compile Include="ListSortDescriptionTests.cs" />
<Compile Include="ListBindableAttributeTests.cs" />
<Compile Include="ListChangedEventArgsTests.cs" />
<Compile Include="LicenseProviderAttributeTests.cs" />
<Compile Include="LicenseExceptionTests.cs" />
<Compile Include="ExtenderProvidedPropertyAttributeTests.cs" />
<Compile Include="InstanceCreationEditorTests.cs" />
<Compile Include="InstallerTypeAttributeTests.cs" />
<Compile Include="InheritanceAttributeTests.cs" />
<Compile Include="HandledEventArgsTests.cs" />
<Compile Include="BindableAttributeTests.cs" />
<Compile Include="AmbientValueAttributeTests.cs" />
<Compile Include="AddingNewEventArgsTests.cs" />
<Compile Include="ArrayConverterTests.cs" />
<Compile Include="AttributeCollectionTests.cs" />
<Compile Include="AttributeProviderAttributeTests.cs" />
<Compile Include="BaseNumberConverterTests.cs" />
<Compile Include="BindingListTests.cs" />
<Compile Include="BooleanConverterTests.cs" />
<Compile Include="ByteConvertersTests.cs" />
<Compile Include="CharConverterTests.cs" />
<Compile Include="CollectionChangedEventArgsTests.cs" />
<Compile Include="CollectionConverterTests.cs" />
<Compile Include="ComponentConverterTests.cs" />
<Compile Include="ComplexBindingPropertiesAttributeTests.cs" />
<Compile Include="ComponentResourceManagerTests.cs" />
<Compile Include="ComponentEditorTests.cs" />
<Compile Include="ContainerFilterServiceTests.cs" />
<Compile Include="ConverterTestBase.cs" />
<Compile Include="CustomTypeDescriptorTests.cs" />
<Compile Include="DefaultBindingPropertyAttributeTests.cs" />
<Compile Include="DataObjectMethodAttributeTests.cs" />
<Compile Include="DataObjectFieldAttributeTests.cs" />
<Compile Include="DataObjectAttributeTests.cs" />
<Compile Include="DateTimeConverterTests.cs" />
<Compile Include="DateTimeOffsetConverterTests.cs" />
<Compile Include="DecimalConverterTests.cs" />
<Compile Include="DefaultEventAttributeTests.cs" />
<Compile Include="DesignTimeVisibleAttributeTests.cs" />
<Compile Include="DefaultPropertyAttributeTests.cs" />
<Compile Include="Design\DesignerTransactionCloseEventArgsTests.cs" />
<Compile Include="Design\DesignerVerbTests.cs" />
<Compile Include="Design\DesignerVerbCollectionTests.cs" />
<Compile Include="Design\DesigntimeLicenseContextTests.cs" />
<Compile Include="Design\DesigntimeLicenseContextSerializerTests.cs" />
<Compile Include="Design\HelpKeywordAttributeTests.cs" />
<Compile Include="Design\Serialization\MemberRelationshipServiceTests.cs" />
<Compile Include="Design\ServiceContainerTests.cs" />
<Compile Include="Design\StandardToolWindowsTests.cs" />
<Compile Include="Design\Serialization\SerializationStoreTests.cs" />
<Compile Include="Design\Serialization\RootDesignerSerializerAttributeTests.cs" />
<Compile Include="Design\Serialization\ResolveNameEventArgsTests.cs" />
<Compile Include="Design\Serialization\MemberRelationshipTests.cs" />
<Compile Include="Design\Serialization\DesignerLoaderTests.cs" />
<Compile Include="Design\Serialization\DefaultSerializationProviderAttributeTests.cs" />
<Compile Include="Design\MenuCommandTests.cs" />
<Compile Include="LicenseContextTests.cs" />
<Compile Include="TestDesignerHost.cs" />
<Compile Include="DoubleConverterTests.cs" />
<Compile Include="EnumConverterTest.cs" />
<Compile Include="EventDescriptorCollectionTests.cs" />
<Compile Include="EventDescriptorTests.cs" />
<Compile Include="GuidConverterTests.cs" />
<Compile Include="Int16ConverterTests.cs" />
<Compile Include="Int32ConverterTests.cs" />
<Compile Include="Int64ConverterTests.cs" />
<Compile Include="MemberDescriptorTests.cs" />
<Compile Include="DescriptorTestAttribute.cs" />
<Compile Include="DescriptorTestComponent.cs" />
<Compile Include="Mocks\MockEventDescriptor.cs" />
<Compile Include="Mocks\MockPropertyDescriptor.cs" />
<Compile Include="Mocks\MockServiceProvider.cs" />
<Compile Include="MultilineStringConverterTests.cs" />
<Compile Include="NullableConverterTests.cs" />
<Compile Include="ReflectionCachesUpdateHandlerTests.cs" />
<Compile Include="PropertyDescriptorCollectionTests.cs" />
<Compile Include="PropertyDescriptorTests.cs" />
<Compile Include="ProvidePropertyAttributeTests.cs" />
<Compile Include="Resources\TestResx.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>TestResx.resx</DependentUpon>
</Compile>
<Compile Include="SampleClasses.cs" />
<Compile Include="SByteConverterTests.cs" />
<Compile Include="SingleConverterTests.cs" />
<Compile Include="StringConverterTests.cs" />
<Compile Include="Timers\TimersDescriptionAttributeTests.cs" />
<Compile Include="TimeSpanConverterTests.cs" />
<Compile Include="TypeConverterAttributeTests.cs" />
<Compile Include="TypeConverterTests.cs" />
<Compile Include="TypeConverterTestBase.cs" />
<Compile Include="TypeDescriptionProviderTests.cs" />
<Compile Include="TypeDescriptionProviderAttributeTests.cs" />
<Compile Include="TypeDescriptorTests.cs" />
<Compile Include="TypeListConverterTests.cs" />
<Compile Include="UInt16ConverterTests.cs" />
<Compile Include="UInt32ConverterTests.cs" />
<Compile Include="UInt64ConverterTests.cs" />
<Compile Include="UriTypeConverterTests.cs" />
<Compile Include="VersionConverterTests.cs" />
<Compile Include="Drawing\StringTypeConverterTestBase.cs" />
<Compile Include="TimerTests.cs" />
<Compile Include="ContainerTests.cs" />
<Compile Include="CultureInfoConverterTests.cs" />
<Compile Include="LicenseManagerTests.cs" />
<Compile Include="ReferenceConverterTests.cs" />
<Compile Include="ContextStackTests.cs" />
<Compile Include="Design\Serialization\InstanceDescriptorTests.cs" />
<Compile Include="Design\ActiveDesignerEventArgsTests.cs" />
<Compile Include="Design\CheckoutExceptionTests.cs" />
<Compile Include="Design\CommandIDTests.cs" />
<Compile Include="Design\ComponentChangedEventArgsTests.cs" />
<Compile Include="Design\ComponentChangingEventArgsTests.cs" />
<Compile Include="Design\ComponentEventArgsTests.cs" />
<Compile Include="Design\ComponentRenameEventArgsTests.cs" />
<Compile Include="Design\DesignerCollectionTests.cs" />
<Compile Include="Design\DesignerEventArgsTests.cs" />
<Compile Include="Design\DesignerOptionServiceTests.cs" />
<Compile Include="Design\DesignerTransactionTests.cs" />
<Compile Include="Security\Authentication\ExtendedProtection\ExtendedProtectionPolicyTypeConverterTests.cs" />
<Compile Include="XTypeDescriptionProviderTests.cs" />
<Compile Include="$(CommonTestPath)TestUtilities\System\DisableParallelization.cs"
Link="Common\TestUtilities\System\DisableParallelization.cs" />
<TrimmerRootDescriptor Include="$(ILLinkDescriptorsPath)ILLink.Descriptors.Castle.xml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="System.ComponentModel.TypeConverter.TestData" Version="$(SystemComponentModelTypeConverterTestDataVersion)" />
<PackageReference Include="Moq" Version="$(MoqVersion)" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\TestResx.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>TestResx.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<TrimmerRootDescriptor Include="$(MSBuildThisFileDirectory)ILLink.Descriptors.xml" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/HardwareIntrinsics/General/Vector64/Sqrt.Int32.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void SqrtInt32()
{
var test = new VectorUnaryOpTest__SqrtInt32();
// 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__SqrtInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
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<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int32> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
return testStruct;
}
public void RunStructFldScenario(VectorUnaryOpTest__SqrtInt32 testClass)
{
var result = Vector64.Sqrt(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Vector64<Int32> _clsVar1;
private Vector64<Int32> _fld1;
private DataTable _dataTable;
static VectorUnaryOpTest__SqrtInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
}
public VectorUnaryOpTest__SqrtInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, new Int32[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector64.Sqrt(
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector64).GetMethod(nameof(Vector64.Sqrt), new Type[] {
typeof(Vector64<Int32>)
});
if (method is null)
{
method = typeof(Vector64).GetMethod(nameof(Vector64.Sqrt), 1, new Type[] {
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Int32));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector64.Sqrt(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr);
var result = Vector64.Sqrt(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorUnaryOpTest__SqrtInt32();
var result = Vector64.Sqrt(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector64.Sqrt(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector64.Sqrt(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector64<Int32> op1, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (int)(Math.Sqrt(firstOp[0])))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (int)(Math.Sqrt(firstOp[i])))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.Sqrt)}<Int32>(Vector64<Int32>): {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 SqrtInt32()
{
var test = new VectorUnaryOpTest__SqrtInt32();
// 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__SqrtInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
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<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int32> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
return testStruct;
}
public void RunStructFldScenario(VectorUnaryOpTest__SqrtInt32 testClass)
{
var result = Vector64.Sqrt(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Vector64<Int32> _clsVar1;
private Vector64<Int32> _fld1;
private DataTable _dataTable;
static VectorUnaryOpTest__SqrtInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
}
public VectorUnaryOpTest__SqrtInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, new Int32[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector64.Sqrt(
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector64).GetMethod(nameof(Vector64.Sqrt), new Type[] {
typeof(Vector64<Int32>)
});
if (method is null)
{
method = typeof(Vector64).GetMethod(nameof(Vector64.Sqrt), 1, new Type[] {
typeof(Vector64<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Int32));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector64.Sqrt(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr);
var result = Vector64.Sqrt(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorUnaryOpTest__SqrtInt32();
var result = Vector64.Sqrt(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector64.Sqrt(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector64.Sqrt(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector64<Int32> op1, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (int)(Math.Sqrt(firstOp[0])))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (int)(Math.Sqrt(firstOp[i])))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector64)}.{nameof(Vector64.Sqrt)}<Int32>(Vector64<Int32>): {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,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b40521/b40521.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).cs" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/native/libs/System.Security.Cryptography.Native/pal_ssl.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "pal_crypto_types.h"
#include "pal_compiler.h"
#include "opensslshim.h"
/*
These values should be kept in sync with System.Security.Authentication.SslProtocols.
*/
typedef enum
{
PAL_SSL_NONE = 0,
PAL_SSL_SSL2 = 12,
PAL_SSL_SSL3 = 48,
PAL_SSL_TLS = 192,
PAL_SSL_TLS11 = 768,
PAL_SSL_TLS12 = 3072,
PAL_SSL_TLS13 = 12288,
} SslProtocols;
/*
These values should be kept in sync with System.Net.Security.EncryptionPolicy.
*/
typedef enum
{
RequireEncryption = 0,
AllowNoEncryption,
NoEncryption
} EncryptionPolicy;
/*
These values should be kept in sync with System.Security.Authentication.CipherAlgorithmType.
*/
typedef enum
{
CipherAlgorithmType_None = 0,
Null = 24576,
Des = 26113,
Rc2 = 26114,
TripleDes = 26115,
Aes128 = 26126,
Aes192 = 26127,
Aes256 = 26128,
Aes = 26129,
Rc4 = 26625,
// Algorithm constants which are not present in the managed CipherAlgorithmType enum.
SSL_IDEA = 229380,
SSL_CAMELLIA128 = 229381,
SSL_CAMELLIA256 = 229382,
SSL_eGOST2814789CNT = 229383,
SSL_SEED = 229384,
} CipherAlgorithmType;
/*
These values should be kept in sync with System.Security.Authentication.ExchangeAlgorithmType.
*/
typedef enum
{
ExchangeAlgorithmType_None,
RsaSign = 9216,
RsaKeyX = 41984,
DiffieHellman = 43522,
// ExchangeAlgorithm constants which are not present in the managed ExchangeAlgorithmType enum.
SSL_ECDH = 43525,
SSL_ECDSA = 41475,
SSL_ECDHE = 44550,
SSL_kPSK = 229390,
SSL_kGOST = 229391,
SSL_kSRP = 229392,
SSL_kKRB5 = 229393,
} ExchangeAlgorithmType;
/*
These values should be kept in sync with System.Security.Authentication.HashAlgorithmType.
*/
typedef enum
{
HashAlgorithmType_None = 0,
Md5 = 32771,
Sha1 = 32772,
// HashAlgorithm constants which are not present in the managed HashAlgorithmType enum.
SSL_SHA256 = 32780,
SSL_SHA384 = 32781,
SSL_GOST94 = 229410,
SSL_GOST89 = 229411,
SSL_AEAD = 229412,
} HashAlgorithmType;
typedef enum
{
MD5_HashKeySize = 8 * MD5_DIGEST_LENGTH,
SHA1_HashKeySize = 8 * SHA_DIGEST_LENGTH,
SHA256_HashKeySize = 8 * SHA256_DIGEST_LENGTH,
SHA384_HashKeySize = 8 * SHA384_DIGEST_LENGTH,
GOST_HashKeySize = 256,
Default = 0,
} DataHashSize;
typedef enum
{
PAL_SSL_ERROR_NONE = 0,
PAL_SSL_ERROR_SSL = 1,
PAL_SSL_ERROR_WANT_READ = 2,
PAL_SSL_ERROR_WANT_WRITE = 3,
PAL_SSL_ERROR_SYSCALL = 5,
PAL_SSL_ERROR_ZERO_RETURN = 6,
} SslErrorCode;
// the function pointer definition for the callback used in SslCtxSetAlpnSelectCb
typedef int32_t (*SslCtxSetAlpnCallback)(SSL* ssl,
const uint8_t** out,
uint8_t* outlen,
const uint8_t* in,
uint32_t inlen,
void* arg);
/*
Ensures that libssl is correctly initialized and ready to use.
*/
PALEXPORT void CryptoNative_EnsureLibSslInitialized(void);
/*
Shims the SSLv23_method method.
Returns the requested SSL_METHOD.
*/
PALEXPORT const SSL_METHOD* CryptoNative_SslV2_3Method(void);
/*
Shims the SSL_CTX_new method.
Returns the new SSL_CTX instance.
*/
PALEXPORT SSL_CTX* CryptoNative_SslCtxCreate(const SSL_METHOD* method);
/*
Sets the specified protocols in the SSL_CTX options.
*/
PALEXPORT void CryptoNative_SslCtxSetProtocolOptions(SSL_CTX* ctx, SslProtocols protocols);
/*
Sets internal callback for client certificate selection is set is positive.
It will unset callback if set is zero.
*/
PALEXPORT void CryptoNative_SslSetClientCertCallback(SSL* ssl, int set);
/*
Requests that client sends Post-Handshake Authentication extension in ClientHello.
*/
PALEXPORT void CryptoNative_SslSetPostHandshakeAuth(SSL* ssl, int32_t val);
/*=======
Sets session caching. 0 is disabled.
*/
PALEXPORT void CryptoNative_SslCtxSetCaching(SSL_CTX* ctx, int mode);
/*
Shims the SSL_new method.
Returns the new SSL instance.
*/
PALEXPORT SSL* CryptoNative_SslCreate(SSL_CTX* ctx);
/*
Shims the SSL_get_error method.
Returns the error code for the specified result.
*/
PALEXPORT int32_t CryptoNative_SslGetError(SSL* ssl, int32_t ret);
/*
Cleans up and deletes an SSL instance.
Implemented by calling SSL_free.
No-op if ssl is null.
The given X509 SSL is invalid after this call.
Always succeeds.
*/
PALEXPORT void CryptoNative_SslDestroy(SSL* ssl);
/*
Cleans up and deletes an SSL_CTX instance.
Implemented by calling SSL_CTX_free.
No-op if ctx is null.
The given X509 SSL_CTX is invalid after this call.
Always succeeds.
*/
PALEXPORT void CryptoNative_SslCtxDestroy(SSL_CTX* ctx);
/*
Shims the SSL_set_connect_state method.
*/
PALEXPORT void CryptoNative_SslSetConnectState(SSL* ssl);
/*
Shims the SSL_set_accept_state method.
*/
PALEXPORT void CryptoNative_SslSetAcceptState(SSL* ssl);
/*
Shims the SSL_get_version method.
Returns the protocol version string for the SSL instance.
*/
PALEXPORT const char* CryptoNative_SslGetVersion(SSL* ssl);
/*
Shims the SSL_write method.
Returns the positive number of bytes written when successful, 0 or a negative number
when an error is encountered.
*/
PALEXPORT int32_t CryptoNative_SslWrite(SSL* ssl, const void* buf, int32_t num, int32_t* error);
/*
Shims the SSL_read method.
Returns the positive number of bytes read when successful, 0 or a negative number
when an error is encountered.
*/
PALEXPORT int32_t CryptoNative_SslRead(SSL* ssl, void* buf, int32_t num, int32_t* error);
/*
Shims the SSL_renegotiate method (up to TLS 1.2), or SSL_verify_client_post_handshake (TLS 1.3)
Returns 1 when renegotiation/post-handshake authentication started; 0 on error.
*/
PALEXPORT int32_t CryptoNative_SslRenegotiate(SSL* ssl, int32_t* error);
/*
Shims the SSL_renegotiate_pending method.
Returns 1 when negotiation is requested; 0 once a handshake has finished.
*/
PALEXPORT int32_t CryptoNative_IsSslRenegotiatePending(SSL* ssl);
/*
Shims the SSL_shutdown method.
Returns:
1 if the shutdown was successfully completed;
0 if the shutdown is not yet finished;
<0 if the shutdown was not successful because a fatal error.
*/
PALEXPORT int32_t CryptoNative_SslShutdown(SSL* ssl);
/*
Shims the SSL_set_bio method.
*/
PALEXPORT void CryptoNative_SslSetBio(SSL* ssl, BIO* rbio, BIO* wbio);
/*
Shims the SSL_do_handshake method.
Returns:
1 if the handshake was successful;
0 if the handshake was not successful but was shut down controlled
and by the specifications of the TLS/SSL protocol;
<0 if the handshake was not successful because of a fatal error.
*/
PALEXPORT int32_t CryptoNative_SslDoHandshake(SSL* ssl, int32_t* error);
/*
Gets a value indicating whether the SSL_state is SSL_ST_OK.
Returns 1 if the state is OK, otherwise 0.
*/
PALEXPORT int32_t CryptoNative_IsSslStateOK(SSL* ssl);
/*
Shims the SSL_get_peer_certificate method.
Returns the certificate presented by the peer.
*/
PALEXPORT X509* CryptoNative_SslGetPeerCertificate(SSL* ssl);
/*
Shims the SSL_get_peer_cert_chain method.
Returns the certificate chain presented by the peer.
*/
PALEXPORT X509Stack* CryptoNative_SslGetPeerCertChain(SSL* ssl);
/*
Shims the SSL_use_certificate method.
Returns 1 upon success, otherwise 0.
*/
PALEXPORT int32_t CryptoNative_SslUseCertificate(SSL* ssl, X509* x);
/*
Shims the SSL_use_PrivateKey method.
Returns 1 upon success, otherwise 0.
*/
PALEXPORT int32_t CryptoNative_SslUsePrivateKey(SSL* ssl, EVP_PKEY* pkey);
/*
Shims the SSL_CTX_use_certificate method.
Returns 1 upon success, otherwise 0.
*/
PALEXPORT int32_t CryptoNative_SslCtxUseCertificate(SSL_CTX* ctx, X509* x);
/*
Shims the SSL_CTX_use_PrivateKey method.
Returns 1 upon success, otherwise 0.
*/
PALEXPORT int32_t CryptoNative_SslCtxUsePrivateKey(SSL_CTX* ctx, EVP_PKEY* pkey);
/*
Shims the SSL_CTX_check_private_key method.
Returns 1 upon success, otherwise 0.
*/
PALEXPORT int32_t CryptoNative_SslCtxCheckPrivateKey(SSL_CTX* ctx);
/*
Shims the SSL_CTX_set_quiet_shutdown method.
*/
PALEXPORT void CryptoNative_SslCtxSetQuietShutdown(SSL_CTX* ctx);
/*
Shims the SSL_set_quiet_shutdown method.
*/
PALEXPORT void CryptoNative_SslSetQuietShutdown(SSL* ctx, int mode);
/*
Shims the SSL_get_client_CA_list method.
Returns the list of CA names explicity set.
*/
PALEXPORT X509NameStack* CryptoNative_SslGetClientCAList(SSL* ssl);
/*
Shims the SSL_set_verify method.
*/
PALEXPORT void CryptoNative_SslSetVerifyPeer(SSL* ssl);
/*
Shims SSL_set_ex_data to attach application context.
*/
PALEXPORT int32_t CryptoNative_SslSetData(SSL* ssl, void *ptr);
/*
Shims SSL_get_ex_data to retrieve application context.
*/
PALEXPORT void* CryptoNative_SslGetData(SSL* ssl);
/*
Sets the specified encryption policy on the SSL_CTX.
*/
PALEXPORT int32_t CryptoNative_SslCtxSetEncryptionPolicy(SSL_CTX* ctx, EncryptionPolicy policy);
/*
Sets ciphers (< TLS 1.3) and cipher suites (TLS 1.3) on the SSL_CTX
*/
PALEXPORT int32_t CryptoNative_SslCtxSetCiphers(SSL_CTX* ctx, const char* cipherList, const char* cipherSuites);
PALEXPORT int32_t CryptoNative_SetCiphers(SSL* ssl, const char* cipherList, const char* cipherSuites);
/*
Determines if TLS 1.3 is supported by this OpenSSL implementation
*/
PALEXPORT int32_t CryptoNative_Tls13Supported(void);
/*
Shims the SSL_get_finished method.
*/
PALEXPORT int32_t CryptoNative_SslGetFinished(SSL* ssl, void* buf, int32_t count);
/*
Shims the SSL_get_peer_finished method.
*/
PALEXPORT int32_t CryptoNative_SslGetPeerFinished(SSL* ssl, void* buf, int32_t count);
/*
Returns true/false based on if existing ssl session was re-used or not.
Shims the SSL_session_reused macro.
*/
PALEXPORT int32_t CryptoNative_SslSessionReused(SSL* ssl);
/*
Adds the given certificate to the extra chain certificates associated with ctx.
libssl frees the x509 object.
Returns 1 if success and 0 in case of failure
*/
PALEXPORT int32_t CryptoNative_SslCtxAddExtraChainCert(SSL_CTX* ctx, X509* x509);
/*
Adds the given certificate to the extra chain certificates associated with ssl state.
libssl frees the x509 object.
Returns 1 if success and 0 in case of failure
*/
PALEXPORT int32_t CryptoNative_SslAddExtraChainCert(SSL* ssl, X509* x509);
/*
Adds the names of the given certificates to the list of acceptable issuers sent to
client when requesting a client certificate. Shims the SSL_add_client_CA function.
No transfer of ownership or refcount changes.
Returns 1 if success and 0 in case of failure
*/
PALEXPORT int32_t CryptoNative_SslAddClientCAs(SSL* ssl, X509** x509s, uint32_t count);
/*
Shims the ssl_ctx_set_alpn_select_cb method.
*/
PALEXPORT void CryptoNative_SslCtxSetAlpnSelectCb(SSL_CTX* ctx, SslCtxSetAlpnCallback cb, void *arg);
/*
Shims the ssl_set_alpn_protos method.
Returns 0 on success, non-zero on failure.
*/
PALEXPORT int32_t CryptoNative_SslSetAlpnProtos(SSL* ssl, const uint8_t* protos, uint32_t protos_len);
/*
Shims the ssl_get0_alpn_selected method.
*/
PALEXPORT void CryptoNative_SslGet0AlpnSelected(SSL* ssl, const uint8_t** protocol, uint32_t* len);
/*
Shims the SSL_set_tlsext_host_name method.
*/
PALEXPORT int32_t CryptoNative_SslSetTlsExtHostName(SSL* ssl, uint8_t* name);
/*
Shims the SSL_get_current_cipher and SSL_CIPHER_get_id.
*/
PALEXPORT int32_t CryptoNative_SslGetCurrentCipherId(SSL* ssl, int32_t* cipherId);
/*
Looks up a cipher by the IANA identifier, returns a shared string for the OpenSSL name for the cipher,
and emits a value indicating if the cipher belongs to the SSL2-TLS1.2 list, or the TLS1.3+ list.
*/
PALEXPORT const char* CryptoNative_GetOpenSslCipherSuiteName(SSL* ssl, int32_t cipherSuite, int32_t* isTls12OrLower);
/*
Checks if given protocol version is supported.
*/
PALEXPORT int32_t CryptoNative_OpenSslGetProtocolSupport(SslProtocols protocol);
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "pal_crypto_types.h"
#include "pal_compiler.h"
#include "opensslshim.h"
/*
These values should be kept in sync with System.Security.Authentication.SslProtocols.
*/
typedef enum
{
PAL_SSL_NONE = 0,
PAL_SSL_SSL2 = 12,
PAL_SSL_SSL3 = 48,
PAL_SSL_TLS = 192,
PAL_SSL_TLS11 = 768,
PAL_SSL_TLS12 = 3072,
PAL_SSL_TLS13 = 12288,
} SslProtocols;
/*
These values should be kept in sync with System.Net.Security.EncryptionPolicy.
*/
typedef enum
{
RequireEncryption = 0,
AllowNoEncryption,
NoEncryption
} EncryptionPolicy;
/*
These values should be kept in sync with System.Security.Authentication.CipherAlgorithmType.
*/
typedef enum
{
CipherAlgorithmType_None = 0,
Null = 24576,
Des = 26113,
Rc2 = 26114,
TripleDes = 26115,
Aes128 = 26126,
Aes192 = 26127,
Aes256 = 26128,
Aes = 26129,
Rc4 = 26625,
// Algorithm constants which are not present in the managed CipherAlgorithmType enum.
SSL_IDEA = 229380,
SSL_CAMELLIA128 = 229381,
SSL_CAMELLIA256 = 229382,
SSL_eGOST2814789CNT = 229383,
SSL_SEED = 229384,
} CipherAlgorithmType;
/*
These values should be kept in sync with System.Security.Authentication.ExchangeAlgorithmType.
*/
typedef enum
{
ExchangeAlgorithmType_None,
RsaSign = 9216,
RsaKeyX = 41984,
DiffieHellman = 43522,
// ExchangeAlgorithm constants which are not present in the managed ExchangeAlgorithmType enum.
SSL_ECDH = 43525,
SSL_ECDSA = 41475,
SSL_ECDHE = 44550,
SSL_kPSK = 229390,
SSL_kGOST = 229391,
SSL_kSRP = 229392,
SSL_kKRB5 = 229393,
} ExchangeAlgorithmType;
/*
These values should be kept in sync with System.Security.Authentication.HashAlgorithmType.
*/
typedef enum
{
HashAlgorithmType_None = 0,
Md5 = 32771,
Sha1 = 32772,
// HashAlgorithm constants which are not present in the managed HashAlgorithmType enum.
SSL_SHA256 = 32780,
SSL_SHA384 = 32781,
SSL_GOST94 = 229410,
SSL_GOST89 = 229411,
SSL_AEAD = 229412,
} HashAlgorithmType;
typedef enum
{
MD5_HashKeySize = 8 * MD5_DIGEST_LENGTH,
SHA1_HashKeySize = 8 * SHA_DIGEST_LENGTH,
SHA256_HashKeySize = 8 * SHA256_DIGEST_LENGTH,
SHA384_HashKeySize = 8 * SHA384_DIGEST_LENGTH,
GOST_HashKeySize = 256,
Default = 0,
} DataHashSize;
typedef enum
{
PAL_SSL_ERROR_NONE = 0,
PAL_SSL_ERROR_SSL = 1,
PAL_SSL_ERROR_WANT_READ = 2,
PAL_SSL_ERROR_WANT_WRITE = 3,
PAL_SSL_ERROR_SYSCALL = 5,
PAL_SSL_ERROR_ZERO_RETURN = 6,
} SslErrorCode;
// the function pointer definition for the callback used in SslCtxSetAlpnSelectCb
typedef int32_t (*SslCtxSetAlpnCallback)(SSL* ssl,
const uint8_t** out,
uint8_t* outlen,
const uint8_t* in,
uint32_t inlen,
void* arg);
/*
Ensures that libssl is correctly initialized and ready to use.
*/
PALEXPORT void CryptoNative_EnsureLibSslInitialized(void);
/*
Shims the SSLv23_method method.
Returns the requested SSL_METHOD.
*/
PALEXPORT const SSL_METHOD* CryptoNative_SslV2_3Method(void);
/*
Shims the SSL_CTX_new method.
Returns the new SSL_CTX instance.
*/
PALEXPORT SSL_CTX* CryptoNative_SslCtxCreate(const SSL_METHOD* method);
/*
Sets the specified protocols in the SSL_CTX options.
*/
PALEXPORT void CryptoNative_SslCtxSetProtocolOptions(SSL_CTX* ctx, SslProtocols protocols);
/*
Sets internal callback for client certificate selection is set is positive.
It will unset callback if set is zero.
*/
PALEXPORT void CryptoNative_SslSetClientCertCallback(SSL* ssl, int set);
/*
Requests that client sends Post-Handshake Authentication extension in ClientHello.
*/
PALEXPORT void CryptoNative_SslSetPostHandshakeAuth(SSL* ssl, int32_t val);
/*=======
Sets session caching. 0 is disabled.
*/
PALEXPORT void CryptoNative_SslCtxSetCaching(SSL_CTX* ctx, int mode);
/*
Shims the SSL_new method.
Returns the new SSL instance.
*/
PALEXPORT SSL* CryptoNative_SslCreate(SSL_CTX* ctx);
/*
Shims the SSL_get_error method.
Returns the error code for the specified result.
*/
PALEXPORT int32_t CryptoNative_SslGetError(SSL* ssl, int32_t ret);
/*
Cleans up and deletes an SSL instance.
Implemented by calling SSL_free.
No-op if ssl is null.
The given X509 SSL is invalid after this call.
Always succeeds.
*/
PALEXPORT void CryptoNative_SslDestroy(SSL* ssl);
/*
Cleans up and deletes an SSL_CTX instance.
Implemented by calling SSL_CTX_free.
No-op if ctx is null.
The given X509 SSL_CTX is invalid after this call.
Always succeeds.
*/
PALEXPORT void CryptoNative_SslCtxDestroy(SSL_CTX* ctx);
/*
Shims the SSL_set_connect_state method.
*/
PALEXPORT void CryptoNative_SslSetConnectState(SSL* ssl);
/*
Shims the SSL_set_accept_state method.
*/
PALEXPORT void CryptoNative_SslSetAcceptState(SSL* ssl);
/*
Shims the SSL_get_version method.
Returns the protocol version string for the SSL instance.
*/
PALEXPORT const char* CryptoNative_SslGetVersion(SSL* ssl);
/*
Shims the SSL_write method.
Returns the positive number of bytes written when successful, 0 or a negative number
when an error is encountered.
*/
PALEXPORT int32_t CryptoNative_SslWrite(SSL* ssl, const void* buf, int32_t num, int32_t* error);
/*
Shims the SSL_read method.
Returns the positive number of bytes read when successful, 0 or a negative number
when an error is encountered.
*/
PALEXPORT int32_t CryptoNative_SslRead(SSL* ssl, void* buf, int32_t num, int32_t* error);
/*
Shims the SSL_renegotiate method (up to TLS 1.2), or SSL_verify_client_post_handshake (TLS 1.3)
Returns 1 when renegotiation/post-handshake authentication started; 0 on error.
*/
PALEXPORT int32_t CryptoNative_SslRenegotiate(SSL* ssl, int32_t* error);
/*
Shims the SSL_renegotiate_pending method.
Returns 1 when negotiation is requested; 0 once a handshake has finished.
*/
PALEXPORT int32_t CryptoNative_IsSslRenegotiatePending(SSL* ssl);
/*
Shims the SSL_shutdown method.
Returns:
1 if the shutdown was successfully completed;
0 if the shutdown is not yet finished;
<0 if the shutdown was not successful because a fatal error.
*/
PALEXPORT int32_t CryptoNative_SslShutdown(SSL* ssl);
/*
Shims the SSL_set_bio method.
*/
PALEXPORT void CryptoNative_SslSetBio(SSL* ssl, BIO* rbio, BIO* wbio);
/*
Shims the SSL_do_handshake method.
Returns:
1 if the handshake was successful;
0 if the handshake was not successful but was shut down controlled
and by the specifications of the TLS/SSL protocol;
<0 if the handshake was not successful because of a fatal error.
*/
PALEXPORT int32_t CryptoNative_SslDoHandshake(SSL* ssl, int32_t* error);
/*
Gets a value indicating whether the SSL_state is SSL_ST_OK.
Returns 1 if the state is OK, otherwise 0.
*/
PALEXPORT int32_t CryptoNative_IsSslStateOK(SSL* ssl);
/*
Shims the SSL_get_peer_certificate method.
Returns the certificate presented by the peer.
*/
PALEXPORT X509* CryptoNative_SslGetPeerCertificate(SSL* ssl);
/*
Shims the SSL_get_peer_cert_chain method.
Returns the certificate chain presented by the peer.
*/
PALEXPORT X509Stack* CryptoNative_SslGetPeerCertChain(SSL* ssl);
/*
Shims the SSL_use_certificate method.
Returns 1 upon success, otherwise 0.
*/
PALEXPORT int32_t CryptoNative_SslUseCertificate(SSL* ssl, X509* x);
/*
Shims the SSL_use_PrivateKey method.
Returns 1 upon success, otherwise 0.
*/
PALEXPORT int32_t CryptoNative_SslUsePrivateKey(SSL* ssl, EVP_PKEY* pkey);
/*
Shims the SSL_CTX_use_certificate method.
Returns 1 upon success, otherwise 0.
*/
PALEXPORT int32_t CryptoNative_SslCtxUseCertificate(SSL_CTX* ctx, X509* x);
/*
Shims the SSL_CTX_use_PrivateKey method.
Returns 1 upon success, otherwise 0.
*/
PALEXPORT int32_t CryptoNative_SslCtxUsePrivateKey(SSL_CTX* ctx, EVP_PKEY* pkey);
/*
Shims the SSL_CTX_check_private_key method.
Returns 1 upon success, otherwise 0.
*/
PALEXPORT int32_t CryptoNative_SslCtxCheckPrivateKey(SSL_CTX* ctx);
/*
Shims the SSL_CTX_set_quiet_shutdown method.
*/
PALEXPORT void CryptoNative_SslCtxSetQuietShutdown(SSL_CTX* ctx);
/*
Shims the SSL_set_quiet_shutdown method.
*/
PALEXPORT void CryptoNative_SslSetQuietShutdown(SSL* ctx, int mode);
/*
Shims the SSL_get_client_CA_list method.
Returns the list of CA names explicity set.
*/
PALEXPORT X509NameStack* CryptoNative_SslGetClientCAList(SSL* ssl);
/*
Shims the SSL_set_verify method.
*/
PALEXPORT void CryptoNative_SslSetVerifyPeer(SSL* ssl);
/*
Shims SSL_set_ex_data to attach application context.
*/
PALEXPORT int32_t CryptoNative_SslSetData(SSL* ssl, void *ptr);
/*
Shims SSL_get_ex_data to retrieve application context.
*/
PALEXPORT void* CryptoNative_SslGetData(SSL* ssl);
/*
Sets the specified encryption policy on the SSL_CTX.
*/
PALEXPORT int32_t CryptoNative_SslCtxSetEncryptionPolicy(SSL_CTX* ctx, EncryptionPolicy policy);
/*
Sets ciphers (< TLS 1.3) and cipher suites (TLS 1.3) on the SSL_CTX
*/
PALEXPORT int32_t CryptoNative_SslCtxSetCiphers(SSL_CTX* ctx, const char* cipherList, const char* cipherSuites);
PALEXPORT int32_t CryptoNative_SetCiphers(SSL* ssl, const char* cipherList, const char* cipherSuites);
/*
Determines if TLS 1.3 is supported by this OpenSSL implementation
*/
PALEXPORT int32_t CryptoNative_Tls13Supported(void);
/*
Shims the SSL_get_finished method.
*/
PALEXPORT int32_t CryptoNative_SslGetFinished(SSL* ssl, void* buf, int32_t count);
/*
Shims the SSL_get_peer_finished method.
*/
PALEXPORT int32_t CryptoNative_SslGetPeerFinished(SSL* ssl, void* buf, int32_t count);
/*
Returns true/false based on if existing ssl session was re-used or not.
Shims the SSL_session_reused macro.
*/
PALEXPORT int32_t CryptoNative_SslSessionReused(SSL* ssl);
/*
Adds the given certificate to the extra chain certificates associated with ctx.
libssl frees the x509 object.
Returns 1 if success and 0 in case of failure
*/
PALEXPORT int32_t CryptoNative_SslCtxAddExtraChainCert(SSL_CTX* ctx, X509* x509);
/*
Adds the given certificate to the extra chain certificates associated with ssl state.
libssl frees the x509 object.
Returns 1 if success and 0 in case of failure
*/
PALEXPORT int32_t CryptoNative_SslAddExtraChainCert(SSL* ssl, X509* x509);
/*
Adds the names of the given certificates to the list of acceptable issuers sent to
client when requesting a client certificate. Shims the SSL_add_client_CA function.
No transfer of ownership or refcount changes.
Returns 1 if success and 0 in case of failure
*/
PALEXPORT int32_t CryptoNative_SslAddClientCAs(SSL* ssl, X509** x509s, uint32_t count);
/*
Shims the ssl_ctx_set_alpn_select_cb method.
*/
PALEXPORT void CryptoNative_SslCtxSetAlpnSelectCb(SSL_CTX* ctx, SslCtxSetAlpnCallback cb, void *arg);
/*
Shims the ssl_set_alpn_protos method.
Returns 0 on success, non-zero on failure.
*/
PALEXPORT int32_t CryptoNative_SslSetAlpnProtos(SSL* ssl, const uint8_t* protos, uint32_t protos_len);
/*
Shims the ssl_get0_alpn_selected method.
*/
PALEXPORT void CryptoNative_SslGet0AlpnSelected(SSL* ssl, const uint8_t** protocol, uint32_t* len);
/*
Shims the SSL_set_tlsext_host_name method.
*/
PALEXPORT int32_t CryptoNative_SslSetTlsExtHostName(SSL* ssl, uint8_t* name);
/*
Shims the SSL_get_current_cipher and SSL_CIPHER_get_id.
*/
PALEXPORT int32_t CryptoNative_SslGetCurrentCipherId(SSL* ssl, int32_t* cipherId);
/*
Looks up a cipher by the IANA identifier, returns a shared string for the OpenSSL name for the cipher,
and emits a value indicating if the cipher belongs to the SSL2-TLS1.2 list, or the TLS1.3+ list.
*/
PALEXPORT const char* CryptoNative_GetOpenSslCipherSuiteName(SSL* ssl, int32_t cipherSuite, int32_t* isTls12OrLower);
/*
Checks if given protocol version is supported.
*/
PALEXPORT int32_t CryptoNative_OpenSslGetProtocolSupport(SslProtocols protocol);
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.ObjectModel/src/System/ComponentModel/PropertyChangedEventHandler.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.ComponentModel
{
/// <summary>
/// Represents the method that will handle the <see langword='PropertyChanged'/>
/// event raised when a property is changed on a component.
/// </summary>
public delegate void PropertyChangedEventHandler(object? sender, PropertyChangedEventArgs e);
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.ComponentModel
{
/// <summary>
/// Represents the method that will handle the <see langword='PropertyChanged'/>
/// event raised when a property is changed on a component.
/// </summary>
public delegate void PropertyChangedEventHandler(object? sender, PropertyChangedEventArgs e);
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/coreclr/nativeaot/Runtime/i386/AllocFast.S
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// TODO: Implement
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// TODO: Implement
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Web.HttpUtility/ref/System.Web.HttpUtility.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.Web
{
public sealed partial class HttpUtility
{
public HttpUtility() { }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("s")]
public static string? HtmlAttributeEncode(string? s) { throw null; }
public static void HtmlAttributeEncode(string? s, System.IO.TextWriter output) { }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("s")]
public static string? HtmlDecode(string? s) { throw null; }
public static void HtmlDecode(string? s, System.IO.TextWriter output) { }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("value")]
public static string? HtmlEncode(object? value) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("s")]
public static string? HtmlEncode(string? s) { throw null; }
public static void HtmlEncode(string? s, System.IO.TextWriter output) { }
public static string JavaScriptStringEncode(string? value) { throw null; }
public static string JavaScriptStringEncode(string? value, bool addDoubleQuotes) { throw null; }
public static System.Collections.Specialized.NameValueCollection ParseQueryString(string query) { throw null; }
public static System.Collections.Specialized.NameValueCollection ParseQueryString(string query, System.Text.Encoding encoding) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("bytes")]
public static string? UrlDecode(byte[]? bytes, int offset, int count, System.Text.Encoding e) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("bytes")]
public static string? UrlDecode(byte[]? bytes, System.Text.Encoding e) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static string? UrlDecode(string? str) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static string? UrlDecode(string? str, System.Text.Encoding e) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("bytes")]
public static byte[]? UrlDecodeToBytes(byte[]? bytes) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("bytes")]
public static byte[]? UrlDecodeToBytes(byte[]? bytes, int offset, int count) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static byte[]? UrlDecodeToBytes(string? str) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static byte[]? UrlDecodeToBytes(string? str, System.Text.Encoding e) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("bytes")]
public static string? UrlEncode(byte[]? bytes) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("bytes")]
public static string? UrlEncode(byte[]? bytes, int offset, int count) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static string? UrlEncode(string? str) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static string? UrlEncode(string? str, System.Text.Encoding e) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("bytes")]
public static byte[]? UrlEncodeToBytes(byte[]? bytes) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("bytes")]
public static byte[]? UrlEncodeToBytes(byte[]? bytes, int offset, int count) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static byte[]? UrlEncodeToBytes(string? str) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static byte[]? UrlEncodeToBytes(string? str, System.Text.Encoding e) { throw null; }
[System.ObsoleteAttribute("This method produces non-standards-compliant output and has interoperability issues. The preferred alternative is UrlEncode(String).")]
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static string? UrlEncodeUnicode(string? str) { throw null; }
[System.ObsoleteAttribute("This method produces non-standards-compliant output and has interoperability issues. The preferred alternative is UrlEncodeToBytes(String).")]
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static byte[]? UrlEncodeUnicodeToBytes(string? str) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static string? UrlPathEncode(string? str) { throw null; }
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ------------------------------------------------------------------------------
// Changes to this file must follow the https://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Web
{
public sealed partial class HttpUtility
{
public HttpUtility() { }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("s")]
public static string? HtmlAttributeEncode(string? s) { throw null; }
public static void HtmlAttributeEncode(string? s, System.IO.TextWriter output) { }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("s")]
public static string? HtmlDecode(string? s) { throw null; }
public static void HtmlDecode(string? s, System.IO.TextWriter output) { }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("value")]
public static string? HtmlEncode(object? value) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("s")]
public static string? HtmlEncode(string? s) { throw null; }
public static void HtmlEncode(string? s, System.IO.TextWriter output) { }
public static string JavaScriptStringEncode(string? value) { throw null; }
public static string JavaScriptStringEncode(string? value, bool addDoubleQuotes) { throw null; }
public static System.Collections.Specialized.NameValueCollection ParseQueryString(string query) { throw null; }
public static System.Collections.Specialized.NameValueCollection ParseQueryString(string query, System.Text.Encoding encoding) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("bytes")]
public static string? UrlDecode(byte[]? bytes, int offset, int count, System.Text.Encoding e) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("bytes")]
public static string? UrlDecode(byte[]? bytes, System.Text.Encoding e) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static string? UrlDecode(string? str) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static string? UrlDecode(string? str, System.Text.Encoding e) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("bytes")]
public static byte[]? UrlDecodeToBytes(byte[]? bytes) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("bytes")]
public static byte[]? UrlDecodeToBytes(byte[]? bytes, int offset, int count) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static byte[]? UrlDecodeToBytes(string? str) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static byte[]? UrlDecodeToBytes(string? str, System.Text.Encoding e) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("bytes")]
public static string? UrlEncode(byte[]? bytes) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("bytes")]
public static string? UrlEncode(byte[]? bytes, int offset, int count) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static string? UrlEncode(string? str) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static string? UrlEncode(string? str, System.Text.Encoding e) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("bytes")]
public static byte[]? UrlEncodeToBytes(byte[]? bytes) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("bytes")]
public static byte[]? UrlEncodeToBytes(byte[]? bytes, int offset, int count) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static byte[]? UrlEncodeToBytes(string? str) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static byte[]? UrlEncodeToBytes(string? str, System.Text.Encoding e) { throw null; }
[System.ObsoleteAttribute("This method produces non-standards-compliant output and has interoperability issues. The preferred alternative is UrlEncode(String).")]
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static string? UrlEncodeUnicode(string? str) { throw null; }
[System.ObsoleteAttribute("This method produces non-standards-compliant output and has interoperability issues. The preferred alternative is UrlEncodeToBytes(String).")]
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static byte[]? UrlEncodeUnicodeToBytes(string? str) { throw null; }
[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static string? UrlPathEncode(string? str) { throw null; }
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/Methodical/Boxing/misc/tailjump_il_r.ilproj
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
</PropertyGroup>
<ItemGroup>
<Compile Include="tailjump.il" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
</PropertyGroup>
<ItemGroup>
<Compile Include="tailjump.il" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/jit64/localloc/ehverify/eh13_small.il
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
.assembly extern System.Console
{
.publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A )
.ver 4:0:0:0
}
.assembly extern xunit.core {}
.assembly extern mscorlib{}
.assembly extern localloc_common{}
.assembly 'eh13_small'{}
.class private auto ansi beforefieldinit LocallocTest
extends [mscorlib]System.Object
{
.field private static int32 locallocSize
.method public hidebysig static int32 Main() cil managed
{
.custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = (
01 00 00 00
)
.entrypoint
.maxstack 4
.locals (unsigned int64 local1,
unsigned int64 local2,
int32* intArray1,
int32* intArray2,
int32 retValue)
IL_0000: ldc.i8 0xfedcba9876543210
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: conv.i8
IL_000d: add
IL_000e: stloc.1
IL_000f: ldc.i4.4
IL_0016: localloc
IL_0018: stloc.2
IL_0019: ldc.i4.4
IL_0020: localloc
IL_0022: stloc.3
IL_0023: ldc.i4.1
IL_0028: stsfld int32 LocallocTest::locallocSize
.try
{
IL_002d: ldstr "Test Exception"
IL_0032: newobj instance void [mscorlib]System.Exception::.ctor(string)
IL_0037: throw
} // end .try
filter
{
pop
ldc.i4.1 // invoke handler block
endfilter
}
{
IL_0038: pop
ldstr "In outer Handler block"
call void [System.Console]System.Console::WriteLine(string)
.try
{
IL_0039: ldloc.2
IL_003a: ldsfld int32 LocallocTest::locallocSize
IL_003f: ldc.i4 1000
IL_0044: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*,
int32,
int32)
IL_0049: ldloc.3
IL_004a: ldsfld int32 LocallocTest::locallocSize
IL_004f: ldc.i4 2000
IL_0054: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*,
int32,
int32)
IL_0059: ldstr "Test Exception"
IL_005e: newobj instance void [mscorlib]System.Exception::.ctor(string)
IL_0063: throw
} // end .try
filter
{
pop
ldc.i4.1 // invoke handler block
endfilter
}
{
IL_0064: pop
ldstr "In inner Handler block"
call void [System.Console]System.Console::WriteLine(string)
IL_0065: ldstr "intArray1"
IL_006a: ldloc.2
IL_006b: ldsfld int32 LocallocTest::locallocSize
IL_0070: ldc.i4 0x3e8
IL_0075: call bool [localloc_common]LocallocTesting.Global::verifyStack(string,
int32*,
int32,
int32)
IL_007a: brtrue.s IL_0084
IL_007c: ldc.i4.1
IL_007d: stloc.s retValue
IL_007f: leave IL_0125
IL_0084: ldstr "intArray2"
IL_0089: ldloc.3
IL_008a: ldsfld int32 LocallocTest::locallocSize
IL_008f: ldc.i4 0x7d0
IL_0094: call bool [localloc_common]LocallocTesting.Global::verifyStack(string,
int32*,
int32,
int32)
IL_0099: brtrue.s IL_00a3
IL_009b: ldc.i4.1
IL_009c: stloc.s retValue
IL_009e: leave IL_0125
IL_00a3: leave.s IL_00a5
} // end handler
IL_00a5: leave.s IL_00a7
} // end handler
IL_00a7: ldstr "intArray1"
IL_00ac: ldloc.2
IL_00ad: ldsfld int32 LocallocTest::locallocSize
IL_00b2: ldc.i4 0x3e8
IL_00b7: call bool [localloc_common]LocallocTesting.Global::verifyStack(string,
int32*,
int32,
int32)
IL_00bc: brtrue.s IL_00c3
IL_00be: ldc.i4.1
IL_00bf: stloc.s retValue
IL_00c1: br.s IL_0125
IL_00c3: ldstr "intArray2"
IL_00c8: ldloc.3
IL_00c9: ldsfld int32 LocallocTest::locallocSize
IL_00ce: ldc.i4 2000
IL_00d3: call bool [localloc_common]LocallocTesting.Global::verifyStack(string,
int32*,
int32,
int32)
IL_00d8: brtrue.s IL_00df
IL_00da: ldc.i4.1
IL_00db: stloc.s retValue
IL_00dd: br.s IL_0125
IL_00df: ldstr "local1"
IL_00e4: ldloc.0
IL_00e5: ldc.i8 0xfedcba9876543210
IL_00ee: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string,
unsigned int64,
unsigned int64)
IL_00f3: brtrue.s IL_00fa
IL_00f5: ldc.i4.1
IL_00f6: stloc.s retValue
IL_00f8: br.s IL_0125
IL_00fa: ldstr "local2"
IL_00ff: ldloc.1
IL_0100: ldc.i8 0xfedcba9876543211
IL_0109: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string,
unsigned int64,
unsigned int64)
IL_010e: brtrue.s IL_0115
IL_0110: ldc.i4.1
IL_0111: stloc.s retValue
IL_0113: br.s IL_0125
IL_0115: ldstr "Passed\n"
IL_011a: call void [System.Console]System.Console::WriteLine(string)
IL_011f: ldc.i4.s 100
IL_0121: stloc.s retValue
IL_0123: br.s IL_0125
IL_0125: ldloc.s retValue
IL_0127: ret
} // end of method LocallocTest::Main
.method private hidebysig specialname rtspecialname static
void .cctor() cil managed
{
.maxstack 8
IL_0000: ldc.i4.0
IL_0001: stsfld int32 LocallocTest::locallocSize
IL_0006: ret
} // end of method LocallocTest::.cctor
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method LocallocTest::.ctor
} // end of class LocallocTest
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
.assembly extern System.Console
{
.publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A )
.ver 4:0:0:0
}
.assembly extern xunit.core {}
.assembly extern mscorlib{}
.assembly extern localloc_common{}
.assembly 'eh13_small'{}
.class private auto ansi beforefieldinit LocallocTest
extends [mscorlib]System.Object
{
.field private static int32 locallocSize
.method public hidebysig static int32 Main() cil managed
{
.custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = (
01 00 00 00
)
.entrypoint
.maxstack 4
.locals (unsigned int64 local1,
unsigned int64 local2,
int32* intArray1,
int32* intArray2,
int32 retValue)
IL_0000: ldc.i8 0xfedcba9876543210
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: conv.i8
IL_000d: add
IL_000e: stloc.1
IL_000f: ldc.i4.4
IL_0016: localloc
IL_0018: stloc.2
IL_0019: ldc.i4.4
IL_0020: localloc
IL_0022: stloc.3
IL_0023: ldc.i4.1
IL_0028: stsfld int32 LocallocTest::locallocSize
.try
{
IL_002d: ldstr "Test Exception"
IL_0032: newobj instance void [mscorlib]System.Exception::.ctor(string)
IL_0037: throw
} // end .try
filter
{
pop
ldc.i4.1 // invoke handler block
endfilter
}
{
IL_0038: pop
ldstr "In outer Handler block"
call void [System.Console]System.Console::WriteLine(string)
.try
{
IL_0039: ldloc.2
IL_003a: ldsfld int32 LocallocTest::locallocSize
IL_003f: ldc.i4 1000
IL_0044: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*,
int32,
int32)
IL_0049: ldloc.3
IL_004a: ldsfld int32 LocallocTest::locallocSize
IL_004f: ldc.i4 2000
IL_0054: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*,
int32,
int32)
IL_0059: ldstr "Test Exception"
IL_005e: newobj instance void [mscorlib]System.Exception::.ctor(string)
IL_0063: throw
} // end .try
filter
{
pop
ldc.i4.1 // invoke handler block
endfilter
}
{
IL_0064: pop
ldstr "In inner Handler block"
call void [System.Console]System.Console::WriteLine(string)
IL_0065: ldstr "intArray1"
IL_006a: ldloc.2
IL_006b: ldsfld int32 LocallocTest::locallocSize
IL_0070: ldc.i4 0x3e8
IL_0075: call bool [localloc_common]LocallocTesting.Global::verifyStack(string,
int32*,
int32,
int32)
IL_007a: brtrue.s IL_0084
IL_007c: ldc.i4.1
IL_007d: stloc.s retValue
IL_007f: leave IL_0125
IL_0084: ldstr "intArray2"
IL_0089: ldloc.3
IL_008a: ldsfld int32 LocallocTest::locallocSize
IL_008f: ldc.i4 0x7d0
IL_0094: call bool [localloc_common]LocallocTesting.Global::verifyStack(string,
int32*,
int32,
int32)
IL_0099: brtrue.s IL_00a3
IL_009b: ldc.i4.1
IL_009c: stloc.s retValue
IL_009e: leave IL_0125
IL_00a3: leave.s IL_00a5
} // end handler
IL_00a5: leave.s IL_00a7
} // end handler
IL_00a7: ldstr "intArray1"
IL_00ac: ldloc.2
IL_00ad: ldsfld int32 LocallocTest::locallocSize
IL_00b2: ldc.i4 0x3e8
IL_00b7: call bool [localloc_common]LocallocTesting.Global::verifyStack(string,
int32*,
int32,
int32)
IL_00bc: brtrue.s IL_00c3
IL_00be: ldc.i4.1
IL_00bf: stloc.s retValue
IL_00c1: br.s IL_0125
IL_00c3: ldstr "intArray2"
IL_00c8: ldloc.3
IL_00c9: ldsfld int32 LocallocTest::locallocSize
IL_00ce: ldc.i4 2000
IL_00d3: call bool [localloc_common]LocallocTesting.Global::verifyStack(string,
int32*,
int32,
int32)
IL_00d8: brtrue.s IL_00df
IL_00da: ldc.i4.1
IL_00db: stloc.s retValue
IL_00dd: br.s IL_0125
IL_00df: ldstr "local1"
IL_00e4: ldloc.0
IL_00e5: ldc.i8 0xfedcba9876543210
IL_00ee: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string,
unsigned int64,
unsigned int64)
IL_00f3: brtrue.s IL_00fa
IL_00f5: ldc.i4.1
IL_00f6: stloc.s retValue
IL_00f8: br.s IL_0125
IL_00fa: ldstr "local2"
IL_00ff: ldloc.1
IL_0100: ldc.i8 0xfedcba9876543211
IL_0109: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string,
unsigned int64,
unsigned int64)
IL_010e: brtrue.s IL_0115
IL_0110: ldc.i4.1
IL_0111: stloc.s retValue
IL_0113: br.s IL_0125
IL_0115: ldstr "Passed\n"
IL_011a: call void [System.Console]System.Console::WriteLine(string)
IL_011f: ldc.i4.s 100
IL_0121: stloc.s retValue
IL_0123: br.s IL_0125
IL_0125: ldloc.s retValue
IL_0127: ret
} // end of method LocallocTest::Main
.method private hidebysig specialname rtspecialname static
void .cctor() cil managed
{
.maxstack 8
IL_0000: ldc.i4.0
IL_0001: stsfld int32 LocallocTest::locallocSize
IL_0006: ret
} // end of method LocallocTest::.cctor
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method LocallocTest::.ctor
} // end of class LocallocTest
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b44984/b44984.ilproj
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).il" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).il" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Console/tests/WindowAndCursorProps.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.IO;
using Microsoft.DotNet.RemoteExecutor;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;
public class WindowAndCursorProps
{
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser & ~TestPlatforms.iOS & ~TestPlatforms.MacCatalyst & ~TestPlatforms.tvOS)] // Expected behavior specific to Unix
public static void BufferWidth_GetUnix_ReturnsWindowWidth()
{
Assert.Equal(Console.WindowWidth, Console.BufferWidth);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void BufferWidth_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.BufferWidth = 1);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser & ~TestPlatforms.iOS & ~TestPlatforms.MacCatalyst & ~TestPlatforms.tvOS)] // Expected behavior specific to Unix
public static void BufferHeight_GetUnix_ReturnsWindowHeight()
{
Assert.Equal(Console.WindowHeight, Console.BufferHeight);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void BufferHeight_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.BufferHeight = 1);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void SetBufferSize_Unix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.SetBufferSize(0, 0));
}
[Theory]
[PlatformSpecific(TestPlatforms.Windows)]
[InlineData(0)]
[InlineData(-1)]
public static void WindowWidth_SetInvalid_ThrowsArgumentOutOfRangeException(int value)
{
if (Console.IsOutputRedirected)
{
Assert.Throws<IOException>(() => Console.WindowWidth = value);
}
else
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("width", () => Console.WindowWidth = value);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser & ~TestPlatforms.iOS & ~TestPlatforms.MacCatalyst & ~TestPlatforms.tvOS)] // Expected behavior specific to Unix
public static void WindowWidth_GetUnix_Success()
{
// Validate that Console.WindowWidth returns some value in a non-redirected o/p.
Helpers.RunInNonRedirectedOutput((data) => Console.WriteLine(Console.WindowWidth));
Helpers.RunInRedirectedOutput((data) => Console.WriteLine(Console.WindowWidth));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser)] // Expected behavior specific to Unix
public static void WindowWidth_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.WindowWidth = 100);
}
[Theory]
[PlatformSpecific(TestPlatforms.Windows)] // Expected behavior specific to Windows
[InlineData(0)]
[InlineData(-1)]
public static void WindowHeight_SetInvalid_ThrowsArgumentOutOfRangeException(int value)
{
if (Console.IsOutputRedirected)
{
Assert.Throws<IOException>(() => Console.WindowHeight = value);
}
else
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("height", () => Console.WindowHeight = value);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser & ~TestPlatforms.iOS & ~TestPlatforms.MacCatalyst & ~TestPlatforms.tvOS)] // Expected behavior specific to Unix
public static void WindowHeight_GetUnix_Success()
{
// Validate that Console.WindowHeight returns some value in a non-redirected o/p.
Helpers.RunInNonRedirectedOutput((data) => Console.WriteLine(Console.WindowHeight));
Helpers.RunInRedirectedOutput((data) => Console.WriteLine(Console.WindowHeight));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void WindowHeight_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.WindowHeight = 100);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser & ~TestPlatforms.iOS & ~TestPlatforms.MacCatalyst & ~TestPlatforms.tvOS)] // Expected behavior specific to Unix
public static void LargestWindowWidth_UnixGet_ReturnsExpected()
{
Helpers.RunInNonRedirectedOutput((data) => Assert.Equal(Console.WindowWidth, Console.LargestWindowWidth));
Helpers.RunInRedirectedOutput((data) => Assert.Equal(Console.WindowWidth, Console.LargestWindowWidth));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser & ~TestPlatforms.iOS & ~TestPlatforms.MacCatalyst & ~TestPlatforms.tvOS)] // Expected behavior specific to Unix
public static void LargestWindowHeight_UnixGet_ReturnsExpected()
{
Helpers.RunInNonRedirectedOutput((data) => Assert.Equal(Console.WindowHeight, Console.LargestWindowHeight));
Helpers.RunInRedirectedOutput((data) => Assert.Equal(Console.WindowHeight, Console.LargestWindowHeight));
}
[Fact]
[PlatformSpecific(TestPlatforms.Browser)]
public static void WindowHeight_Getter_Throws_PlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.WindowHeight);
}
[Fact]
[PlatformSpecific(TestPlatforms.Browser)]
public static void WindowWidth_Getter_Throws_PlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.WindowWidth);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void WindowLeft_GetUnix_ReturnsZero()
{
Assert.Equal(0, Console.WindowLeft);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void WindowLeft_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.WindowLeft = 0);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void WindowTop_GetUnix_ReturnsZero()
{
Assert.Equal(0, Console.WindowTop);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void WindowTop_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.WindowTop = 0);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Expected behavior specific to Windows
public static void WindowLeftTop_Windows()
{
if (Console.IsOutputRedirected)
{
Assert.Throws<IOException>(() => Console.WindowLeft);
Assert.Throws<IOException>(() => Console.WindowTop);
}
else
{
Console.WriteLine(Console.WindowLeft);
Console.WriteLine(Console.WindowTop);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void CursorVisible_GetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.CursorVisible);
}
[Theory]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser & ~TestPlatforms.iOS & ~TestPlatforms.MacCatalyst & ~TestPlatforms.tvOS )] // Expected behavior specific to Unix
[InlineData(true)]
[InlineData(false)]
public static void CursorVisible_SetUnixRedirected_Nop(bool value)
{
Helpers.RunInRedirectedOutput((data) => {
Console.CursorVisible = value;
Assert.Equal(0, data.ToArray().Length);
});
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void Title_GetUnix_ThrowPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.Title);
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void Title_SetUnix_Success()
{
RemoteExecutor.Invoke(() =>
{
Console.Title = "Title set by unit test";
}).Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public static void Title_GetWindows_ReturnsNonNull()
{
Assert.NotNull(Console.Title);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))]
[PlatformSpecific(TestPlatforms.Windows)]
public static void Title_Get_Windows_NoNulls()
{
string title = Console.Title;
string trimmedTitle = title.TrimEnd('\0');
Assert.Equal(trimmedTitle, title);
}
private static bool IsNotWindowsNanoServerAndNotServerCoreAndRemoteExecutorSupported => PlatformDetection.IsNotWindowsNanoNorServerCore && RemoteExecutor.IsSupported;
[ConditionalTheory(nameof(IsNotWindowsNanoServerAndNotServerCoreAndRemoteExecutorSupported))] // Nano and Server Core currently ignore set title
[ActiveIssue("https://github.com/dotnet/runtime/issues/34454", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[InlineData(0)]
[InlineData(1)]
[InlineData(254)]
[InlineData(255)]
[InlineData(256)]
[InlineData(257)]
[InlineData(511)]
[InlineData(512)]
[InlineData(513)]
[InlineData(1024)]
[PlatformSpecific(TestPlatforms.Windows)]
public static void Title_Set_Windows(int lengthOfTitle)
{
// Try to set the title to some other value.
RemoteExecutor.Invoke(lengthOfTitleString =>
{
string newTitle = new string('a', int.Parse(lengthOfTitleString));
Console.Title = newTitle;
if (newTitle.Length >= 511 && !PlatformDetection.IsNetCore && PlatformDetection.IsWindows10Version1703OrGreater && !PlatformDetection.IsWindows10Version1709OrGreater)
{
// RS2 has a bug when getting the window title when the title length is longer than 513 character
Assert.Throws<IOException>(() => Console.Title);
}
else
{
Assert.Equal(newTitle, Console.Title);
}
}, lengthOfTitle.ToString()).Dispose();
}
[Fact]
public static void Title_SetNull_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("value", () => Console.Title = null);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
[OuterLoop] // makes noise, not very inner-loop friendly
public static void Beep_Invoke_Success()
{
// Nothing to verify; just run the code.
Console.Beep();
}
[Fact]
[OuterLoop] // makes noise, not very inner-loop friendly
[PlatformSpecific(TestPlatforms.Windows)]
public static void BeepWithFrequency_Invoke_Success()
{
// Nothing to verify; just run the code.
Console.Beep(800, 200);
}
[Theory]
[PlatformSpecific(TestPlatforms.Windows)]
[InlineData(36)]
[InlineData(32768)]
public void BeepWithFrequency_InvalidFrequency_ThrowsArgumentOutOfRangeException(int frequency)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("frequency", () => Console.Beep(frequency, 200));
}
[Theory]
[PlatformSpecific(TestPlatforms.Windows)]
[InlineData(0)]
[InlineData(-1)]
public void BeepWithFrequency_InvalidDuration_ThrowsArgumentOutOfRangeException(int duration)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("duration", () => Console.Beep(800, duration));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void BeepWithFrequency_Unix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.Beep(800, 200));
}
[Fact]
[OuterLoop] // clears the screen, not very inner-loop friendly
public static void Clear_Invoke_Success()
{
if (!OperatingSystem.IsWindows() || (!Console.IsInputRedirected && !Console.IsOutputRedirected))
{
// Nothing to verify; just run the code.
Console.Clear();
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Browser)]
public static void SetCursorPosition_Throws_PlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.SetCursorPosition(0, 0));
}
[Fact]
[SkipOnPlatform(TestPlatforms.Browser | TestPlatforms.iOS | TestPlatforms.MacCatalyst | TestPlatforms.tvOS, "Not supported on Browser, iOS, MacCatalyst, or tvOS.")]
public static void SetCursorPosition_Invoke_Success()
{
if (!OperatingSystem.IsWindows() || (!Console.IsInputRedirected && !Console.IsOutputRedirected))
{
int origLeft = Console.CursorLeft;
int origTop = Console.CursorTop;
// Nothing to verify; just run the code.
// On windows, we might end of throwing IOException, since the handles are redirected.
Console.SetCursorPosition(0, 0);
Console.SetCursorPosition(1, 2);
Console.SetCursorPosition(origLeft, origTop);
}
}
[Theory]
[InlineData(-1)]
[InlineData(short.MaxValue + 1)]
public void SetCursorPosition_InvalidPosition_ThrowsArgumentOutOfRangeException(int value)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("left", () => Console.SetCursorPosition(value, 100));
AssertExtensions.Throws<ArgumentOutOfRangeException>("top", () => Console.SetCursorPosition(100, value));
}
[Fact]
[SkipOnPlatform(TestPlatforms.Browser | TestPlatforms.iOS | TestPlatforms.MacCatalyst | TestPlatforms.tvOS, "Not supported on Browser, iOS, MacCatalyst, or tvOS.")]
public static void GetCursorPosition_Invoke_ReturnsExpected()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
int origLeft = Console.CursorLeft, origTop = Console.CursorTop;
(int, int) origTuple = Console.GetCursorPosition();
Console.SetCursorPosition(10, 12);
Assert.Equal(10, Console.CursorLeft);
Assert.Equal(12, Console.CursorTop);
Assert.Equal((10, 12), Console.GetCursorPosition());
Console.SetCursorPosition(origLeft, origTop);
Assert.Equal(origLeft, Console.CursorLeft);
Assert.Equal(origTop, Console.CursorTop);
Assert.Equal(origTuple, Console.GetCursorPosition());
}
else if (!OperatingSystem.IsWindows())
{
Assert.Equal(0, Console.CursorLeft);
Assert.Equal(0, Console.CursorTop);
Assert.Equal((0, 0), Console.GetCursorPosition());
}
}
[Fact]
[SkipOnPlatform(TestPlatforms.Browser | TestPlatforms.iOS | TestPlatforms.MacCatalyst | TestPlatforms.tvOS, "Not supported on Browser, iOS, MacCatalyst, or tvOS.")]
public void CursorLeft_Set_GetReturnsExpected()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
int origLeft = Console.CursorLeft;
Console.CursorLeft = 10;
Assert.Equal(10, Console.CursorLeft);
Console.CursorLeft = origLeft;
Assert.Equal(origLeft, Console.CursorLeft);
}
else if (!OperatingSystem.IsWindows())
{
Assert.Equal(0, Console.CursorLeft);
}
}
[Theory]
[InlineData(-1)]
[InlineData(short.MaxValue + 1)]
[SkipOnPlatform(TestPlatforms.Browser | TestPlatforms.iOS | TestPlatforms.MacCatalyst | TestPlatforms.tvOS, "Not supported on Browser, iOS, MacCatalyst, or tvOS.")]
public void CursorLeft_SetInvalid_ThrowsArgumentOutOfRangeException(int value)
{
if (PlatformDetection.IsWindows && Console.IsOutputRedirected)
{
Assert.Throws<IOException>(() => Console.CursorLeft = value);
}
else
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("left", () => Console.CursorLeft = value);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Browser)]
public void CursorLeft_Setter_Throws_PlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.CursorLeft = 0);
}
[Fact]
[SkipOnPlatform(TestPlatforms.Browser | TestPlatforms.iOS | TestPlatforms.MacCatalyst | TestPlatforms.tvOS, "Not supported on Browser, iOS, MacCatalyst, or tvOS.")]
public void CursorTop_Set_GetReturnsExpected()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
int origTop = Console.CursorTop;
Console.CursorTop = 10;
Assert.Equal(10, Console.CursorTop);
Console.CursorTop = origTop;
Assert.Equal(origTop, Console.CursorTop);
}
else if (!OperatingSystem.IsWindows())
{
Assert.Equal(0, Console.CursorTop);
}
}
[Theory]
[InlineData(-1)]
[InlineData(short.MaxValue + 1)]
[SkipOnPlatform(TestPlatforms.Browser | TestPlatforms.iOS | TestPlatforms.MacCatalyst | TestPlatforms.tvOS, "Not supported on Browser, iOS, MacCatalyst, or tvOS.")]
public void CursorTop_SetInvalid_ThrowsArgumentOutOfRangeException(int value)
{
if (PlatformDetection.IsWindows & Console.IsOutputRedirected)
{
Assert.Throws<IOException>(() => Console.CursorTop = value);
}
else
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("top", () => Console.CursorTop = value);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Browser)]
public void CursorTop_Setter_Throws_PlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.CursorTop = 0 );
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void CursorSize_Set_GetReturnsExpected()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
int orig = Console.CursorSize;
try
{
Console.CursorSize = 50;
Assert.Equal(50, Console.CursorSize);
}
finally
{
Console.CursorSize = orig;
}
}
}
[Theory]
[InlineData(0)]
[InlineData(101)]
[PlatformSpecific(TestPlatforms.Windows)]
public void CursorSize_SetInvalidValue_ThrowsArgumentOutOfRangeException(int value)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => Console.CursorSize = value);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser & ~TestPlatforms.iOS & ~TestPlatforms.MacCatalyst & ~TestPlatforms.tvOS)]
public void CursorSize_GetUnix_ReturnsExpected()
{
Assert.Equal(100, Console.CursorSize);
}
[Fact]
[PlatformSpecific(TestPlatforms.Browser)]
public void CursorSize_Getter_Throws_PlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.CursorSize);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void CursorSize_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.CursorSize = 1);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void SetWindowPosition_GetWindowPosition_ReturnsExpected()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("left", () => Console.SetWindowPosition(-1, Console.WindowTop));
AssertExtensions.Throws<ArgumentOutOfRangeException>("top", () => Console.SetWindowPosition(Console.WindowLeft, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("left", () => Console.SetWindowPosition(Console.BufferWidth - Console.WindowWidth + 2, Console.WindowTop));
AssertExtensions.Throws<ArgumentOutOfRangeException>("left", () => Console.SetWindowPosition(Console.WindowHeight, Console.BufferHeight - Console.WindowHeight + 2));
int origTop = Console.WindowTop;
int origLeft = Console.WindowLeft;
try
{
Console.SetWindowPosition(0, 0);
Assert.Equal(0, Console.WindowTop);
Assert.Equal(0, Console.WindowLeft);
}
finally
{
Console.WindowTop = origTop;
Console.WindowLeft = origLeft;
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void SetWindowPosition_Unix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.SetWindowPosition(50, 50));
}
[PlatformSpecific(TestPlatforms.Windows)]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))]
public void SetWindowSize_GetWindowSize_ReturnsExpected()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("width", () => Console.SetWindowSize(-1, Console.WindowHeight));
AssertExtensions.Throws<ArgumentOutOfRangeException>("height", () => Console.SetWindowSize(Console.WindowHeight, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("width", () => Console.SetWindowSize(short.MaxValue - Console.WindowLeft, Console.WindowHeight));
AssertExtensions.Throws<ArgumentOutOfRangeException>("height", () => Console.SetWindowSize(Console.WindowWidth, short.MaxValue - Console.WindowTop));
int origWidth = Console.WindowWidth;
int origHeight = Console.WindowHeight;
try
{
Console.SetWindowSize(10, 10);
Assert.Equal(10, Console.WindowWidth);
Assert.Equal(10, Console.WindowHeight);
}
finally
{
Console.WindowWidth = origWidth;
Console.WindowHeight = origHeight;
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void SetWindowSize_Unix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.SetWindowSize(50, 50));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void MoveBufferArea_DefaultChar()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceLeft", () => Console.MoveBufferArea(-1, 0, 0, 0, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceTop", () => Console.MoveBufferArea(0, -1, 0, 0, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceWidth", () => Console.MoveBufferArea(0, 0, -1, 0, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceHeight", () => Console.MoveBufferArea(0, 0, 0, -1, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("targetLeft", () => Console.MoveBufferArea(0, 0, 0, 0, -1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("targetTop", () => Console.MoveBufferArea(0, 0, 0, 0, 0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceLeft", () => Console.MoveBufferArea(Console.BufferWidth + 1, 0, 0, 0, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("targetLeft", () => Console.MoveBufferArea(0, 0, 0, 0, Console.BufferWidth + 1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceTop", () => Console.MoveBufferArea(0, Console.BufferHeight + 1, 0, 0, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("targetTop", () => Console.MoveBufferArea(0, 0, 0, 0, 0, Console.BufferHeight + 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceHeight", () => Console.MoveBufferArea(0, 1, 0, Console.BufferHeight, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceWidth", () => Console.MoveBufferArea(1, 0, Console.BufferWidth, 0, 0, 0));
// Nothing to verify; just run the code.
Console.MoveBufferArea(0, 0, 1, 1, 2, 2);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void MoveBufferArea()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(-1, 0, 0, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, -1, 0, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, -1, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, -1, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, 0, -1, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, 0, 0, -1, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(Console.BufferWidth + 1, 0, 0, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, 0, Console.BufferWidth + 1, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, Console.BufferHeight + 1, 0, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, 0, 0, Console.BufferHeight + 1, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 1, 0, Console.BufferHeight, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(1, 0, Console.BufferWidth, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
// Nothing to verify; just run the code.
Console.MoveBufferArea(0, 0, 1, 1, 2, 2, 'a', ConsoleColor.Black, ConsoleColor.White);
}
}
[Theory]
[InlineData(ConsoleColor.Black - 1)]
[InlineData(ConsoleColor.White + 1)]
[PlatformSpecific(TestPlatforms.Windows)]
public void MoveBufferArea_InvalidColor_ThrowsException(ConsoleColor color)
{
AssertExtensions.Throws<ArgumentException>("sourceForeColor", () => Console.MoveBufferArea(0, 0, 0, 0, 0, 0, 'a', color, ConsoleColor.Black));
AssertExtensions.Throws<ArgumentException>("sourceBackColor", () => Console.MoveBufferArea(0, 0, 0, 0, 0, 0, 'a', ConsoleColor.Black, color));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void MoveBufferArea_Unix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.MoveBufferArea(0, 0, 0, 0, 0, 0));
Assert.Throws<PlatformNotSupportedException>(() => Console.MoveBufferArea(0, 0, 0, 0, 0, 0, 'c', ConsoleColor.White, ConsoleColor.Black));
}
}
|
// 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.IO;
using Microsoft.DotNet.RemoteExecutor;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;
public class WindowAndCursorProps
{
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser & ~TestPlatforms.iOS & ~TestPlatforms.MacCatalyst & ~TestPlatforms.tvOS)] // Expected behavior specific to Unix
public static void BufferWidth_GetUnix_ReturnsWindowWidth()
{
Assert.Equal(Console.WindowWidth, Console.BufferWidth);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void BufferWidth_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.BufferWidth = 1);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser & ~TestPlatforms.iOS & ~TestPlatforms.MacCatalyst & ~TestPlatforms.tvOS)] // Expected behavior specific to Unix
public static void BufferHeight_GetUnix_ReturnsWindowHeight()
{
Assert.Equal(Console.WindowHeight, Console.BufferHeight);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void BufferHeight_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.BufferHeight = 1);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void SetBufferSize_Unix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.SetBufferSize(0, 0));
}
[Theory]
[PlatformSpecific(TestPlatforms.Windows)]
[InlineData(0)]
[InlineData(-1)]
public static void WindowWidth_SetInvalid_ThrowsArgumentOutOfRangeException(int value)
{
if (Console.IsOutputRedirected)
{
Assert.Throws<IOException>(() => Console.WindowWidth = value);
}
else
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("width", () => Console.WindowWidth = value);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser & ~TestPlatforms.iOS & ~TestPlatforms.MacCatalyst & ~TestPlatforms.tvOS)] // Expected behavior specific to Unix
public static void WindowWidth_GetUnix_Success()
{
// Validate that Console.WindowWidth returns some value in a non-redirected o/p.
Helpers.RunInNonRedirectedOutput((data) => Console.WriteLine(Console.WindowWidth));
Helpers.RunInRedirectedOutput((data) => Console.WriteLine(Console.WindowWidth));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser)] // Expected behavior specific to Unix
public static void WindowWidth_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.WindowWidth = 100);
}
[Theory]
[PlatformSpecific(TestPlatforms.Windows)] // Expected behavior specific to Windows
[InlineData(0)]
[InlineData(-1)]
public static void WindowHeight_SetInvalid_ThrowsArgumentOutOfRangeException(int value)
{
if (Console.IsOutputRedirected)
{
Assert.Throws<IOException>(() => Console.WindowHeight = value);
}
else
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("height", () => Console.WindowHeight = value);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser & ~TestPlatforms.iOS & ~TestPlatforms.MacCatalyst & ~TestPlatforms.tvOS)] // Expected behavior specific to Unix
public static void WindowHeight_GetUnix_Success()
{
// Validate that Console.WindowHeight returns some value in a non-redirected o/p.
Helpers.RunInNonRedirectedOutput((data) => Console.WriteLine(Console.WindowHeight));
Helpers.RunInRedirectedOutput((data) => Console.WriteLine(Console.WindowHeight));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void WindowHeight_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.WindowHeight = 100);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser & ~TestPlatforms.iOS & ~TestPlatforms.MacCatalyst & ~TestPlatforms.tvOS)] // Expected behavior specific to Unix
public static void LargestWindowWidth_UnixGet_ReturnsExpected()
{
Helpers.RunInNonRedirectedOutput((data) => Assert.Equal(Console.WindowWidth, Console.LargestWindowWidth));
Helpers.RunInRedirectedOutput((data) => Assert.Equal(Console.WindowWidth, Console.LargestWindowWidth));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser & ~TestPlatforms.iOS & ~TestPlatforms.MacCatalyst & ~TestPlatforms.tvOS)] // Expected behavior specific to Unix
public static void LargestWindowHeight_UnixGet_ReturnsExpected()
{
Helpers.RunInNonRedirectedOutput((data) => Assert.Equal(Console.WindowHeight, Console.LargestWindowHeight));
Helpers.RunInRedirectedOutput((data) => Assert.Equal(Console.WindowHeight, Console.LargestWindowHeight));
}
[Fact]
[PlatformSpecific(TestPlatforms.Browser)]
public static void WindowHeight_Getter_Throws_PlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.WindowHeight);
}
[Fact]
[PlatformSpecific(TestPlatforms.Browser)]
public static void WindowWidth_Getter_Throws_PlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.WindowWidth);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void WindowLeft_GetUnix_ReturnsZero()
{
Assert.Equal(0, Console.WindowLeft);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void WindowLeft_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.WindowLeft = 0);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void WindowTop_GetUnix_ReturnsZero()
{
Assert.Equal(0, Console.WindowTop);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void WindowTop_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.WindowTop = 0);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Expected behavior specific to Windows
public static void WindowLeftTop_Windows()
{
if (Console.IsOutputRedirected)
{
Assert.Throws<IOException>(() => Console.WindowLeft);
Assert.Throws<IOException>(() => Console.WindowTop);
}
else
{
Console.WriteLine(Console.WindowLeft);
Console.WriteLine(Console.WindowTop);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void CursorVisible_GetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.CursorVisible);
}
[Theory]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser & ~TestPlatforms.iOS & ~TestPlatforms.MacCatalyst & ~TestPlatforms.tvOS )] // Expected behavior specific to Unix
[InlineData(true)]
[InlineData(false)]
public static void CursorVisible_SetUnixRedirected_Nop(bool value)
{
Helpers.RunInRedirectedOutput((data) => {
Console.CursorVisible = value;
Assert.Equal(0, data.ToArray().Length);
});
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void Title_GetUnix_ThrowPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.Title);
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void Title_SetUnix_Success()
{
RemoteExecutor.Invoke(() =>
{
Console.Title = "Title set by unit test";
}).Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public static void Title_GetWindows_ReturnsNonNull()
{
Assert.NotNull(Console.Title);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))]
[PlatformSpecific(TestPlatforms.Windows)]
public static void Title_Get_Windows_NoNulls()
{
string title = Console.Title;
string trimmedTitle = title.TrimEnd('\0');
Assert.Equal(trimmedTitle, title);
}
private static bool IsNotWindowsNanoServerAndNotServerCoreAndRemoteExecutorSupported => PlatformDetection.IsNotWindowsNanoNorServerCore && RemoteExecutor.IsSupported;
[ConditionalTheory(nameof(IsNotWindowsNanoServerAndNotServerCoreAndRemoteExecutorSupported))] // Nano and Server Core currently ignore set title
[ActiveIssue("https://github.com/dotnet/runtime/issues/34454", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[InlineData(0)]
[InlineData(1)]
[InlineData(254)]
[InlineData(255)]
[InlineData(256)]
[InlineData(257)]
[InlineData(511)]
[InlineData(512)]
[InlineData(513)]
[InlineData(1024)]
[PlatformSpecific(TestPlatforms.Windows)]
public static void Title_Set_Windows(int lengthOfTitle)
{
// Try to set the title to some other value.
RemoteExecutor.Invoke(lengthOfTitleString =>
{
string newTitle = new string('a', int.Parse(lengthOfTitleString));
Console.Title = newTitle;
if (newTitle.Length >= 511 && !PlatformDetection.IsNetCore && PlatformDetection.IsWindows10Version1703OrGreater && !PlatformDetection.IsWindows10Version1709OrGreater)
{
// RS2 has a bug when getting the window title when the title length is longer than 513 character
Assert.Throws<IOException>(() => Console.Title);
}
else
{
Assert.Equal(newTitle, Console.Title);
}
}, lengthOfTitle.ToString()).Dispose();
}
[Fact]
public static void Title_SetNull_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("value", () => Console.Title = null);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
[OuterLoop] // makes noise, not very inner-loop friendly
public static void Beep_Invoke_Success()
{
// Nothing to verify; just run the code.
Console.Beep();
}
[Fact]
[OuterLoop] // makes noise, not very inner-loop friendly
[PlatformSpecific(TestPlatforms.Windows)]
public static void BeepWithFrequency_Invoke_Success()
{
// Nothing to verify; just run the code.
Console.Beep(800, 200);
}
[Theory]
[PlatformSpecific(TestPlatforms.Windows)]
[InlineData(36)]
[InlineData(32768)]
public void BeepWithFrequency_InvalidFrequency_ThrowsArgumentOutOfRangeException(int frequency)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("frequency", () => Console.Beep(frequency, 200));
}
[Theory]
[PlatformSpecific(TestPlatforms.Windows)]
[InlineData(0)]
[InlineData(-1)]
public void BeepWithFrequency_InvalidDuration_ThrowsArgumentOutOfRangeException(int duration)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("duration", () => Console.Beep(800, duration));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void BeepWithFrequency_Unix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.Beep(800, 200));
}
[Fact]
[OuterLoop] // clears the screen, not very inner-loop friendly
public static void Clear_Invoke_Success()
{
if (!OperatingSystem.IsWindows() || (!Console.IsInputRedirected && !Console.IsOutputRedirected))
{
// Nothing to verify; just run the code.
Console.Clear();
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Browser)]
public static void SetCursorPosition_Throws_PlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.SetCursorPosition(0, 0));
}
[Fact]
[SkipOnPlatform(TestPlatforms.Browser | TestPlatforms.iOS | TestPlatforms.MacCatalyst | TestPlatforms.tvOS, "Not supported on Browser, iOS, MacCatalyst, or tvOS.")]
public static void SetCursorPosition_Invoke_Success()
{
if (!OperatingSystem.IsWindows() || (!Console.IsInputRedirected && !Console.IsOutputRedirected))
{
int origLeft = Console.CursorLeft;
int origTop = Console.CursorTop;
// Nothing to verify; just run the code.
// On windows, we might end of throwing IOException, since the handles are redirected.
Console.SetCursorPosition(0, 0);
Console.SetCursorPosition(1, 2);
Console.SetCursorPosition(origLeft, origTop);
}
}
[Theory]
[InlineData(-1)]
[InlineData(short.MaxValue + 1)]
public void SetCursorPosition_InvalidPosition_ThrowsArgumentOutOfRangeException(int value)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("left", () => Console.SetCursorPosition(value, 100));
AssertExtensions.Throws<ArgumentOutOfRangeException>("top", () => Console.SetCursorPosition(100, value));
}
[Fact]
[SkipOnPlatform(TestPlatforms.Browser | TestPlatforms.iOS | TestPlatforms.MacCatalyst | TestPlatforms.tvOS, "Not supported on Browser, iOS, MacCatalyst, or tvOS.")]
public static void GetCursorPosition_Invoke_ReturnsExpected()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
int origLeft = Console.CursorLeft, origTop = Console.CursorTop;
(int, int) origTuple = Console.GetCursorPosition();
Console.SetCursorPosition(10, 12);
Assert.Equal(10, Console.CursorLeft);
Assert.Equal(12, Console.CursorTop);
Assert.Equal((10, 12), Console.GetCursorPosition());
Console.SetCursorPosition(origLeft, origTop);
Assert.Equal(origLeft, Console.CursorLeft);
Assert.Equal(origTop, Console.CursorTop);
Assert.Equal(origTuple, Console.GetCursorPosition());
}
else if (!OperatingSystem.IsWindows())
{
Assert.Equal(0, Console.CursorLeft);
Assert.Equal(0, Console.CursorTop);
Assert.Equal((0, 0), Console.GetCursorPosition());
}
}
[Fact]
[SkipOnPlatform(TestPlatforms.Browser | TestPlatforms.iOS | TestPlatforms.MacCatalyst | TestPlatforms.tvOS, "Not supported on Browser, iOS, MacCatalyst, or tvOS.")]
public void CursorLeft_Set_GetReturnsExpected()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
int origLeft = Console.CursorLeft;
Console.CursorLeft = 10;
Assert.Equal(10, Console.CursorLeft);
Console.CursorLeft = origLeft;
Assert.Equal(origLeft, Console.CursorLeft);
}
else if (!OperatingSystem.IsWindows())
{
Assert.Equal(0, Console.CursorLeft);
}
}
[Theory]
[InlineData(-1)]
[InlineData(short.MaxValue + 1)]
[SkipOnPlatform(TestPlatforms.Browser | TestPlatforms.iOS | TestPlatforms.MacCatalyst | TestPlatforms.tvOS, "Not supported on Browser, iOS, MacCatalyst, or tvOS.")]
public void CursorLeft_SetInvalid_ThrowsArgumentOutOfRangeException(int value)
{
if (PlatformDetection.IsWindows && Console.IsOutputRedirected)
{
Assert.Throws<IOException>(() => Console.CursorLeft = value);
}
else
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("left", () => Console.CursorLeft = value);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Browser)]
public void CursorLeft_Setter_Throws_PlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.CursorLeft = 0);
}
[Fact]
[SkipOnPlatform(TestPlatforms.Browser | TestPlatforms.iOS | TestPlatforms.MacCatalyst | TestPlatforms.tvOS, "Not supported on Browser, iOS, MacCatalyst, or tvOS.")]
public void CursorTop_Set_GetReturnsExpected()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
int origTop = Console.CursorTop;
Console.CursorTop = 10;
Assert.Equal(10, Console.CursorTop);
Console.CursorTop = origTop;
Assert.Equal(origTop, Console.CursorTop);
}
else if (!OperatingSystem.IsWindows())
{
Assert.Equal(0, Console.CursorTop);
}
}
[Theory]
[InlineData(-1)]
[InlineData(short.MaxValue + 1)]
[SkipOnPlatform(TestPlatforms.Browser | TestPlatforms.iOS | TestPlatforms.MacCatalyst | TestPlatforms.tvOS, "Not supported on Browser, iOS, MacCatalyst, or tvOS.")]
public void CursorTop_SetInvalid_ThrowsArgumentOutOfRangeException(int value)
{
if (PlatformDetection.IsWindows & Console.IsOutputRedirected)
{
Assert.Throws<IOException>(() => Console.CursorTop = value);
}
else
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("top", () => Console.CursorTop = value);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Browser)]
public void CursorTop_Setter_Throws_PlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.CursorTop = 0 );
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void CursorSize_Set_GetReturnsExpected()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
int orig = Console.CursorSize;
try
{
Console.CursorSize = 50;
Assert.Equal(50, Console.CursorSize);
}
finally
{
Console.CursorSize = orig;
}
}
}
[Theory]
[InlineData(0)]
[InlineData(101)]
[PlatformSpecific(TestPlatforms.Windows)]
public void CursorSize_SetInvalidValue_ThrowsArgumentOutOfRangeException(int value)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => Console.CursorSize = value);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser & ~TestPlatforms.iOS & ~TestPlatforms.MacCatalyst & ~TestPlatforms.tvOS)]
public void CursorSize_GetUnix_ReturnsExpected()
{
Assert.Equal(100, Console.CursorSize);
}
[Fact]
[PlatformSpecific(TestPlatforms.Browser)]
public void CursorSize_Getter_Throws_PlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.CursorSize);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void CursorSize_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.CursorSize = 1);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void SetWindowPosition_GetWindowPosition_ReturnsExpected()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("left", () => Console.SetWindowPosition(-1, Console.WindowTop));
AssertExtensions.Throws<ArgumentOutOfRangeException>("top", () => Console.SetWindowPosition(Console.WindowLeft, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("left", () => Console.SetWindowPosition(Console.BufferWidth - Console.WindowWidth + 2, Console.WindowTop));
AssertExtensions.Throws<ArgumentOutOfRangeException>("left", () => Console.SetWindowPosition(Console.WindowHeight, Console.BufferHeight - Console.WindowHeight + 2));
int origTop = Console.WindowTop;
int origLeft = Console.WindowLeft;
try
{
Console.SetWindowPosition(0, 0);
Assert.Equal(0, Console.WindowTop);
Assert.Equal(0, Console.WindowLeft);
}
finally
{
Console.WindowTop = origTop;
Console.WindowLeft = origLeft;
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void SetWindowPosition_Unix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.SetWindowPosition(50, 50));
}
[PlatformSpecific(TestPlatforms.Windows)]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))]
public void SetWindowSize_GetWindowSize_ReturnsExpected()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("width", () => Console.SetWindowSize(-1, Console.WindowHeight));
AssertExtensions.Throws<ArgumentOutOfRangeException>("height", () => Console.SetWindowSize(Console.WindowHeight, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("width", () => Console.SetWindowSize(short.MaxValue - Console.WindowLeft, Console.WindowHeight));
AssertExtensions.Throws<ArgumentOutOfRangeException>("height", () => Console.SetWindowSize(Console.WindowWidth, short.MaxValue - Console.WindowTop));
int origWidth = Console.WindowWidth;
int origHeight = Console.WindowHeight;
try
{
Console.SetWindowSize(10, 10);
Assert.Equal(10, Console.WindowWidth);
Assert.Equal(10, Console.WindowHeight);
}
finally
{
Console.WindowWidth = origWidth;
Console.WindowHeight = origHeight;
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void SetWindowSize_Unix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.SetWindowSize(50, 50));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void MoveBufferArea_DefaultChar()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceLeft", () => Console.MoveBufferArea(-1, 0, 0, 0, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceTop", () => Console.MoveBufferArea(0, -1, 0, 0, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceWidth", () => Console.MoveBufferArea(0, 0, -1, 0, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceHeight", () => Console.MoveBufferArea(0, 0, 0, -1, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("targetLeft", () => Console.MoveBufferArea(0, 0, 0, 0, -1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("targetTop", () => Console.MoveBufferArea(0, 0, 0, 0, 0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceLeft", () => Console.MoveBufferArea(Console.BufferWidth + 1, 0, 0, 0, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("targetLeft", () => Console.MoveBufferArea(0, 0, 0, 0, Console.BufferWidth + 1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceTop", () => Console.MoveBufferArea(0, Console.BufferHeight + 1, 0, 0, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("targetTop", () => Console.MoveBufferArea(0, 0, 0, 0, 0, Console.BufferHeight + 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceHeight", () => Console.MoveBufferArea(0, 1, 0, Console.BufferHeight, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceWidth", () => Console.MoveBufferArea(1, 0, Console.BufferWidth, 0, 0, 0));
// Nothing to verify; just run the code.
Console.MoveBufferArea(0, 0, 1, 1, 2, 2);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void MoveBufferArea()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(-1, 0, 0, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, -1, 0, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, -1, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, -1, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, 0, -1, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, 0, 0, -1, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(Console.BufferWidth + 1, 0, 0, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, 0, Console.BufferWidth + 1, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, Console.BufferHeight + 1, 0, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, 0, 0, Console.BufferHeight + 1, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 1, 0, Console.BufferHeight, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(1, 0, Console.BufferWidth, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
// Nothing to verify; just run the code.
Console.MoveBufferArea(0, 0, 1, 1, 2, 2, 'a', ConsoleColor.Black, ConsoleColor.White);
}
}
[Theory]
[InlineData(ConsoleColor.Black - 1)]
[InlineData(ConsoleColor.White + 1)]
[PlatformSpecific(TestPlatforms.Windows)]
public void MoveBufferArea_InvalidColor_ThrowsException(ConsoleColor color)
{
AssertExtensions.Throws<ArgumentException>("sourceForeColor", () => Console.MoveBufferArea(0, 0, 0, 0, 0, 0, 'a', color, ConsoleColor.Black));
AssertExtensions.Throws<ArgumentException>("sourceBackColor", () => Console.MoveBufferArea(0, 0, 0, 0, 0, 0, 'a', ConsoleColor.Black, color));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void MoveBufferArea_Unix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.MoveBufferArea(0, 0, 0, 0, 0, 0));
Assert.Throws<PlatformNotSupportedException>(() => Console.MoveBufferArea(0, 0, 0, 0, 0, 0, 'c', ConsoleColor.White, ConsoleColor.Black));
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate.Vector128.Int32.Vector128.Int32.3.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate_Vector128_Int32_Vector128_Int32_3()
{
var test = new SimpleTernaryOpTest__MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate_Vector128_Int32_Vector128_Int32_3();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate_Vector128_Int32_Vector128_Int32_3
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int64[] inArray1, Int32[] inArray2, Int32[] inArray3, Int64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>();
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<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int32, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int64> _fld1;
public Vector128<Int32> _fld2;
public Vector128<Int32> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate_Vector128_Int32_Vector128_Int32_3 testClass)
{
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(_fld1, _fld2, _fld3, 3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate_Vector128_Int32_Vector128_Int32_3 testClass)
{
fixed (Vector128<Int64>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
fixed (Vector128<Int32>* pFld3 = &_fld3)
{
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(
AdvSimd.LoadVector128((Int64*)(pFld1)),
AdvSimd.LoadVector128((Int32*)(pFld2)),
AdvSimd.LoadVector128((Int32*)(pFld3)),
3
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static readonly byte Imm = 3;
private static Int64[] _data1 = new Int64[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Int32[] _data3 = new Int32[Op3ElementCount];
private static Vector128<Int64> _clsVar1;
private static Vector128<Int32> _clsVar2;
private static Vector128<Int32> _clsVar3;
private Vector128<Int64> _fld1;
private Vector128<Int32> _fld2;
private Vector128<Int32> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate_Vector128_Int32_Vector128_Int32_3()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public SimpleTernaryOpTest__MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate_Vector128_Int32_Vector128_Int32_3()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Int64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(
AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr),
(byte)3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(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.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)),
(byte)3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(
_clsVar1,
_clsVar2,
_clsVar3,
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int64>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int32>* pClsVar2 = &_clsVar2)
fixed (Vector128<Int32>* pClsVar3 = &_clsVar3)
{
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(
AdvSimd.LoadVector128((Int64*)(pClsVar1)),
AdvSimd.LoadVector128((Int32*)(pClsVar2)),
AdvSimd.LoadVector128((Int32*)(pClsVar3)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr);
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(op1, op2, op3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var op3 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr));
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(op1, op2, op3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate_Vector128_Int32_Vector128_Int32_3();
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(test._fld1, test._fld2, test._fld3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate_Vector128_Int32_Vector128_Int32_3();
fixed (Vector128<Int64>* pFld1 = &test._fld1)
fixed (Vector128<Int32>* pFld2 = &test._fld2)
fixed (Vector128<Int32>* pFld3 = &test._fld3)
{
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(
AdvSimd.LoadVector128((Int64*)(pFld1)),
AdvSimd.LoadVector128((Int32*)(pFld2)),
AdvSimd.LoadVector128((Int32*)(pFld3)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(_fld1, _fld2, _fld3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int64>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
fixed (Vector128<Int32>* pFld3 = &_fld3)
{
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(
AdvSimd.LoadVector128((Int64*)(pFld1)),
AdvSimd.LoadVector128((Int32*)(pFld2)),
AdvSimd.LoadVector128((Int32*)(pFld3)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(test._fld1, test._fld2, test._fld3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(
AdvSimd.LoadVector128((Int64*)(&test._fld1)),
AdvSimd.LoadVector128((Int32*)(&test._fld2)),
AdvSimd.LoadVector128((Int32*)(&test._fld3)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int64> op1, Vector128<Int32> op2, Vector128<Int32> op3, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] inArray3 = new Int32[Op3ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] inArray3 = new Int32[Op3ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Int64[] firstOp, Int32[] secondOp, Int32[] thirdOp, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.MultiplyDoublingWideningUpperByScalarAndSubtractSaturate(firstOp, secondOp, thirdOp[Imm], i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate)}<Int64>(Vector128<Int64>, Vector128<Int32>, Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate_Vector128_Int32_Vector128_Int32_3()
{
var test = new SimpleTernaryOpTest__MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate_Vector128_Int32_Vector128_Int32_3();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate_Vector128_Int32_Vector128_Int32_3
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int64[] inArray1, Int32[] inArray2, Int32[] inArray3, Int64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>();
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<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int32, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int64> _fld1;
public Vector128<Int32> _fld2;
public Vector128<Int32> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate_Vector128_Int32_Vector128_Int32_3 testClass)
{
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(_fld1, _fld2, _fld3, 3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate_Vector128_Int32_Vector128_Int32_3 testClass)
{
fixed (Vector128<Int64>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
fixed (Vector128<Int32>* pFld3 = &_fld3)
{
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(
AdvSimd.LoadVector128((Int64*)(pFld1)),
AdvSimd.LoadVector128((Int32*)(pFld2)),
AdvSimd.LoadVector128((Int32*)(pFld3)),
3
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static readonly byte Imm = 3;
private static Int64[] _data1 = new Int64[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Int32[] _data3 = new Int32[Op3ElementCount];
private static Vector128<Int64> _clsVar1;
private static Vector128<Int32> _clsVar2;
private static Vector128<Int32> _clsVar3;
private Vector128<Int64> _fld1;
private Vector128<Int32> _fld2;
private Vector128<Int32> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate_Vector128_Int32_Vector128_Int32_3()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public SimpleTernaryOpTest__MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate_Vector128_Int32_Vector128_Int32_3()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Int64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(
AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr),
(byte)3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(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.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)),
(byte)3
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(
_clsVar1,
_clsVar2,
_clsVar3,
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int64>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int32>* pClsVar2 = &_clsVar2)
fixed (Vector128<Int32>* pClsVar3 = &_clsVar3)
{
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(
AdvSimd.LoadVector128((Int64*)(pClsVar1)),
AdvSimd.LoadVector128((Int32*)(pClsVar2)),
AdvSimd.LoadVector128((Int32*)(pClsVar3)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr);
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(op1, op2, op3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var op3 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr));
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(op1, op2, op3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate_Vector128_Int32_Vector128_Int32_3();
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(test._fld1, test._fld2, test._fld3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate_Vector128_Int32_Vector128_Int32_3();
fixed (Vector128<Int64>* pFld1 = &test._fld1)
fixed (Vector128<Int32>* pFld2 = &test._fld2)
fixed (Vector128<Int32>* pFld3 = &test._fld3)
{
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(
AdvSimd.LoadVector128((Int64*)(pFld1)),
AdvSimd.LoadVector128((Int32*)(pFld2)),
AdvSimd.LoadVector128((Int32*)(pFld3)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(_fld1, _fld2, _fld3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int64>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
fixed (Vector128<Int32>* pFld3 = &_fld3)
{
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(
AdvSimd.LoadVector128((Int64*)(pFld1)),
AdvSimd.LoadVector128((Int32*)(pFld2)),
AdvSimd.LoadVector128((Int32*)(pFld3)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(test._fld1, test._fld2, test._fld3, 3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(
AdvSimd.LoadVector128((Int64*)(&test._fld1)),
AdvSimd.LoadVector128((Int32*)(&test._fld2)),
AdvSimd.LoadVector128((Int32*)(&test._fld3)),
3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int64> op1, Vector128<Int32> op2, Vector128<Int32> op3, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] inArray3 = new Int32[Op3ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] inArray3 = new Int32[Op3ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Int64[] firstOp, Int32[] secondOp, Int32[] thirdOp, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.MultiplyDoublingWideningUpperByScalarAndSubtractSaturate(firstOp, secondOp, thirdOp[Imm], i) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate)}<Int64>(Vector128<Int64>, Vector128<Int32>, Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/coreclr/pal/src/libunwind/src/x86/Lstep.c
|
#define UNW_LOCAL_ONLY
#include <libunwind.h>
#if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY)
#include "Gstep.c"
#endif
|
#define UNW_LOCAL_ONLY
#include <libunwind.h>
#if defined(UNW_LOCAL_ONLY) && !defined(UNW_REMOTE_ONLY)
#include "Gstep.c"
#endif
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/HardwareIntrinsics/General/Vector128/ConditionalSelect.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 ConditionalSelectSingle()
{
var test = new VectorTernaryOpTest__ConditionalSelectSingle();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorTernaryOpTest__ConditionalSelectSingle
{
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(Single[] inArray1, Single[] inArray2, Single[] inArray3, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray3 = inArray3.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) < 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<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Single, 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<Single> _fld1;
public Vector128<Single> _fld2;
public Vector128<Single> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(VectorTernaryOpTest__ConditionalSelectSingle testClass)
{
var result = Vector128.ConditionalSelect(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Single[] _data3 = new Single[Op3ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private static Vector128<Single> _clsVar3;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private Vector128<Single> _fld3;
private DataTable _dataTable;
static VectorTernaryOpTest__ConditionalSelectSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public VectorTernaryOpTest__ConditionalSelectSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Single[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector128.ConditionalSelect(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector128).GetMethod(nameof(Vector128.ConditionalSelect), new Type[] {
typeof(Vector128<Single>),
typeof(Vector128<Single>),
typeof(Vector128<Single>)
});
if (method is null)
{
method = typeof(Vector128).GetMethod(nameof(Vector128.ConditionalSelect), 1, new Type[] {
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Single));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector128.ConditionalSelect(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray3Ptr);
var result = Vector128.ConditionalSelect(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorTernaryOpTest__ConditionalSelectSingle();
var result = Vector128.ConditionalSelect(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector128.ConditionalSelect(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector128.ConditionalSelect(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, Vector128<Single> op3, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] inArray3 = new Single[Op3ElementCount];
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.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] inArray3 = new Single[Op3ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] secondOp, Single[] thirdOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != ((BitConverter.SingleToInt32Bits(secondOp[0]) & BitConverter.SingleToInt32Bits(firstOp[0])) | (BitConverter.SingleToInt32Bits(thirdOp[0]) & ~BitConverter.SingleToInt32Bits(firstOp[0]))))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != ((BitConverter.SingleToInt32Bits(secondOp[i]) & BitConverter.SingleToInt32Bits(firstOp[i])) | (BitConverter.SingleToInt32Bits(thirdOp[i]) & ~BitConverter.SingleToInt32Bits(firstOp[i]))))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.ConditionalSelect)}<Single>(Vector128<Single>, Vector128<Single>, Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void ConditionalSelectSingle()
{
var test = new VectorTernaryOpTest__ConditionalSelectSingle();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorTernaryOpTest__ConditionalSelectSingle
{
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(Single[] inArray1, Single[] inArray2, Single[] inArray3, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray3 = inArray3.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) < 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<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Single, 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<Single> _fld1;
public Vector128<Single> _fld2;
public Vector128<Single> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(VectorTernaryOpTest__ConditionalSelectSingle testClass)
{
var result = Vector128.ConditionalSelect(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Single[] _data3 = new Single[Op3ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private static Vector128<Single> _clsVar3;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private Vector128<Single> _fld3;
private DataTable _dataTable;
static VectorTernaryOpTest__ConditionalSelectSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public VectorTernaryOpTest__ConditionalSelectSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Single[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector128.ConditionalSelect(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector128).GetMethod(nameof(Vector128.ConditionalSelect), new Type[] {
typeof(Vector128<Single>),
typeof(Vector128<Single>),
typeof(Vector128<Single>)
});
if (method is null)
{
method = typeof(Vector128).GetMethod(nameof(Vector128.ConditionalSelect), 1, new Type[] {
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Single));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector128.ConditionalSelect(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray3Ptr);
var result = Vector128.ConditionalSelect(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorTernaryOpTest__ConditionalSelectSingle();
var result = Vector128.ConditionalSelect(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector128.ConditionalSelect(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector128.ConditionalSelect(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, Vector128<Single> op3, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] inArray3 = new Single[Op3ElementCount];
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.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] inArray3 = new Single[Op3ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] secondOp, Single[] thirdOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != ((BitConverter.SingleToInt32Bits(secondOp[0]) & BitConverter.SingleToInt32Bits(firstOp[0])) | (BitConverter.SingleToInt32Bits(thirdOp[0]) & ~BitConverter.SingleToInt32Bits(firstOp[0]))))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != ((BitConverter.SingleToInt32Bits(secondOp[i]) & BitConverter.SingleToInt32Bits(firstOp[i])) | (BitConverter.SingleToInt32Bits(thirdOp[i]) & ~BitConverter.SingleToInt32Bits(firstOp[i]))))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.ConditionalSelect)}<Single>(Vector128<Single>, Vector128<Single>, Vector128<Single>): {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,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Runtime/tests/TrimmingTests/InterfacesOnArrays.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;
class Program
{
class Mine { }
static int Main()
{
Mine[] s = new Mine[1] { new Mine() };
Mine[] d = new Mine[1];
((ICollection<Mine>)s).CopyTo(d, 0);
return s[0] == d[0] ? 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.Collections.Generic;
class Program
{
class Mine { }
static int Main()
{
Mine[] s = new Mine[1] { new Mine() };
Mine[] d = new Mine[1];
((ICollection<Mine>)s).CopyTo(d, 0);
return s[0] == d[0] ? 100 : -1;
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/coreclr/nativeaot/Runtime.Base/src/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Runtime.CompilerServices
{
internal class UnsafeValueTypeAttribute : Attribute { }
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Runtime.CompilerServices
{
internal class UnsafeValueTypeAttribute : Attribute { }
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/jit64/localloc/unwind/unwind04_small.il
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// Unwind from fault block
.assembly extern System.Console
{
.publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A )
.ver 4:0:0:0
}
.assembly extern xunit.core {}
.assembly extern mscorlib{}
.assembly extern localloc_common{}
.assembly 'unwind04_small'{}
.class private auto ansi beforefieldinit LocallocTest
extends [mscorlib]System.Object
{
.field private static bool testFailed
.field private static int32 locallocSize
.method public hidebysig static int32 Main() cil managed
{
.custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = (
01 00 00 00
)
.entrypoint
.maxstack 4
.locals (unsigned int64 local1,
unsigned int64 local2,
int32* intArray1,
int32 retValue)
IL_0000: ldc.i8 0xfedcba9876543210
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: conv.i8
IL_000d: add
IL_000e: stloc.1
IL_000f: ldc.i4.4
IL_0016: localloc
IL_0018: stloc.2
IL_0019: ldc.i4.1
IL_001e: stsfld int32 LocallocTest::locallocSize
.try
{
IL_0023: ldloc.2
IL_0024: ldsfld int32 LocallocTest::locallocSize
IL_0029: ldc.i4 1000
IL_002e: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*,
int32,
int32)
IL_0033: call void LocallocTest::unwindTest1()
IL_0038: ldc.i4.1
IL_0039: stloc.3
IL_003a: leave.s IL_00a8
}
catch [mscorlib]System.Object
{
IL_003c: pop
IL_003d: leave.s IL_003f
}
IL_003f: ldsfld bool LocallocTest::testFailed
IL_0044: brfalse.s IL_004a
IL_0046: ldc.i4.1
IL_0047: stloc.3
IL_0048: br.s IL_00a8
IL_004a: ldstr "intArray1"
IL_004f: ldloc.2
IL_0050: ldsfld int32 LocallocTest::locallocSize
IL_0055: ldc.i4 1000
IL_005a: call bool [localloc_common]LocallocTesting.Global::verifyStack(string,
int32*,
int32,
int32)
IL_005f: brtrue.s IL_0065
IL_0061: ldc.i4.1
IL_0062: stloc.3
IL_0063: br.s IL_00a8
IL_0065: ldstr "local1"
IL_006a: ldloc.0
IL_006b: ldc.i8 0xfedcba9876543210
IL_0074: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string,
unsigned int64,
unsigned int64)
IL_0079: brtrue.s IL_007f
IL_007b: ldc.i4.1
IL_007c: stloc.3
IL_007d: br.s IL_00a8
IL_007f: ldstr "local2"
IL_0084: ldloc.1
IL_0085: ldc.i8 0xfedcba9876543211
IL_008e: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string,
unsigned int64,
unsigned int64)
IL_0093: brtrue.s IL_0099
IL_0095: ldc.i4.1
IL_0096: stloc.3
IL_0097: br.s IL_00a8
IL_0099: ldstr "Passed\n"
IL_009e: call void [System.Console]System.Console::WriteLine(string)
IL_00a3: ldc.i4.s 100
IL_00a5: stloc.3
IL_00a6: br.s IL_00a8
IL_00a8: ldloc.3
IL_00a9: ret
}
.method public hidebysig static void unwindTest1() cil managed
{
.maxstack 10
.locals (int32* intArray2,
class LocallocTest testObj)
IL_0000: ldc.i4.4
IL_0007: localloc
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: ldsfld int32 LocallocTest::locallocSize
IL_0010: ldc.i4 2000
IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*,
int32,
int32)
.try
{
IL_001a: newobj instance void LocallocTest::.ctor()
IL_001f: stloc.1
IL_0020: ldloc.1
IL_0021: ldc.i4.1
IL_0022: ldc.i4.2
IL_0023: ldc.i4.3
IL_0024: ldc.i4.4
IL_0025: ldc.i4.5
IL_0026: ldc.i4.6
IL_0027: ldc.i4.7
IL_0028: ldc.i4.8
IL_0029: ldc.i4.s 9
IL_002b: callvirt instance void LocallocTest::unwindTest2(int32,
int32,
int32,
int32,
int32,
int32,
int32,
int32,
int32)
IL_0030: leave.s IL_0061
}
fault
{
IL_0032: ldstr "fault block in unwindTest1.\n"
IL_0037: call void [System.Console]System.Console::WriteLine(string)
IL_003c: ldsfld bool LocallocTest::testFailed
IL_0041: brtrue.s IL_0060
IL_0043: ldstr "intArray2"
IL_0048: ldloc.0
IL_0049: ldsfld int32 LocallocTest::locallocSize
IL_004e: ldc.i4 2000
IL_0053: call bool [localloc_common]LocallocTesting.Global::verifyStack(string,
int32*,
int32,
int32)
IL_0058: ldc.i4.0
IL_0059: ceq
IL_005b: stsfld bool LocallocTest::testFailed
IL_0060: endfault
}
IL_0061: br.s IL_0063
IL_0063: ret
}
.method private hidebysig instance void
unwindTest2(int32 i1,
int32 i2,
int32 i3,
int32 i4,
int32 i5,
int32 i6,
int32 i7,
int32 i8,
int32 i9) cil managed
{
.maxstack 4
.locals (int32* intArray3)
IL_0000: ldc.i4.4
IL_0007: localloc
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: ldsfld int32 LocallocTest::locallocSize
IL_0010: ldc.i4 3000
IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*,
int32,
int32)
.try{
IL_001a: ldstr "Test Exception"
IL_001f: newobj instance void [mscorlib]System.Exception::.ctor(string)
IL_0024: throw
}
fault
{
IL_0025: ldstr "fault block in unwindTest2.\n"
IL_002a: call void [System.Console]System.Console::WriteLine(string)
IL_002f: ldarg.s i9
IL_0031: ldc.i4.s 9
IL_0033: beq.s IL_0047
IL_0035: ldstr "Parameters on stack is corrupted\n"
IL_003a: call void [System.Console]System.Console::WriteLine(string)
IL_003f: ldc.i4.1
IL_0040: stsfld bool LocallocTest::testFailed
IL_0045: br.s IL_0064
IL_0047: ldstr "intArray3"
IL_004c: ldloc.0
IL_004d: ldsfld int32 LocallocTest::locallocSize
IL_0052: ldc.i4 3000
IL_0057: call bool [localloc_common]LocallocTesting.Global::verifyStack(string,
int32*,
int32,
int32)
IL_005c: ldc.i4.0
IL_005d: ceq
IL_005f: stsfld bool LocallocTest::testFailed
IL_0064: endfault
}
IL_0065:
}
.method private hidebysig specialname rtspecialname static
void .cctor() cil managed
{
.maxstack 8
IL_0000: ldc.i4.0
IL_0001: stsfld bool LocallocTest::testFailed
IL_0006: ldc.i4.0
IL_0007: stsfld int32 LocallocTest::locallocSize
IL_000c: ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// Unwind from fault block
.assembly extern System.Console
{
.publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A )
.ver 4:0:0:0
}
.assembly extern xunit.core {}
.assembly extern mscorlib{}
.assembly extern localloc_common{}
.assembly 'unwind04_small'{}
.class private auto ansi beforefieldinit LocallocTest
extends [mscorlib]System.Object
{
.field private static bool testFailed
.field private static int32 locallocSize
.method public hidebysig static int32 Main() cil managed
{
.custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = (
01 00 00 00
)
.entrypoint
.maxstack 4
.locals (unsigned int64 local1,
unsigned int64 local2,
int32* intArray1,
int32 retValue)
IL_0000: ldc.i8 0xfedcba9876543210
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: conv.i8
IL_000d: add
IL_000e: stloc.1
IL_000f: ldc.i4.4
IL_0016: localloc
IL_0018: stloc.2
IL_0019: ldc.i4.1
IL_001e: stsfld int32 LocallocTest::locallocSize
.try
{
IL_0023: ldloc.2
IL_0024: ldsfld int32 LocallocTest::locallocSize
IL_0029: ldc.i4 1000
IL_002e: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*,
int32,
int32)
IL_0033: call void LocallocTest::unwindTest1()
IL_0038: ldc.i4.1
IL_0039: stloc.3
IL_003a: leave.s IL_00a8
}
catch [mscorlib]System.Object
{
IL_003c: pop
IL_003d: leave.s IL_003f
}
IL_003f: ldsfld bool LocallocTest::testFailed
IL_0044: brfalse.s IL_004a
IL_0046: ldc.i4.1
IL_0047: stloc.3
IL_0048: br.s IL_00a8
IL_004a: ldstr "intArray1"
IL_004f: ldloc.2
IL_0050: ldsfld int32 LocallocTest::locallocSize
IL_0055: ldc.i4 1000
IL_005a: call bool [localloc_common]LocallocTesting.Global::verifyStack(string,
int32*,
int32,
int32)
IL_005f: brtrue.s IL_0065
IL_0061: ldc.i4.1
IL_0062: stloc.3
IL_0063: br.s IL_00a8
IL_0065: ldstr "local1"
IL_006a: ldloc.0
IL_006b: ldc.i8 0xfedcba9876543210
IL_0074: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string,
unsigned int64,
unsigned int64)
IL_0079: brtrue.s IL_007f
IL_007b: ldc.i4.1
IL_007c: stloc.3
IL_007d: br.s IL_00a8
IL_007f: ldstr "local2"
IL_0084: ldloc.1
IL_0085: ldc.i8 0xfedcba9876543211
IL_008e: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string,
unsigned int64,
unsigned int64)
IL_0093: brtrue.s IL_0099
IL_0095: ldc.i4.1
IL_0096: stloc.3
IL_0097: br.s IL_00a8
IL_0099: ldstr "Passed\n"
IL_009e: call void [System.Console]System.Console::WriteLine(string)
IL_00a3: ldc.i4.s 100
IL_00a5: stloc.3
IL_00a6: br.s IL_00a8
IL_00a8: ldloc.3
IL_00a9: ret
}
.method public hidebysig static void unwindTest1() cil managed
{
.maxstack 10
.locals (int32* intArray2,
class LocallocTest testObj)
IL_0000: ldc.i4.4
IL_0007: localloc
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: ldsfld int32 LocallocTest::locallocSize
IL_0010: ldc.i4 2000
IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*,
int32,
int32)
.try
{
IL_001a: newobj instance void LocallocTest::.ctor()
IL_001f: stloc.1
IL_0020: ldloc.1
IL_0021: ldc.i4.1
IL_0022: ldc.i4.2
IL_0023: ldc.i4.3
IL_0024: ldc.i4.4
IL_0025: ldc.i4.5
IL_0026: ldc.i4.6
IL_0027: ldc.i4.7
IL_0028: ldc.i4.8
IL_0029: ldc.i4.s 9
IL_002b: callvirt instance void LocallocTest::unwindTest2(int32,
int32,
int32,
int32,
int32,
int32,
int32,
int32,
int32)
IL_0030: leave.s IL_0061
}
fault
{
IL_0032: ldstr "fault block in unwindTest1.\n"
IL_0037: call void [System.Console]System.Console::WriteLine(string)
IL_003c: ldsfld bool LocallocTest::testFailed
IL_0041: brtrue.s IL_0060
IL_0043: ldstr "intArray2"
IL_0048: ldloc.0
IL_0049: ldsfld int32 LocallocTest::locallocSize
IL_004e: ldc.i4 2000
IL_0053: call bool [localloc_common]LocallocTesting.Global::verifyStack(string,
int32*,
int32,
int32)
IL_0058: ldc.i4.0
IL_0059: ceq
IL_005b: stsfld bool LocallocTest::testFailed
IL_0060: endfault
}
IL_0061: br.s IL_0063
IL_0063: ret
}
.method private hidebysig instance void
unwindTest2(int32 i1,
int32 i2,
int32 i3,
int32 i4,
int32 i5,
int32 i6,
int32 i7,
int32 i8,
int32 i9) cil managed
{
.maxstack 4
.locals (int32* intArray3)
IL_0000: ldc.i4.4
IL_0007: localloc
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: ldsfld int32 LocallocTest::locallocSize
IL_0010: ldc.i4 3000
IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*,
int32,
int32)
.try{
IL_001a: ldstr "Test Exception"
IL_001f: newobj instance void [mscorlib]System.Exception::.ctor(string)
IL_0024: throw
}
fault
{
IL_0025: ldstr "fault block in unwindTest2.\n"
IL_002a: call void [System.Console]System.Console::WriteLine(string)
IL_002f: ldarg.s i9
IL_0031: ldc.i4.s 9
IL_0033: beq.s IL_0047
IL_0035: ldstr "Parameters on stack is corrupted\n"
IL_003a: call void [System.Console]System.Console::WriteLine(string)
IL_003f: ldc.i4.1
IL_0040: stsfld bool LocallocTest::testFailed
IL_0045: br.s IL_0064
IL_0047: ldstr "intArray3"
IL_004c: ldloc.0
IL_004d: ldsfld int32 LocallocTest::locallocSize
IL_0052: ldc.i4 3000
IL_0057: call bool [localloc_common]LocallocTesting.Global::verifyStack(string,
int32*,
int32,
int32)
IL_005c: ldc.i4.0
IL_005d: ceq
IL_005f: stsfld bool LocallocTest::testFailed
IL_0064: endfault
}
IL_0065:
}
.method private hidebysig specialname rtspecialname static
void .cctor() cil managed
{
.maxstack 8
IL_0000: ldc.i4.0
IL_0001: stsfld bool LocallocTest::testFailed
IL_0006: ldc.i4.0
IL_0007: stsfld int32 LocallocTest::locallocSize
IL_000c: ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/Loader/classloader/regressions/429802/CMain.ilproj
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="CMain.il" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="BarImpl.ilproj" />
<ProjectReference Include="MyBar.ilproj" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="CMain.il" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="BarImpl.ilproj" />
<ProjectReference Include="MyBar.ilproj" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Security.Cryptography/tests/Sha384Tests.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.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Security.Cryptography.Tests
{
public class Sha384Tests : HashAlgorithmTestDriver
{
protected override HashAlgorithm Create()
{
return SHA384.Create();
}
protected override bool TryHashData(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten)
{
return SHA384.TryHashData(source, destination, out bytesWritten);
}
protected override byte[] HashData(byte[] source) => SHA384.HashData(source);
protected override byte[] HashData(ReadOnlySpan<byte> source) => SHA384.HashData(source);
protected override int HashData(ReadOnlySpan<byte> source, Span<byte> destination) =>
SHA384.HashData(source, destination);
protected override int HashData(Stream source, Span<byte> destination) =>
SHA384.HashData(source, destination);
protected override byte[] HashData(Stream source) => SHA384.HashData(source);
protected override ValueTask<int> HashDataAsync(Stream source, Memory<byte> destination, CancellationToken cancellationToken) =>
SHA384.HashDataAsync(source, destination, cancellationToken);
protected override ValueTask<byte[]> HashDataAsync(Stream source, CancellationToken cancellationToken) =>
SHA384.HashDataAsync(source, cancellationToken);
[Fact]
public void Sha384_Empty()
{
Verify(
Array.Empty<byte>(),
"38B060A751AC96384CD9327EB1B1E36A21FDB71114BE07434C0CC7BF63F6E1DA274EDEBFE76F65FBD51AD2F14898B95B");
}
[Fact]
public void Sha384_Empty_Stream()
{
VerifyRepeating(
"",
0,
"38B060A751AC96384CD9327EB1B1E36A21FDB71114BE07434C0CC7BF63F6E1DA274EDEBFE76F65FBD51AD2F14898B95B");
}
[Fact]
public async Task Sha384_Empty_Stream_Async()
{
await VerifyRepeatingAsync(
"",
0,
"38B060A751AC96384CD9327EB1B1E36A21FDB71114BE07434C0CC7BF63F6E1DA274EDEBFE76F65FBD51AD2F14898B95B");
}
[Fact]
public void Sha384_VerifyLargeStream_MultipleOf4096()
{
// Verfied with:
// for _ in {1..1024}; do echo -n "0102030405060708"; done | openssl dgst -sha384
VerifyRepeating(
"0102030405060708",
1024,
"d9deec18b8ec0d31270eaeaaf3bcb1de55f1d81482a55d2c023bad873175f1694d8c28e8138d9147dc180e679cd79c58");
}
[Fact]
public void Sha384_VerifyLargeStream_NotMultipleOf4096()
{
// Verfied with:
// for _ in {1..1025}; do echo -n "0102030405060708"; done | openssl dgst -sha384
VerifyRepeating(
"0102030405060708",
1025,
"35cf18493364379093c7def8477330f817f9045d2e311d721730b24d98c9d9e9761c7f27821742e0c236509627aea7fa");
}
[Fact]
public async Task Sha384_VerifyLargeStream_NotMultipleOf4096_Async()
{
// Verfied with:
// for _ in {1..1025}; do echo -n "0102030405060708"; done | openssl dgst -sha384
await VerifyRepeatingAsync(
"0102030405060708",
1025,
"35cf18493364379093c7def8477330f817f9045d2e311d721730b24d98c9d9e9761c7f27821742e0c236509627aea7fa");
}
[Fact]
public async Task Sha384_VerifyLargeStream_MultipleOf4096_Async()
{
// Verfied with:
// for _ in {1..1024}; do echo -n "0102030405060708"; done | openssl dgst -sha384
await VerifyRepeatingAsync(
"0102030405060708",
1024,
"d9deec18b8ec0d31270eaeaaf3bcb1de55f1d81482a55d2c023bad873175f1694d8c28e8138d9147dc180e679cd79c58");
}
// These test cases are from http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/SHA_All.pdf
[Fact]
public void Sha384_NistShaAll_1()
{
Verify(
"abc",
"CB00753F45A35E8BB5A03D699AC65007272C32AB0EDED1631A8B605A43FF5BED8086072BA1E7CC2358BAECA134C825A7");
}
[Fact]
public void Sha384_Fips180_MultiBlock()
{
VerifyMultiBlock(
"a",
"bc",
"CB00753F45A35E8BB5A03D699AC65007272C32AB0EDED1631A8B605A43FF5BED8086072BA1E7CC2358BAECA134C825A7",
"38B060A751AC96384CD9327EB1B1E36A21FDB71114BE07434C0CC7BF63F6E1DA274EDEBFE76F65FBD51AD2F14898B95B");
}
[Fact]
public void Sha384_NistShaAll_2()
{
Verify(
"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
"09330C33F71147E83D192FC782CD1B4753111B173B3B05D22FA08086E3B0F712FCC7C71A557E2DB966C3E9FA91746039");
}
}
}
|
// 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.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Security.Cryptography.Tests
{
public class Sha384Tests : HashAlgorithmTestDriver
{
protected override HashAlgorithm Create()
{
return SHA384.Create();
}
protected override bool TryHashData(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten)
{
return SHA384.TryHashData(source, destination, out bytesWritten);
}
protected override byte[] HashData(byte[] source) => SHA384.HashData(source);
protected override byte[] HashData(ReadOnlySpan<byte> source) => SHA384.HashData(source);
protected override int HashData(ReadOnlySpan<byte> source, Span<byte> destination) =>
SHA384.HashData(source, destination);
protected override int HashData(Stream source, Span<byte> destination) =>
SHA384.HashData(source, destination);
protected override byte[] HashData(Stream source) => SHA384.HashData(source);
protected override ValueTask<int> HashDataAsync(Stream source, Memory<byte> destination, CancellationToken cancellationToken) =>
SHA384.HashDataAsync(source, destination, cancellationToken);
protected override ValueTask<byte[]> HashDataAsync(Stream source, CancellationToken cancellationToken) =>
SHA384.HashDataAsync(source, cancellationToken);
[Fact]
public void Sha384_Empty()
{
Verify(
Array.Empty<byte>(),
"38B060A751AC96384CD9327EB1B1E36A21FDB71114BE07434C0CC7BF63F6E1DA274EDEBFE76F65FBD51AD2F14898B95B");
}
[Fact]
public void Sha384_Empty_Stream()
{
VerifyRepeating(
"",
0,
"38B060A751AC96384CD9327EB1B1E36A21FDB71114BE07434C0CC7BF63F6E1DA274EDEBFE76F65FBD51AD2F14898B95B");
}
[Fact]
public async Task Sha384_Empty_Stream_Async()
{
await VerifyRepeatingAsync(
"",
0,
"38B060A751AC96384CD9327EB1B1E36A21FDB71114BE07434C0CC7BF63F6E1DA274EDEBFE76F65FBD51AD2F14898B95B");
}
[Fact]
public void Sha384_VerifyLargeStream_MultipleOf4096()
{
// Verfied with:
// for _ in {1..1024}; do echo -n "0102030405060708"; done | openssl dgst -sha384
VerifyRepeating(
"0102030405060708",
1024,
"d9deec18b8ec0d31270eaeaaf3bcb1de55f1d81482a55d2c023bad873175f1694d8c28e8138d9147dc180e679cd79c58");
}
[Fact]
public void Sha384_VerifyLargeStream_NotMultipleOf4096()
{
// Verfied with:
// for _ in {1..1025}; do echo -n "0102030405060708"; done | openssl dgst -sha384
VerifyRepeating(
"0102030405060708",
1025,
"35cf18493364379093c7def8477330f817f9045d2e311d721730b24d98c9d9e9761c7f27821742e0c236509627aea7fa");
}
[Fact]
public async Task Sha384_VerifyLargeStream_NotMultipleOf4096_Async()
{
// Verfied with:
// for _ in {1..1025}; do echo -n "0102030405060708"; done | openssl dgst -sha384
await VerifyRepeatingAsync(
"0102030405060708",
1025,
"35cf18493364379093c7def8477330f817f9045d2e311d721730b24d98c9d9e9761c7f27821742e0c236509627aea7fa");
}
[Fact]
public async Task Sha384_VerifyLargeStream_MultipleOf4096_Async()
{
// Verfied with:
// for _ in {1..1024}; do echo -n "0102030405060708"; done | openssl dgst -sha384
await VerifyRepeatingAsync(
"0102030405060708",
1024,
"d9deec18b8ec0d31270eaeaaf3bcb1de55f1d81482a55d2c023bad873175f1694d8c28e8138d9147dc180e679cd79c58");
}
// These test cases are from http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/SHA_All.pdf
[Fact]
public void Sha384_NistShaAll_1()
{
Verify(
"abc",
"CB00753F45A35E8BB5A03D699AC65007272C32AB0EDED1631A8B605A43FF5BED8086072BA1E7CC2358BAECA134C825A7");
}
[Fact]
public void Sha384_Fips180_MultiBlock()
{
VerifyMultiBlock(
"a",
"bc",
"CB00753F45A35E8BB5A03D699AC65007272C32AB0EDED1631A8B605A43FF5BED8086072BA1E7CC2358BAECA134C825A7",
"38B060A751AC96384CD9327EB1B1E36A21FDB71114BE07434C0CC7BF63F6E1DA274EDEBFE76F65FBD51AD2F14898B95B");
}
[Fact]
public void Sha384_NistShaAll_2()
{
Verify(
"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
"09330C33F71147E83D192FC782CD1B4753111B173B3B05D22FA08086E3B0F712FCC7C71A557E2DB966C3E9FA91746039");
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.ComponentModel.Composition/tests/System/ComponentModel/Composition/CompositionExceptionTests.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.ComponentModel.Composition.Factories;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Tests;
using System.Text;
using System.UnitTesting;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
using Xunit.Sdk;
namespace System.ComponentModel.Composition
{
[Serializable]
public class CompositionExceptionTests
{
[Fact]
public void Constructor1_ShouldSetMessagePropertyToDefault()
{
var exception = new CompositionException();
ExceptionAssert.HasDefaultMessage(exception);
}
[Fact]
public void Constructor2_NullAsMessageArgument_ShouldSetMessagePropertyToDefault()
{
var exception = new CompositionException((string)null);
ExceptionAssert.HasDefaultMessage(exception);
}
[Fact]
public void Constructor3_EmptyEnumerableAsErrorsArgument_ShouldSetMessagePropertyToDefault()
{
var exception = new CompositionException(Enumerable.Empty<CompositionError>());
ExceptionAssert.HasDefaultMessage(exception);
}
[Fact]
public void Constructor4_NullAsMessageArgument_ShouldSetMessagePropertyToDefault()
{
var exception = new CompositionException((string)null, new Exception());
ExceptionAssert.HasDefaultMessage(exception);
}
[Fact]
public void Constructor5_NullAsMessageArgument_ShouldSetMessagePropertyToDefault()
{
var exception = new CompositionException((string)null, new Exception(), Enumerable.Empty<CompositionError>());
ExceptionAssert.HasDefaultMessage(exception);
}
[Fact]
public void Constructor2_ValueAsMessageArgument_ShouldSetMessageProperty()
{
var expectations = Expectations.GetExceptionMessages();
foreach (var e in expectations)
{
var exception = new CompositionException(e);
Assert.Equal(e, exception.Message);
}
}
[Fact]
public void Constructor4_ValueAsMessageArgument_ShouldSetMessageProperty()
{
var expectations = Expectations.GetExceptionMessages();
foreach (var e in expectations)
{
var exception = new CompositionException(e, new Exception());
Assert.Equal(e, exception.Message);
}
}
[Fact]
public void Constructor5_ValueAsMessageArgument_ShouldSetMessageProperty()
{
var expectations = Expectations.GetExceptionMessages();
foreach (var e in expectations)
{
var exception = new CompositionException(e, new Exception(), Enumerable.Empty<CompositionError>());
Assert.Equal(e, exception.Message);
}
}
[Fact]
public void Constructor1_ShouldSetInnerExceptionPropertyToNull()
{
var exception = new CompositionException();
Assert.Null(exception.InnerException);
}
[Fact]
public void Constructor2_ShouldSetInnerExceptionPropertyToNull()
{
var exception = new CompositionException("Message");
Assert.Null(exception.InnerException);
}
[Fact]
public void Constructor3_ShouldSetInnerExceptionPropertyToNull()
{
var exception = new CompositionException(Enumerable.Empty<CompositionError>());
Assert.Null(exception.InnerException);
}
[Fact]
public void Constructor4_NullAsInnerExceptionArgument_ShouldSetInnerExceptionPropertyToNull()
{
var exception = new CompositionException("Message", (Exception)null);
Assert.Null(exception.InnerException);
}
[Fact]
public void Constructor5_NullAsInnerExceptionArgument_ShouldSetInnerExceptionPropertyToNull()
{
var exception = new CompositionException("Message", (Exception)null, Enumerable.Empty<CompositionError>());
Assert.Null(exception.InnerException);
}
[Fact]
public void Constructor4_ValueAsInnerExceptionArgument_ShouldSetInnerExceptionProperty()
{
var expectations = Expectations.GetInnerExceptions();
foreach (var e in expectations)
{
var exception = new CompositionException("Message", e);
Assert.Same(e, exception.InnerException);
}
}
[Fact]
public void Constructor5_ValueAsInnerExceptionArgument_ShouldSetInnerExceptionProperty()
{
var expectations = Expectations.GetInnerExceptions();
foreach (var e in expectations)
{
var exception = new CompositionException("Message", e, Enumerable.Empty<CompositionError>());
Assert.Same(e, exception.InnerException);
}
}
[Fact]
public void Constructor2_ArrayWithNullAsErrorsArgument_ShouldThrowArgument()
{
var errors = new CompositionError[] { null };
Assert.Throws<ArgumentException>("errors", () =>
{
new CompositionException(errors);
});
}
[Fact]
public void Constructor5_ArrayWithNullAsErrorsArgument_ShouldThrowArgument()
{
var errors = new CompositionError[] { null };
Assert.Throws<ArgumentException>("errors", () =>
{
new CompositionException("Message", new Exception(), errors);
});
}
[Fact]
public void Constructor1_ShouldSetErrorsPropertyToEmpty()
{
var exception = new CompositionException();
Assert.Empty(exception.Errors);
}
[Fact]
public void Constructor2_NullAsErrorsArgument_ShouldSetErrorsPropertyToEmptyEnumerable()
{
var exception = new CompositionException((IEnumerable<CompositionError>)null);
Assert.Empty(exception.Errors);
}
[Fact]
public void Constructor2_EmptyEnumerableAsErrorsArgument_ShouldSetErrorsPropertyToEmptyEnumerable()
{
var exception = new CompositionException(Enumerable.Empty<CompositionError>());
Assert.Empty(exception.Errors);
}
[Fact]
public void Constructor2_ValueAsErrorsArgument_ShouldSetErrorsProperty()
{
var expectations = Expectations.GetCompositionErrors();
foreach (var e in expectations)
{
var exception = new CompositionException(e);
EqualityExtensions.CheckEquals(e, exception.Errors);
}
}
[Fact]
public void Constructor2_ArrayAsAsErrorsArgument_ShouldNotAllowModificationAfterConstruction()
{
var error = CreateCompositionError();
var errors = new CompositionError[] { error };
var exception = new CompositionException(errors);
errors[0] = null;
EnumerableAssert.AreEqual(exception.Errors, error);
}
[Fact]
public void Constructor3_ShouldSetErrorsPropertyToEmpty()
{
var exception = new CompositionException();
Assert.Empty(exception.Errors);
}
[Fact]
public void Constructor4_ShouldSetErrorsPropertyToEmptyEnumerable()
{
var exception = new CompositionException("Message", new Exception());
Assert.Empty(exception.Errors);
}
[Fact]
public void Constructor5_NullAsErrorsArgument_ShouldSetErrorsPropertyToEmptyEnumerable()
{
var exception = new CompositionException("Message", new Exception(), (IEnumerable<CompositionError>)null);
Assert.Empty(exception.Errors);
}
[Fact]
public void Constructor5_EmptyEnumerableAsErrorsArgument_ShouldSetErrorsPropertyToEmptyEnumerable()
{
var exception = new CompositionException("Message", new Exception(), Enumerable.Empty<CompositionError>());
Assert.Empty(exception.Errors);
}
[Fact]
public void Constructor5_ValueAsErrorsArgument_ShouldSetErrorsProperty()
{
var expectations = Expectations.GetCompositionErrors();
foreach (var e in expectations)
{
var exception = new CompositionException("Message", new Exception(), e);
EqualityExtensions.CheckEquals(e, exception.Errors);
}
}
[Fact]
public void Constructor5_ArrayAsAsErrorsArgument_ShouldNotAllowModificationAfterConstruction()
{
var error = CreateCompositionError();
var errors = new CompositionError[] { error };
var exception = new CompositionException("Message", new Exception(), errors);
errors[0] = null;
EnumerableAssert.AreEqual(exception.Errors, error);
}
[Fact]
public void Message_ShouldIncludeElementGraph()
{
var expectations = new ExpectationCollection<CompositionError, string>();
CompositionError error = null;
error = CreateCompositionErrorWithElementChain(1);
expectations.Add(error, GetElementGraphString(error));
error = CreateCompositionErrorWithElementChain(2);
expectations.Add(error, GetElementGraphString(error));
error = CreateCompositionErrorWithElementChain(3);
expectations.Add(error, GetElementGraphString(error));
error = CreateCompositionErrorWithElementChain(10);
expectations.Add(error, GetElementGraphString(error));
foreach (var e in expectations)
{
var exception = CreateCompositionException(new CompositionError[] { e.Input });
string result = exception.ToString();
string expected = FixMessage(e.Output);
AssertExtensions.Contains(result, expected);
}
}
[Fact]
public void Message_ShouldIncludeErrors()
{
var expectations = new ExpectationCollection<IEnumerable<CompositionError>, string>();
expectations.Add(ErrorFactory.CreateFromDsl("Error"), "1<Separator> Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error|Error"), "1<Separator> Error|2<Separator> Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error|Error|Error"), "1<Separator> Error|2<Separator> Error|3<Separator> Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error)"), "1<Separator> Error|<Prefix>Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error|Error)"), "1<Separator> Error|<Prefix>Error|2<Separator> Error|<Prefix>Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error|Error|Error)"), "1<Separator> Error|<Prefix>Error|2<Separator> Error|<Prefix>Error|3<Separator> Error|<Prefix>Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error(Exception))"), "1<Separator> Exception|<Prefix>Error|<Prefix>Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error|Exception)"), "1<Separator> Error|<Prefix>Error|2<Separator> Exception|<Prefix>Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error(Exception)"), "1<Separator> Exception|<Prefix>Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error(Exception(Exception))"), "1<Separator> Exception|<Prefix>Exception|<Prefix>Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error(Exception)|Error)"), "1<Separator> Exception|<Prefix>Error|<Prefix>Error|2<Separator> Error|<Prefix>Error");
foreach (var e in expectations)
{
var exception = CreateCompositionException(e.Input);
AssertMessage(exception, e.Output.Split('|'));
}
}
[Fact]
public void Messsage_ShouldIncludeCountOfRootCauses()
{
var expectations = new ExpectationCollection<IEnumerable<CompositionError>, int>();
expectations.Add(ErrorFactory.CreateFromDsl("Error"), 1);
expectations.Add(ErrorFactory.CreateFromDsl("Error|Error"), 2);
expectations.Add(ErrorFactory.CreateFromDsl("Error|Error|Error"), 3);
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error)"), 1);
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error)|Error(Error)"), 2);
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error|Error)"), 2);
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error|Error|Exception)"), 3);
foreach (var e in expectations)
{
var exception = CreateCompositionException(e.Input);
AssertMessage(exception, e.Output, CultureInfo.CurrentCulture);
}
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void Message_ShouldFormatCountOfRootCausesUsingTheCurrentCulture()
{
RemoteExecutor.Invoke(() =>
{
IEnumerable<CultureInfo> cultures = Expectations.GetCulturesForFormatting();
foreach (CultureInfo culture in cultures)
{
// Save old culture and set a fixed culture for object instantiation
using (new ThreadCultureChange(culture, culture))
{
CompositionError[] errors = CreateCompositionErrors(1000);
CompositionException exception = CreateCompositionException(errors);
AssertMessage(exception, 1000, culture);
errors = CreateCompositionErrors(1);
exception = CreateCompositionException(errors);
AssertMessage(exception, 1, culture);
}
}
}).Dispose();
}
private string GetElementGraphString(CompositionError error)
{
StringBuilder writer = new StringBuilder();
ICompositionElement element = error.Element;
writer.AppendFormat(CultureInfo.CurrentCulture, SR.CompositionException_ElementPrefix, element.DisplayName);
while ((element = element.Origin) != null)
{
writer.AppendFormat(CultureInfo.CurrentCulture, SR.CompositionException_OriginFormat, SR.CompositionException_OriginSeparator, element.DisplayName);
}
return writer.ToString();
}
private void AssertMessage(CompositionException exception, int rootCauseCount, CultureInfo culture)
{
using (StringReader reader = new StringReader(exception.Message))
{
string line = reader.ReadLine();
if (rootCauseCount == 1)
{
Assert.Contains(SR.CompositionException_SingleErrorWithSinglePath, line);
}
else
{
string option1 = string.Format(CultureInfo.CurrentCulture, SR.CompositionException_SingleErrorWithMultiplePaths, rootCauseCount);
string option2 = string.Format(CultureInfo.CurrentCulture, SR.CompositionException_MultipleErrorsWithMultiplePaths, rootCauseCount);
if (!line.Contains(option1) && !line.Contains(option2))
{
throw new XunitException($"`{line}` contains neither `{option1}` nor `{option2}`");
}
}
}
}
private void AssertMessage(CompositionException exception, string[] expected)
{
using (StringReader reader = new StringReader(exception.Message))
{
// Skip header
reader.ReadLine();
foreach (string expect in expected)
{
// Skip blank line
reader.ReadLine();
Assert.Equal(FixMessage(expect), reader.ReadLine());
}
}
}
private string FixMessage(string expect)
{
string fixedPrefix = expect.Replace("<Prefix>", SR.CompositionException_ErrorPrefix + " ");
string fixedSeparator = fixedPrefix.Replace("<Separator>", SR.CompositionException_PathsCountSeparator);
return fixedSeparator.Replace("<OriginSeparator>", SR.CompositionException_OriginSeparator);
}
private static CompositionError CreateCompositionError()
{
return CreateCompositionError("Description");
}
private static CompositionError CreateCompositionError(string message)
{
return new CompositionError(message);
}
private static CompositionError CreateCompositionErrorWithElementChain(int count)
{
return new CompositionError("Description", ElementFactory.CreateChain(count));
}
private static CompositionError[] CreateCompositionErrors(int count)
{
CompositionError[] errors = new CompositionError[count];
for (int i = 0; i < count; i++)
{
errors[i] = CreateCompositionError("Description" + (i + 1));
}
return errors;
}
private static CompositionException CreateCompositionException()
{
return CreateCompositionException((string)null, (Exception)null, (IEnumerable<CompositionError>)null);
}
private static CompositionException CreateCompositionException(string message)
{
return CreateCompositionException(message, (Exception)null, (IEnumerable<CompositionError>)null);
}
private static CompositionException CreateCompositionException(IEnumerable<CompositionError> errors)
{
return CreateCompositionException((string)null, (Exception)null, errors);
}
private static CompositionException CreateCompositionException(Exception innerException)
{
return CreateCompositionException((string)null, innerException, (IEnumerable<CompositionError>)null);
}
private static CompositionException CreateCompositionException(string message, Exception innerException, IEnumerable<CompositionError> errors)
{
return new CompositionException(message, innerException, errors);
}
}
}
|
// 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.ComponentModel.Composition.Factories;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Tests;
using System.Text;
using System.UnitTesting;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
using Xunit.Sdk;
namespace System.ComponentModel.Composition
{
[Serializable]
public class CompositionExceptionTests
{
[Fact]
public void Constructor1_ShouldSetMessagePropertyToDefault()
{
var exception = new CompositionException();
ExceptionAssert.HasDefaultMessage(exception);
}
[Fact]
public void Constructor2_NullAsMessageArgument_ShouldSetMessagePropertyToDefault()
{
var exception = new CompositionException((string)null);
ExceptionAssert.HasDefaultMessage(exception);
}
[Fact]
public void Constructor3_EmptyEnumerableAsErrorsArgument_ShouldSetMessagePropertyToDefault()
{
var exception = new CompositionException(Enumerable.Empty<CompositionError>());
ExceptionAssert.HasDefaultMessage(exception);
}
[Fact]
public void Constructor4_NullAsMessageArgument_ShouldSetMessagePropertyToDefault()
{
var exception = new CompositionException((string)null, new Exception());
ExceptionAssert.HasDefaultMessage(exception);
}
[Fact]
public void Constructor5_NullAsMessageArgument_ShouldSetMessagePropertyToDefault()
{
var exception = new CompositionException((string)null, new Exception(), Enumerable.Empty<CompositionError>());
ExceptionAssert.HasDefaultMessage(exception);
}
[Fact]
public void Constructor2_ValueAsMessageArgument_ShouldSetMessageProperty()
{
var expectations = Expectations.GetExceptionMessages();
foreach (var e in expectations)
{
var exception = new CompositionException(e);
Assert.Equal(e, exception.Message);
}
}
[Fact]
public void Constructor4_ValueAsMessageArgument_ShouldSetMessageProperty()
{
var expectations = Expectations.GetExceptionMessages();
foreach (var e in expectations)
{
var exception = new CompositionException(e, new Exception());
Assert.Equal(e, exception.Message);
}
}
[Fact]
public void Constructor5_ValueAsMessageArgument_ShouldSetMessageProperty()
{
var expectations = Expectations.GetExceptionMessages();
foreach (var e in expectations)
{
var exception = new CompositionException(e, new Exception(), Enumerable.Empty<CompositionError>());
Assert.Equal(e, exception.Message);
}
}
[Fact]
public void Constructor1_ShouldSetInnerExceptionPropertyToNull()
{
var exception = new CompositionException();
Assert.Null(exception.InnerException);
}
[Fact]
public void Constructor2_ShouldSetInnerExceptionPropertyToNull()
{
var exception = new CompositionException("Message");
Assert.Null(exception.InnerException);
}
[Fact]
public void Constructor3_ShouldSetInnerExceptionPropertyToNull()
{
var exception = new CompositionException(Enumerable.Empty<CompositionError>());
Assert.Null(exception.InnerException);
}
[Fact]
public void Constructor4_NullAsInnerExceptionArgument_ShouldSetInnerExceptionPropertyToNull()
{
var exception = new CompositionException("Message", (Exception)null);
Assert.Null(exception.InnerException);
}
[Fact]
public void Constructor5_NullAsInnerExceptionArgument_ShouldSetInnerExceptionPropertyToNull()
{
var exception = new CompositionException("Message", (Exception)null, Enumerable.Empty<CompositionError>());
Assert.Null(exception.InnerException);
}
[Fact]
public void Constructor4_ValueAsInnerExceptionArgument_ShouldSetInnerExceptionProperty()
{
var expectations = Expectations.GetInnerExceptions();
foreach (var e in expectations)
{
var exception = new CompositionException("Message", e);
Assert.Same(e, exception.InnerException);
}
}
[Fact]
public void Constructor5_ValueAsInnerExceptionArgument_ShouldSetInnerExceptionProperty()
{
var expectations = Expectations.GetInnerExceptions();
foreach (var e in expectations)
{
var exception = new CompositionException("Message", e, Enumerable.Empty<CompositionError>());
Assert.Same(e, exception.InnerException);
}
}
[Fact]
public void Constructor2_ArrayWithNullAsErrorsArgument_ShouldThrowArgument()
{
var errors = new CompositionError[] { null };
Assert.Throws<ArgumentException>("errors", () =>
{
new CompositionException(errors);
});
}
[Fact]
public void Constructor5_ArrayWithNullAsErrorsArgument_ShouldThrowArgument()
{
var errors = new CompositionError[] { null };
Assert.Throws<ArgumentException>("errors", () =>
{
new CompositionException("Message", new Exception(), errors);
});
}
[Fact]
public void Constructor1_ShouldSetErrorsPropertyToEmpty()
{
var exception = new CompositionException();
Assert.Empty(exception.Errors);
}
[Fact]
public void Constructor2_NullAsErrorsArgument_ShouldSetErrorsPropertyToEmptyEnumerable()
{
var exception = new CompositionException((IEnumerable<CompositionError>)null);
Assert.Empty(exception.Errors);
}
[Fact]
public void Constructor2_EmptyEnumerableAsErrorsArgument_ShouldSetErrorsPropertyToEmptyEnumerable()
{
var exception = new CompositionException(Enumerable.Empty<CompositionError>());
Assert.Empty(exception.Errors);
}
[Fact]
public void Constructor2_ValueAsErrorsArgument_ShouldSetErrorsProperty()
{
var expectations = Expectations.GetCompositionErrors();
foreach (var e in expectations)
{
var exception = new CompositionException(e);
EqualityExtensions.CheckEquals(e, exception.Errors);
}
}
[Fact]
public void Constructor2_ArrayAsAsErrorsArgument_ShouldNotAllowModificationAfterConstruction()
{
var error = CreateCompositionError();
var errors = new CompositionError[] { error };
var exception = new CompositionException(errors);
errors[0] = null;
EnumerableAssert.AreEqual(exception.Errors, error);
}
[Fact]
public void Constructor3_ShouldSetErrorsPropertyToEmpty()
{
var exception = new CompositionException();
Assert.Empty(exception.Errors);
}
[Fact]
public void Constructor4_ShouldSetErrorsPropertyToEmptyEnumerable()
{
var exception = new CompositionException("Message", new Exception());
Assert.Empty(exception.Errors);
}
[Fact]
public void Constructor5_NullAsErrorsArgument_ShouldSetErrorsPropertyToEmptyEnumerable()
{
var exception = new CompositionException("Message", new Exception(), (IEnumerable<CompositionError>)null);
Assert.Empty(exception.Errors);
}
[Fact]
public void Constructor5_EmptyEnumerableAsErrorsArgument_ShouldSetErrorsPropertyToEmptyEnumerable()
{
var exception = new CompositionException("Message", new Exception(), Enumerable.Empty<CompositionError>());
Assert.Empty(exception.Errors);
}
[Fact]
public void Constructor5_ValueAsErrorsArgument_ShouldSetErrorsProperty()
{
var expectations = Expectations.GetCompositionErrors();
foreach (var e in expectations)
{
var exception = new CompositionException("Message", new Exception(), e);
EqualityExtensions.CheckEquals(e, exception.Errors);
}
}
[Fact]
public void Constructor5_ArrayAsAsErrorsArgument_ShouldNotAllowModificationAfterConstruction()
{
var error = CreateCompositionError();
var errors = new CompositionError[] { error };
var exception = new CompositionException("Message", new Exception(), errors);
errors[0] = null;
EnumerableAssert.AreEqual(exception.Errors, error);
}
[Fact]
public void Message_ShouldIncludeElementGraph()
{
var expectations = new ExpectationCollection<CompositionError, string>();
CompositionError error = null;
error = CreateCompositionErrorWithElementChain(1);
expectations.Add(error, GetElementGraphString(error));
error = CreateCompositionErrorWithElementChain(2);
expectations.Add(error, GetElementGraphString(error));
error = CreateCompositionErrorWithElementChain(3);
expectations.Add(error, GetElementGraphString(error));
error = CreateCompositionErrorWithElementChain(10);
expectations.Add(error, GetElementGraphString(error));
foreach (var e in expectations)
{
var exception = CreateCompositionException(new CompositionError[] { e.Input });
string result = exception.ToString();
string expected = FixMessage(e.Output);
AssertExtensions.Contains(result, expected);
}
}
[Fact]
public void Message_ShouldIncludeErrors()
{
var expectations = new ExpectationCollection<IEnumerable<CompositionError>, string>();
expectations.Add(ErrorFactory.CreateFromDsl("Error"), "1<Separator> Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error|Error"), "1<Separator> Error|2<Separator> Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error|Error|Error"), "1<Separator> Error|2<Separator> Error|3<Separator> Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error)"), "1<Separator> Error|<Prefix>Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error|Error)"), "1<Separator> Error|<Prefix>Error|2<Separator> Error|<Prefix>Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error|Error|Error)"), "1<Separator> Error|<Prefix>Error|2<Separator> Error|<Prefix>Error|3<Separator> Error|<Prefix>Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error(Exception))"), "1<Separator> Exception|<Prefix>Error|<Prefix>Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error|Exception)"), "1<Separator> Error|<Prefix>Error|2<Separator> Exception|<Prefix>Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error(Exception)"), "1<Separator> Exception|<Prefix>Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error(Exception(Exception))"), "1<Separator> Exception|<Prefix>Exception|<Prefix>Error");
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error(Exception)|Error)"), "1<Separator> Exception|<Prefix>Error|<Prefix>Error|2<Separator> Error|<Prefix>Error");
foreach (var e in expectations)
{
var exception = CreateCompositionException(e.Input);
AssertMessage(exception, e.Output.Split('|'));
}
}
[Fact]
public void Messsage_ShouldIncludeCountOfRootCauses()
{
var expectations = new ExpectationCollection<IEnumerable<CompositionError>, int>();
expectations.Add(ErrorFactory.CreateFromDsl("Error"), 1);
expectations.Add(ErrorFactory.CreateFromDsl("Error|Error"), 2);
expectations.Add(ErrorFactory.CreateFromDsl("Error|Error|Error"), 3);
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error)"), 1);
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error)|Error(Error)"), 2);
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error|Error)"), 2);
expectations.Add(ErrorFactory.CreateFromDsl("Error(Error|Error|Exception)"), 3);
foreach (var e in expectations)
{
var exception = CreateCompositionException(e.Input);
AssertMessage(exception, e.Output, CultureInfo.CurrentCulture);
}
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void Message_ShouldFormatCountOfRootCausesUsingTheCurrentCulture()
{
RemoteExecutor.Invoke(() =>
{
IEnumerable<CultureInfo> cultures = Expectations.GetCulturesForFormatting();
foreach (CultureInfo culture in cultures)
{
// Save old culture and set a fixed culture for object instantiation
using (new ThreadCultureChange(culture, culture))
{
CompositionError[] errors = CreateCompositionErrors(1000);
CompositionException exception = CreateCompositionException(errors);
AssertMessage(exception, 1000, culture);
errors = CreateCompositionErrors(1);
exception = CreateCompositionException(errors);
AssertMessage(exception, 1, culture);
}
}
}).Dispose();
}
private string GetElementGraphString(CompositionError error)
{
StringBuilder writer = new StringBuilder();
ICompositionElement element = error.Element;
writer.AppendFormat(CultureInfo.CurrentCulture, SR.CompositionException_ElementPrefix, element.DisplayName);
while ((element = element.Origin) != null)
{
writer.AppendFormat(CultureInfo.CurrentCulture, SR.CompositionException_OriginFormat, SR.CompositionException_OriginSeparator, element.DisplayName);
}
return writer.ToString();
}
private void AssertMessage(CompositionException exception, int rootCauseCount, CultureInfo culture)
{
using (StringReader reader = new StringReader(exception.Message))
{
string line = reader.ReadLine();
if (rootCauseCount == 1)
{
Assert.Contains(SR.CompositionException_SingleErrorWithSinglePath, line);
}
else
{
string option1 = string.Format(CultureInfo.CurrentCulture, SR.CompositionException_SingleErrorWithMultiplePaths, rootCauseCount);
string option2 = string.Format(CultureInfo.CurrentCulture, SR.CompositionException_MultipleErrorsWithMultiplePaths, rootCauseCount);
if (!line.Contains(option1) && !line.Contains(option2))
{
throw new XunitException($"`{line}` contains neither `{option1}` nor `{option2}`");
}
}
}
}
private void AssertMessage(CompositionException exception, string[] expected)
{
using (StringReader reader = new StringReader(exception.Message))
{
// Skip header
reader.ReadLine();
foreach (string expect in expected)
{
// Skip blank line
reader.ReadLine();
Assert.Equal(FixMessage(expect), reader.ReadLine());
}
}
}
private string FixMessage(string expect)
{
string fixedPrefix = expect.Replace("<Prefix>", SR.CompositionException_ErrorPrefix + " ");
string fixedSeparator = fixedPrefix.Replace("<Separator>", SR.CompositionException_PathsCountSeparator);
return fixedSeparator.Replace("<OriginSeparator>", SR.CompositionException_OriginSeparator);
}
private static CompositionError CreateCompositionError()
{
return CreateCompositionError("Description");
}
private static CompositionError CreateCompositionError(string message)
{
return new CompositionError(message);
}
private static CompositionError CreateCompositionErrorWithElementChain(int count)
{
return new CompositionError("Description", ElementFactory.CreateChain(count));
}
private static CompositionError[] CreateCompositionErrors(int count)
{
CompositionError[] errors = new CompositionError[count];
for (int i = 0; i < count; i++)
{
errors[i] = CreateCompositionError("Description" + (i + 1));
}
return errors;
}
private static CompositionException CreateCompositionException()
{
return CreateCompositionException((string)null, (Exception)null, (IEnumerable<CompositionError>)null);
}
private static CompositionException CreateCompositionException(string message)
{
return CreateCompositionException(message, (Exception)null, (IEnumerable<CompositionError>)null);
}
private static CompositionException CreateCompositionException(IEnumerable<CompositionError> errors)
{
return CreateCompositionException((string)null, (Exception)null, errors);
}
private static CompositionException CreateCompositionException(Exception innerException)
{
return CreateCompositionException((string)null, innerException, (IEnumerable<CompositionError>)null);
}
private static CompositionException CreateCompositionException(string message, Exception innerException, IEnumerable<CompositionError> errors)
{
return new CompositionException(message, innerException, errors);
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Transactions.Local/src/System/Transactions/IPromotableSinglePhaseNotification.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.Transactions
{
public interface IPromotableSinglePhaseNotification : ITransactionPromoter
{
void Initialize();
void SinglePhaseCommit(SinglePhaseEnlistment singlePhaseEnlistment);
void Rollback(SinglePhaseEnlistment singlePhaseEnlistment);
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Transactions
{
public interface IPromotableSinglePhaseNotification : ITransactionPromoter
{
void Initialize();
void SinglePhaseCommit(SinglePhaseEnlistment singlePhaseEnlistment);
void Rollback(SinglePhaseEnlistment singlePhaseEnlistment);
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Net.Http/src/System/Net/Http/Headers/KnownHeaders.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Net.Http.HPack;
using System.Net.Http.QPack;
using System.Runtime.InteropServices;
namespace System.Net.Http.Headers
{
internal static class KnownHeaders
{
// If you add a new entry here, you need to add it to TryGetKnownHeader below as well.
public static readonly KnownHeader PseudoStatus = new KnownHeader(":status", HttpHeaderType.Response, parser: null);
public static readonly KnownHeader Accept = new KnownHeader("Accept", HttpHeaderType.Request, MediaTypeHeaderParser.MultipleValuesParser, null, H2StaticTable.Accept, H3StaticTable.AcceptAny);
public static readonly KnownHeader AcceptCharset = new KnownHeader("Accept-Charset", HttpHeaderType.Request, GenericHeaderParser.MultipleValueStringWithQualityParser, null, H2StaticTable.AcceptCharset);
public static readonly KnownHeader AcceptEncoding = new KnownHeader("Accept-Encoding", HttpHeaderType.Request, GenericHeaderParser.MultipleValueStringWithQualityParser, null, H2StaticTable.AcceptEncoding, H3StaticTable.AcceptEncodingGzipDeflateBr);
public static readonly KnownHeader AcceptLanguage = new KnownHeader("Accept-Language", HttpHeaderType.Request, GenericHeaderParser.MultipleValueStringWithQualityParser, null, H2StaticTable.AcceptLanguage, H3StaticTable.AcceptLanguage);
public static readonly KnownHeader AcceptPatch = new KnownHeader("Accept-Patch");
public static readonly KnownHeader AcceptRanges = new KnownHeader("Accept-Ranges", HttpHeaderType.Response, GenericHeaderParser.TokenListParser, null, H2StaticTable.AcceptRanges, H3StaticTable.AcceptRangesBytes);
public static readonly KnownHeader AccessControlAllowCredentials = new KnownHeader("Access-Control-Allow-Credentials", HttpHeaderType.Response, parser: null, new string[] { "true" }, http3StaticTableIndex: H3StaticTable.AccessControlAllowCredentials);
public static readonly KnownHeader AccessControlAllowHeaders = new KnownHeader("Access-Control-Allow-Headers", HttpHeaderType.Response, parser: null, new string[] { "*" }, http3StaticTableIndex: H3StaticTable.AccessControlAllowHeadersCacheControl);
public static readonly KnownHeader AccessControlAllowMethods = new KnownHeader("Access-Control-Allow-Methods", HttpHeaderType.Response, parser: null, new string[] { "*" }, http3StaticTableIndex: H3StaticTable.AccessControlAllowMethodsGet);
public static readonly KnownHeader AccessControlAllowOrigin = new KnownHeader("Access-Control-Allow-Origin", HttpHeaderType.Response, parser: null, new string[] { "*", "null" }, H2StaticTable.AccessControlAllowOrigin, H3StaticTable.AccessControlAllowOriginAny);
public static readonly KnownHeader AccessControlExposeHeaders = new KnownHeader("Access-Control-Expose-Headers", HttpHeaderType.Response, parser: null, new string[] { "*" }, H3StaticTable.AccessControlExposeHeadersContentLength);
public static readonly KnownHeader AccessControlMaxAge = new KnownHeader("Access-Control-Max-Age");
public static readonly KnownHeader Age = new KnownHeader("Age", HttpHeaderType.Response | HttpHeaderType.NonTrailing, TimeSpanHeaderParser.Parser, null, H2StaticTable.Age, H3StaticTable.Age0);
public static readonly KnownHeader Allow = new KnownHeader("Allow", HttpHeaderType.Content, GenericHeaderParser.TokenListParser, null, H2StaticTable.Allow);
public static readonly KnownHeader AltSvc = new KnownHeader("Alt-Svc", HttpHeaderType.Response, GetAltSvcHeaderParser(), http3StaticTableIndex: H3StaticTable.AltSvcClear);
public static readonly KnownHeader AltUsed = new KnownHeader("Alt-Used", HttpHeaderType.Request, parser: null);
public static readonly KnownHeader Authorization = new KnownHeader("Authorization", HttpHeaderType.Request | HttpHeaderType.NonTrailing, GenericHeaderParser.SingleValueAuthenticationParser, null, H2StaticTable.Authorization, H3StaticTable.Authorization);
public static readonly KnownHeader CacheControl = new KnownHeader("Cache-Control", HttpHeaderType.General | HttpHeaderType.NonTrailing, CacheControlHeaderParser.Parser, new string[] { "must-revalidate", "no-cache", "no-store", "no-transform", "private", "proxy-revalidate", "public" }, H2StaticTable.CacheControl, H3StaticTable.CacheControlMaxAge0);
public static readonly KnownHeader Connection = new KnownHeader("Connection", HttpHeaderType.General, GenericHeaderParser.TokenListParser, new string[] { "close" });
public static readonly KnownHeader ContentDisposition = new KnownHeader("Content-Disposition", HttpHeaderType.Content | HttpHeaderType.NonTrailing, GenericHeaderParser.ContentDispositionParser, new string[] { "inline", "attachment" }, H2StaticTable.ContentDisposition, H3StaticTable.ContentDisposition);
public static readonly KnownHeader ContentEncoding = new KnownHeader("Content-Encoding", HttpHeaderType.Content | HttpHeaderType.NonTrailing, GenericHeaderParser.TokenListParser, new string[] { "gzip", "deflate", "br", "compress", "identity" }, H2StaticTable.ContentEncoding, H3StaticTable.ContentEncodingBr);
public static readonly KnownHeader ContentLanguage = new KnownHeader("Content-Language", HttpHeaderType.Content, GenericHeaderParser.TokenListParser, null, H2StaticTable.ContentLanguage);
public static readonly KnownHeader ContentLength = new KnownHeader("Content-Length", HttpHeaderType.Content | HttpHeaderType.NonTrailing, Int64NumberHeaderParser.Parser, null, H2StaticTable.ContentLength, H3StaticTable.ContentLength0);
public static readonly KnownHeader ContentLocation = new KnownHeader("Content-Location", HttpHeaderType.Content | HttpHeaderType.NonTrailing, UriHeaderParser.RelativeOrAbsoluteUriParser, null, H2StaticTable.ContentLocation);
public static readonly KnownHeader ContentMD5 = new KnownHeader("Content-MD5", HttpHeaderType.Content, ByteArrayHeaderParser.Parser);
public static readonly KnownHeader ContentRange = new KnownHeader("Content-Range", HttpHeaderType.Content | HttpHeaderType.NonTrailing, GenericHeaderParser.ContentRangeParser, null, H2StaticTable.ContentRange);
public static readonly KnownHeader ContentSecurityPolicy = new KnownHeader("Content-Security-Policy", http3StaticTableIndex: H3StaticTable.ContentSecurityPolicyAllNone);
public static readonly KnownHeader ContentType = new KnownHeader("Content-Type", HttpHeaderType.Content | HttpHeaderType.NonTrailing, MediaTypeHeaderParser.SingleValueParser, null, H2StaticTable.ContentType, H3StaticTable.ContentTypeApplicationDnsMessage);
public static readonly KnownHeader Cookie = new KnownHeader("Cookie", H2StaticTable.Cookie, H3StaticTable.Cookie);
public static readonly KnownHeader Cookie2 = new KnownHeader("Cookie2");
public static readonly KnownHeader Date = new KnownHeader("Date", HttpHeaderType.General | HttpHeaderType.NonTrailing, DateHeaderParser.Parser, null, H2StaticTable.Date, H3StaticTable.Date);
public static readonly KnownHeader ETag = new KnownHeader("ETag", HttpHeaderType.Response, GenericHeaderParser.SingleValueEntityTagParser, null, H2StaticTable.ETag, H3StaticTable.ETag);
public static readonly KnownHeader Expect = new KnownHeader("Expect", HttpHeaderType.Request | HttpHeaderType.NonTrailing, GenericHeaderParser.MultipleValueNameValueWithParametersParser, new string[] { "100-continue" }, H2StaticTable.Expect);
public static readonly KnownHeader ExpectCT = new KnownHeader("Expect-CT");
public static readonly KnownHeader Expires = new KnownHeader("Expires", HttpHeaderType.Content | HttpHeaderType.NonTrailing, DateHeaderParser.Parser, null, H2StaticTable.Expires);
public static readonly KnownHeader From = new KnownHeader("From", HttpHeaderType.Request, GenericHeaderParser.SingleValueParserWithoutValidation, null, H2StaticTable.From);
public static readonly KnownHeader GrpcEncoding = new KnownHeader("grpc-encoding", HttpHeaderType.Custom, null, new string[] { "identity", "gzip", "deflate" });
public static readonly KnownHeader GrpcMessage = new KnownHeader("grpc-message");
public static readonly KnownHeader GrpcStatus = new KnownHeader("grpc-status", HttpHeaderType.Custom, null, new string[] { "0" });
public static readonly KnownHeader Host = new KnownHeader("Host", HttpHeaderType.Request | HttpHeaderType.NonTrailing, GenericHeaderParser.HostParser, null, H2StaticTable.Host);
public static readonly KnownHeader IfMatch = new KnownHeader("If-Match", HttpHeaderType.Request | HttpHeaderType.NonTrailing, GenericHeaderParser.MultipleValueEntityTagParser, null, H2StaticTable.IfMatch);
public static readonly KnownHeader IfModifiedSince = new KnownHeader("If-Modified-Since", HttpHeaderType.Request | HttpHeaderType.NonTrailing, DateHeaderParser.Parser, null, H2StaticTable.IfModifiedSince, H3StaticTable.IfModifiedSince);
public static readonly KnownHeader IfNoneMatch = new KnownHeader("If-None-Match", HttpHeaderType.Request | HttpHeaderType.NonTrailing, GenericHeaderParser.MultipleValueEntityTagParser, null, H2StaticTable.IfNoneMatch, H3StaticTable.IfNoneMatch);
public static readonly KnownHeader IfRange = new KnownHeader("If-Range", HttpHeaderType.Request | HttpHeaderType.NonTrailing, GenericHeaderParser.RangeConditionParser, null, H2StaticTable.IfRange, H3StaticTable.IfRange);
public static readonly KnownHeader IfUnmodifiedSince = new KnownHeader("If-Unmodified-Since", HttpHeaderType.Request | HttpHeaderType.NonTrailing, DateHeaderParser.Parser, null, H2StaticTable.IfUnmodifiedSince);
public static readonly KnownHeader KeepAlive = new KnownHeader("Keep-Alive");
public static readonly KnownHeader LastModified = new KnownHeader("Last-Modified", HttpHeaderType.Content, DateHeaderParser.Parser, null, H2StaticTable.LastModified, H3StaticTable.LastModified);
public static readonly KnownHeader Link = new KnownHeader("Link", H2StaticTable.Link, H3StaticTable.Link);
public static readonly KnownHeader Location = new KnownHeader("Location", HttpHeaderType.Response | HttpHeaderType.NonTrailing, UriHeaderParser.RelativeOrAbsoluteUriParser, null, H2StaticTable.Location, H3StaticTable.Location);
public static readonly KnownHeader MaxForwards = new KnownHeader("Max-Forwards", HttpHeaderType.Request | HttpHeaderType.NonTrailing, Int32NumberHeaderParser.Parser, null, H2StaticTable.MaxForwards);
public static readonly KnownHeader Origin = new KnownHeader("Origin", http3StaticTableIndex: H3StaticTable.Origin);
public static readonly KnownHeader P3P = new KnownHeader("P3P");
public static readonly KnownHeader Pragma = new KnownHeader("Pragma", HttpHeaderType.General | HttpHeaderType.NonTrailing, GenericHeaderParser.MultipleValueNameValueParser, new string[] { "no-cache" });
public static readonly KnownHeader ProxyAuthenticate = new KnownHeader("Proxy-Authenticate", HttpHeaderType.Response | HttpHeaderType.NonTrailing, GenericHeaderParser.MultipleValueAuthenticationParser, null, H2StaticTable.ProxyAuthenticate);
public static readonly KnownHeader ProxyAuthorization = new KnownHeader("Proxy-Authorization", HttpHeaderType.Request | HttpHeaderType.NonTrailing, GenericHeaderParser.SingleValueAuthenticationParser, null, H2StaticTable.ProxyAuthorization);
public static readonly KnownHeader ProxyConnection = new KnownHeader("Proxy-Connection");
public static readonly KnownHeader ProxySupport = new KnownHeader("Proxy-Support");
public static readonly KnownHeader PublicKeyPins = new KnownHeader("Public-Key-Pins");
public static readonly KnownHeader Range = new KnownHeader("Range", HttpHeaderType.Request | HttpHeaderType.NonTrailing, GenericHeaderParser.RangeParser, null, H2StaticTable.Range, H3StaticTable.RangeBytes0ToAll);
public static readonly KnownHeader Referer = new KnownHeader("Referer", HttpHeaderType.Request, UriHeaderParser.RelativeOrAbsoluteUriParser, null, H2StaticTable.Referer, H3StaticTable.Referer); // NB: The spelling-mistake "Referer" for "Referrer" must be matched.
public static readonly KnownHeader ReferrerPolicy = new KnownHeader("Referrer-Policy", HttpHeaderType.Custom, null, new string[] { "strict-origin-when-cross-origin", "origin-when-cross-origin", "strict-origin", "origin", "same-origin", "no-referrer-when-downgrade", "no-referrer", "unsafe-url" });
public static readonly KnownHeader Refresh = new KnownHeader("Refresh", H2StaticTable.Refresh);
public static readonly KnownHeader RetryAfter = new KnownHeader("Retry-After", HttpHeaderType.Response | HttpHeaderType.NonTrailing, GenericHeaderParser.RetryConditionParser, null, H2StaticTable.RetryAfter);
public static readonly KnownHeader SecWebSocketAccept = new KnownHeader("Sec-WebSocket-Accept");
public static readonly KnownHeader SecWebSocketExtensions = new KnownHeader("Sec-WebSocket-Extensions");
public static readonly KnownHeader SecWebSocketKey = new KnownHeader("Sec-WebSocket-Key");
public static readonly KnownHeader SecWebSocketProtocol = new KnownHeader("Sec-WebSocket-Protocol");
public static readonly KnownHeader SecWebSocketVersion = new KnownHeader("Sec-WebSocket-Version");
public static readonly KnownHeader Server = new KnownHeader("Server", HttpHeaderType.Response, ProductInfoHeaderParser.MultipleValueParser, null, H2StaticTable.Server, H3StaticTable.Server);
public static readonly KnownHeader ServerTiming = new KnownHeader("Server-Timing");
public static readonly KnownHeader SetCookie = new KnownHeader("Set-Cookie", HttpHeaderType.Custom | HttpHeaderType.NonTrailing, null, null, H2StaticTable.SetCookie, H3StaticTable.SetCookie);
public static readonly KnownHeader SetCookie2 = new KnownHeader("Set-Cookie2", HttpHeaderType.Custom | HttpHeaderType.NonTrailing, null, null);
public static readonly KnownHeader StrictTransportSecurity = new KnownHeader("Strict-Transport-Security", H2StaticTable.StrictTransportSecurity, H3StaticTable.StrictTransportSecurityMaxAge31536000);
public static readonly KnownHeader TE = new KnownHeader("TE", HttpHeaderType.Request | HttpHeaderType.NonTrailing, TransferCodingHeaderParser.MultipleValueWithQualityParser, new string[] { "trailers", "compress", "deflate", "gzip" });
public static readonly KnownHeader TSV = new KnownHeader("TSV");
public static readonly KnownHeader Trailer = new KnownHeader("Trailer", HttpHeaderType.General | HttpHeaderType.NonTrailing, GenericHeaderParser.TokenListParser);
public static readonly KnownHeader TransferEncoding = new KnownHeader("Transfer-Encoding", HttpHeaderType.General | HttpHeaderType.NonTrailing, TransferCodingHeaderParser.MultipleValueParser, new string[] { "chunked", "compress", "deflate", "gzip", "identity" }, H2StaticTable.TransferEncoding);
public static readonly KnownHeader Upgrade = new KnownHeader("Upgrade", HttpHeaderType.General, GenericHeaderParser.MultipleValueProductParser);
public static readonly KnownHeader UpgradeInsecureRequests = new KnownHeader("Upgrade-Insecure-Requests", HttpHeaderType.Custom, null, new string[] { "1" }, http3StaticTableIndex: H3StaticTable.UpgradeInsecureRequests1);
public static readonly KnownHeader UserAgent = new KnownHeader("User-Agent", HttpHeaderType.Request, ProductInfoHeaderParser.MultipleValueParser, null, H2StaticTable.UserAgent, H3StaticTable.UserAgent);
public static readonly KnownHeader Vary = new KnownHeader("Vary", HttpHeaderType.Response | HttpHeaderType.NonTrailing, GenericHeaderParser.TokenListParser, new string[] { "*" }, H2StaticTable.Vary, H3StaticTable.VaryAcceptEncoding);
public static readonly KnownHeader Via = new KnownHeader("Via", HttpHeaderType.General, GenericHeaderParser.MultipleValueViaParser, null, H2StaticTable.Via);
public static readonly KnownHeader WWWAuthenticate = new KnownHeader("WWW-Authenticate", HttpHeaderType.Response | HttpHeaderType.NonTrailing, GenericHeaderParser.MultipleValueAuthenticationParser, null, H2StaticTable.WwwAuthenticate);
public static readonly KnownHeader Warning = new KnownHeader("Warning", HttpHeaderType.General | HttpHeaderType.NonTrailing, GenericHeaderParser.MultipleValueWarningParser);
public static readonly KnownHeader XAspNetVersion = new KnownHeader("X-AspNet-Version");
public static readonly KnownHeader XCache = new KnownHeader("X-Cache");
public static readonly KnownHeader XContentDuration = new KnownHeader("X-Content-Duration");
public static readonly KnownHeader XContentTypeOptions = new KnownHeader("X-Content-Type-Options", HttpHeaderType.Custom, null, new string[] { "nosniff" }, http3StaticTableIndex: H3StaticTable.XContentTypeOptionsNoSniff);
public static readonly KnownHeader XFrameOptions = new KnownHeader("X-Frame-Options", HttpHeaderType.Custom, null, new string[] { "DENY", "SAMEORIGIN" }, http3StaticTableIndex: H3StaticTable.XFrameOptionsDeny);
public static readonly KnownHeader XMSEdgeRef = new KnownHeader("X-MSEdge-Ref");
public static readonly KnownHeader XPoweredBy = new KnownHeader("X-Powered-By");
public static readonly KnownHeader XRequestID = new KnownHeader("X-Request-ID");
public static readonly KnownHeader XUACompatible = new KnownHeader("X-UA-Compatible");
public static readonly KnownHeader XXssProtection = new KnownHeader("X-XSS-Protection", HttpHeaderType.Custom, null, new string[] { "0", "1", "1; mode=block" });
private static HttpHeaderParser? GetAltSvcHeaderParser() =>
#if TARGET_BROWSER
// Allow for the AltSvcHeaderParser to be trimmed on Browser since Alt-Svc is only for SocketsHttpHandler, which isn't used on Browser.
null;
#else
AltSvcHeaderParser.Parser;
#endif
// Helper interface for making GetCandidate generic over strings, utf8, etc
private interface IHeaderNameAccessor
{
int Length { get; }
char this[int index] { get; }
}
private readonly struct StringAccessor : IHeaderNameAccessor
{
private readonly string _string;
public StringAccessor(string s)
{
_string = s;
}
public int Length => _string.Length;
public char this[int index] => _string[index];
}
// Can't use Span here as it's unsupported.
private readonly unsafe struct BytePtrAccessor : IHeaderNameAccessor
{
private readonly byte* _p;
private readonly int _length;
public BytePtrAccessor(byte* p, int length)
{
_p = p;
_length = length;
}
public int Length => _length;
public char this[int index] => (char)_p[index];
}
/// <summary>
/// Find possible known header match via lookup on length and a distinguishing char for that length.
/// </summary>
/// <remarks>
/// Matching is case-insensitive. Because of this, we do not preserve the case of the original header,
/// whether from the wire or from the user explicitly setting a known header using a header name string.
/// </remarks>
private static KnownHeader? GetCandidate<T>(T key)
where T : struct, IHeaderNameAccessor // Enforce struct for performance
{
// Lookup is performed by first switching on the header name's length, and then switching
// on the most unique position in that length's string.
int length = key.Length;
switch (length)
{
case 2:
return TE; // TE
case 3:
switch (key[0] | 0x20)
{
case 'a': return Age; // [A]ge
case 'p': return P3P; // [P]3P
case 't': return TSV; // [T]SV
case 'v': return Via; // [V]ia
}
break;
case 4:
switch (key[0] | 0x20)
{
case 'd': return Date; // [D]ate
case 'e': return ETag; // [E]Tag
case 'f': return From; // [F]rom
case 'h': return Host; // [H]ost
case 'l': return Link; // [L]ink
case 'v': return Vary; // [V]ary
}
break;
case 5:
switch (key[0] | 0x20)
{
case 'a': return Allow; // [A]llow
case 'r': return Range; // [R]ange
}
break;
case 6:
switch (key[0] | 0x20)
{
case 'a': return Accept; // [A]ccept
case 'c': return Cookie; // [C]ookie
case 'e': return Expect; // [E]xpect
case 'o': return Origin; // [O]rigin
case 'p': return Pragma; // [P]ragma
case 's': return Server; // [S]erver
}
break;
case 7:
switch (key[0] | 0x20)
{
case ':': return PseudoStatus; // [:]status
case 'a': return AltSvc; // [A]lt-Svc
case 'c': return Cookie2; // [C]ookie2
case 'e': return Expires; // [E]xpires
case 'r':
switch (key[3] | 0x20)
{
case 'e': return Referer; // [R]ef[e]rer
case 'r': return Refresh; // [R]ef[r]esh
}
break;
case 't': return Trailer; // [T]railer
case 'u': return Upgrade; // [U]pgrade
case 'w': return Warning; // [W]arning
case 'x': return XCache; // [X]-Cache
}
break;
case 8:
switch (key[3] | 0x20)
{
case '-': return AltUsed; // Alt[-]Used
case 'a': return Location; // Loc[a]tion
case 'm': return IfMatch; // If-[M]atch
case 'r': return IfRange; // If-[R]ange
}
break;
case 9:
return ExpectCT; // Expect-CT
case 10:
switch (key[0] | 0x20)
{
case 'c': return Connection; // [C]onnection
case 'k': return KeepAlive; // [K]eep-Alive
case 's': return SetCookie; // [S]et-Cookie
case 'u': return UserAgent; // [U]ser-Agent
}
break;
case 11:
switch (key[0] | 0x20)
{
case 'c': return ContentMD5; // [C]ontent-MD5
case 'g': return GrpcStatus; // [g]rpc-status
case 'r': return RetryAfter; // [R]etry-After
case 's': return SetCookie2; // [S]et-Cookie2
}
break;
case 12:
switch (key[5] | 0x20)
{
case 'd': return XMSEdgeRef; // X-MSE[d]ge-Ref
case 'e': return XPoweredBy; // X-Pow[e]red-By
case 'm': return GrpcMessage; // grpc-[m]essage
case 'n': return ContentType; // Conte[n]t-Type
case 'o': return MaxForwards; // Max-F[o]rwards
case 't': return AcceptPatch; // Accep[t]-Patch
case 'u': return XRequestID; // X-Req[u]est-ID
}
break;
case 13:
switch (key[12] | 0x20)
{
case 'd': return LastModified; // Last-Modifie[d]
case 'e': return ContentRange; // Content-Rang[e]
case 'g':
switch (key[0] | 0x20)
{
case 's': return ServerTiming; // [S]erver-Timin[g]
case 'g': return GrpcEncoding; // [g]rpc-encodin[g]
}
break;
case 'h': return IfNoneMatch; // If-None-Matc[h]
case 'l': return CacheControl; // Cache-Contro[l]
case 'n': return Authorization; // Authorizatio[n]
case 's': return AcceptRanges; // Accept-Range[s]
case 't': return ProxySupport; // Proxy-Suppor[t]
}
break;
case 14:
switch (key[0] | 0x20)
{
case 'a': return AcceptCharset; // [A]ccept-Charset
case 'c': return ContentLength; // [C]ontent-Length
}
break;
case 15:
switch (key[7] | 0x20)
{
case '-': return XFrameOptions; // X-Frame[-]Options
case 'e': return AcceptEncoding; // Accept-[E]ncoding
case 'k': return PublicKeyPins; // Public-[K]ey-Pins
case 'l': return AcceptLanguage; // Accept-[L]anguage
case 'm': return XUACompatible; // X-UA-Co[m]patible
case 'r': return ReferrerPolicy; // Referre[r]-Policy
}
break;
case 16:
switch (key[11] | 0x20)
{
case 'a': return ContentLocation; // Content-Loc[a]tion
case 'c':
switch (key[0] | 0x20)
{
case 'p': return ProxyConnection; // [P]roxy-Conne[c]tion
case 'x': return XXssProtection; // [X]-XSS-Prote[c]tion
}
break;
case 'g': return ContentLanguage; // Content-Lan[g]uage
case 'i': return WWWAuthenticate; // WWW-Authent[i]cate
case 'o': return ContentEncoding; // Content-Enc[o]ding
case 'r': return XAspNetVersion; // X-AspNet-Ve[r]sion
}
break;
case 17:
switch (key[0] | 0x20)
{
case 'i': return IfModifiedSince; // [I]f-Modified-Since
case 's': return SecWebSocketKey; // [S]ec-WebSocket-Key
case 't': return TransferEncoding; // [T]ransfer-Encoding
}
break;
case 18:
switch (key[0] | 0x20)
{
case 'p': return ProxyAuthenticate; // [P]roxy-Authenticate
case 'x': return XContentDuration; // [X]-Content-Duration
}
break;
case 19:
switch (key[0] | 0x20)
{
case 'c': return ContentDisposition; // [C]ontent-Disposition
case 'i': return IfUnmodifiedSince; // [I]f-Unmodified-Since
case 'p': return ProxyAuthorization; // [P]roxy-Authorization
}
break;
case 20:
return SecWebSocketAccept; // Sec-WebSocket-Accept
case 21:
return SecWebSocketVersion; // Sec-WebSocket-Version
case 22:
switch (key[0] | 0x20)
{
case 'a': return AccessControlMaxAge; // [A]ccess-Control-Max-Age
case 's': return SecWebSocketProtocol; // [S]ec-WebSocket-Protocol
case 'x': return XContentTypeOptions; // [X]-Content-Type-Options
}
break;
case 23:
return ContentSecurityPolicy; // Content-Security-Policy
case 24:
return SecWebSocketExtensions; // Sec-WebSocket-Extensions
case 25:
switch (key[0] | 0x20)
{
case 's': return StrictTransportSecurity; // [S]trict-Transport-Security
case 'u': return UpgradeInsecureRequests; // [U]pgrade-Insecure-Requests
}
break;
case 27:
return AccessControlAllowOrigin; // Access-Control-Allow-Origin
case 28:
switch (key[21] | 0x20)
{
case 'h': return AccessControlAllowHeaders; // Access-Control-Allow-[H]eaders
case 'm': return AccessControlAllowMethods; // Access-Control-Allow-[M]ethods
}
break;
case 29:
return AccessControlExposeHeaders; // Access-Control-Expose-Headers
case 32:
return AccessControlAllowCredentials; // Access-Control-Allow-Credentials
}
return null;
}
internal static KnownHeader? TryGetKnownHeader(string name)
{
KnownHeader? candidate = GetCandidate(new StringAccessor(name));
if (candidate != null && StringComparer.OrdinalIgnoreCase.Equals(name, candidate.Name))
{
return candidate;
}
return null;
}
internal static unsafe KnownHeader? TryGetKnownHeader(ReadOnlySpan<byte> name)
{
fixed (byte* p = &MemoryMarshal.GetReference(name))
{
KnownHeader? candidate = GetCandidate(new BytePtrAccessor(p, name.Length));
if (candidate != null && ByteArrayHelpers.EqualsOrdinalAsciiIgnoreCase(candidate.Name, name))
{
return candidate;
}
}
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.Net.Http.HPack;
using System.Net.Http.QPack;
using System.Runtime.InteropServices;
namespace System.Net.Http.Headers
{
internal static class KnownHeaders
{
// If you add a new entry here, you need to add it to TryGetKnownHeader below as well.
public static readonly KnownHeader PseudoStatus = new KnownHeader(":status", HttpHeaderType.Response, parser: null);
public static readonly KnownHeader Accept = new KnownHeader("Accept", HttpHeaderType.Request, MediaTypeHeaderParser.MultipleValuesParser, null, H2StaticTable.Accept, H3StaticTable.AcceptAny);
public static readonly KnownHeader AcceptCharset = new KnownHeader("Accept-Charset", HttpHeaderType.Request, GenericHeaderParser.MultipleValueStringWithQualityParser, null, H2StaticTable.AcceptCharset);
public static readonly KnownHeader AcceptEncoding = new KnownHeader("Accept-Encoding", HttpHeaderType.Request, GenericHeaderParser.MultipleValueStringWithQualityParser, null, H2StaticTable.AcceptEncoding, H3StaticTable.AcceptEncodingGzipDeflateBr);
public static readonly KnownHeader AcceptLanguage = new KnownHeader("Accept-Language", HttpHeaderType.Request, GenericHeaderParser.MultipleValueStringWithQualityParser, null, H2StaticTable.AcceptLanguage, H3StaticTable.AcceptLanguage);
public static readonly KnownHeader AcceptPatch = new KnownHeader("Accept-Patch");
public static readonly KnownHeader AcceptRanges = new KnownHeader("Accept-Ranges", HttpHeaderType.Response, GenericHeaderParser.TokenListParser, null, H2StaticTable.AcceptRanges, H3StaticTable.AcceptRangesBytes);
public static readonly KnownHeader AccessControlAllowCredentials = new KnownHeader("Access-Control-Allow-Credentials", HttpHeaderType.Response, parser: null, new string[] { "true" }, http3StaticTableIndex: H3StaticTable.AccessControlAllowCredentials);
public static readonly KnownHeader AccessControlAllowHeaders = new KnownHeader("Access-Control-Allow-Headers", HttpHeaderType.Response, parser: null, new string[] { "*" }, http3StaticTableIndex: H3StaticTable.AccessControlAllowHeadersCacheControl);
public static readonly KnownHeader AccessControlAllowMethods = new KnownHeader("Access-Control-Allow-Methods", HttpHeaderType.Response, parser: null, new string[] { "*" }, http3StaticTableIndex: H3StaticTable.AccessControlAllowMethodsGet);
public static readonly KnownHeader AccessControlAllowOrigin = new KnownHeader("Access-Control-Allow-Origin", HttpHeaderType.Response, parser: null, new string[] { "*", "null" }, H2StaticTable.AccessControlAllowOrigin, H3StaticTable.AccessControlAllowOriginAny);
public static readonly KnownHeader AccessControlExposeHeaders = new KnownHeader("Access-Control-Expose-Headers", HttpHeaderType.Response, parser: null, new string[] { "*" }, H3StaticTable.AccessControlExposeHeadersContentLength);
public static readonly KnownHeader AccessControlMaxAge = new KnownHeader("Access-Control-Max-Age");
public static readonly KnownHeader Age = new KnownHeader("Age", HttpHeaderType.Response | HttpHeaderType.NonTrailing, TimeSpanHeaderParser.Parser, null, H2StaticTable.Age, H3StaticTable.Age0);
public static readonly KnownHeader Allow = new KnownHeader("Allow", HttpHeaderType.Content, GenericHeaderParser.TokenListParser, null, H2StaticTable.Allow);
public static readonly KnownHeader AltSvc = new KnownHeader("Alt-Svc", HttpHeaderType.Response, GetAltSvcHeaderParser(), http3StaticTableIndex: H3StaticTable.AltSvcClear);
public static readonly KnownHeader AltUsed = new KnownHeader("Alt-Used", HttpHeaderType.Request, parser: null);
public static readonly KnownHeader Authorization = new KnownHeader("Authorization", HttpHeaderType.Request | HttpHeaderType.NonTrailing, GenericHeaderParser.SingleValueAuthenticationParser, null, H2StaticTable.Authorization, H3StaticTable.Authorization);
public static readonly KnownHeader CacheControl = new KnownHeader("Cache-Control", HttpHeaderType.General | HttpHeaderType.NonTrailing, CacheControlHeaderParser.Parser, new string[] { "must-revalidate", "no-cache", "no-store", "no-transform", "private", "proxy-revalidate", "public" }, H2StaticTable.CacheControl, H3StaticTable.CacheControlMaxAge0);
public static readonly KnownHeader Connection = new KnownHeader("Connection", HttpHeaderType.General, GenericHeaderParser.TokenListParser, new string[] { "close" });
public static readonly KnownHeader ContentDisposition = new KnownHeader("Content-Disposition", HttpHeaderType.Content | HttpHeaderType.NonTrailing, GenericHeaderParser.ContentDispositionParser, new string[] { "inline", "attachment" }, H2StaticTable.ContentDisposition, H3StaticTable.ContentDisposition);
public static readonly KnownHeader ContentEncoding = new KnownHeader("Content-Encoding", HttpHeaderType.Content | HttpHeaderType.NonTrailing, GenericHeaderParser.TokenListParser, new string[] { "gzip", "deflate", "br", "compress", "identity" }, H2StaticTable.ContentEncoding, H3StaticTable.ContentEncodingBr);
public static readonly KnownHeader ContentLanguage = new KnownHeader("Content-Language", HttpHeaderType.Content, GenericHeaderParser.TokenListParser, null, H2StaticTable.ContentLanguage);
public static readonly KnownHeader ContentLength = new KnownHeader("Content-Length", HttpHeaderType.Content | HttpHeaderType.NonTrailing, Int64NumberHeaderParser.Parser, null, H2StaticTable.ContentLength, H3StaticTable.ContentLength0);
public static readonly KnownHeader ContentLocation = new KnownHeader("Content-Location", HttpHeaderType.Content | HttpHeaderType.NonTrailing, UriHeaderParser.RelativeOrAbsoluteUriParser, null, H2StaticTable.ContentLocation);
public static readonly KnownHeader ContentMD5 = new KnownHeader("Content-MD5", HttpHeaderType.Content, ByteArrayHeaderParser.Parser);
public static readonly KnownHeader ContentRange = new KnownHeader("Content-Range", HttpHeaderType.Content | HttpHeaderType.NonTrailing, GenericHeaderParser.ContentRangeParser, null, H2StaticTable.ContentRange);
public static readonly KnownHeader ContentSecurityPolicy = new KnownHeader("Content-Security-Policy", http3StaticTableIndex: H3StaticTable.ContentSecurityPolicyAllNone);
public static readonly KnownHeader ContentType = new KnownHeader("Content-Type", HttpHeaderType.Content | HttpHeaderType.NonTrailing, MediaTypeHeaderParser.SingleValueParser, null, H2StaticTable.ContentType, H3StaticTable.ContentTypeApplicationDnsMessage);
public static readonly KnownHeader Cookie = new KnownHeader("Cookie", H2StaticTable.Cookie, H3StaticTable.Cookie);
public static readonly KnownHeader Cookie2 = new KnownHeader("Cookie2");
public static readonly KnownHeader Date = new KnownHeader("Date", HttpHeaderType.General | HttpHeaderType.NonTrailing, DateHeaderParser.Parser, null, H2StaticTable.Date, H3StaticTable.Date);
public static readonly KnownHeader ETag = new KnownHeader("ETag", HttpHeaderType.Response, GenericHeaderParser.SingleValueEntityTagParser, null, H2StaticTable.ETag, H3StaticTable.ETag);
public static readonly KnownHeader Expect = new KnownHeader("Expect", HttpHeaderType.Request | HttpHeaderType.NonTrailing, GenericHeaderParser.MultipleValueNameValueWithParametersParser, new string[] { "100-continue" }, H2StaticTable.Expect);
public static readonly KnownHeader ExpectCT = new KnownHeader("Expect-CT");
public static readonly KnownHeader Expires = new KnownHeader("Expires", HttpHeaderType.Content | HttpHeaderType.NonTrailing, DateHeaderParser.Parser, null, H2StaticTable.Expires);
public static readonly KnownHeader From = new KnownHeader("From", HttpHeaderType.Request, GenericHeaderParser.SingleValueParserWithoutValidation, null, H2StaticTable.From);
public static readonly KnownHeader GrpcEncoding = new KnownHeader("grpc-encoding", HttpHeaderType.Custom, null, new string[] { "identity", "gzip", "deflate" });
public static readonly KnownHeader GrpcMessage = new KnownHeader("grpc-message");
public static readonly KnownHeader GrpcStatus = new KnownHeader("grpc-status", HttpHeaderType.Custom, null, new string[] { "0" });
public static readonly KnownHeader Host = new KnownHeader("Host", HttpHeaderType.Request | HttpHeaderType.NonTrailing, GenericHeaderParser.HostParser, null, H2StaticTable.Host);
public static readonly KnownHeader IfMatch = new KnownHeader("If-Match", HttpHeaderType.Request | HttpHeaderType.NonTrailing, GenericHeaderParser.MultipleValueEntityTagParser, null, H2StaticTable.IfMatch);
public static readonly KnownHeader IfModifiedSince = new KnownHeader("If-Modified-Since", HttpHeaderType.Request | HttpHeaderType.NonTrailing, DateHeaderParser.Parser, null, H2StaticTable.IfModifiedSince, H3StaticTable.IfModifiedSince);
public static readonly KnownHeader IfNoneMatch = new KnownHeader("If-None-Match", HttpHeaderType.Request | HttpHeaderType.NonTrailing, GenericHeaderParser.MultipleValueEntityTagParser, null, H2StaticTable.IfNoneMatch, H3StaticTable.IfNoneMatch);
public static readonly KnownHeader IfRange = new KnownHeader("If-Range", HttpHeaderType.Request | HttpHeaderType.NonTrailing, GenericHeaderParser.RangeConditionParser, null, H2StaticTable.IfRange, H3StaticTable.IfRange);
public static readonly KnownHeader IfUnmodifiedSince = new KnownHeader("If-Unmodified-Since", HttpHeaderType.Request | HttpHeaderType.NonTrailing, DateHeaderParser.Parser, null, H2StaticTable.IfUnmodifiedSince);
public static readonly KnownHeader KeepAlive = new KnownHeader("Keep-Alive");
public static readonly KnownHeader LastModified = new KnownHeader("Last-Modified", HttpHeaderType.Content, DateHeaderParser.Parser, null, H2StaticTable.LastModified, H3StaticTable.LastModified);
public static readonly KnownHeader Link = new KnownHeader("Link", H2StaticTable.Link, H3StaticTable.Link);
public static readonly KnownHeader Location = new KnownHeader("Location", HttpHeaderType.Response | HttpHeaderType.NonTrailing, UriHeaderParser.RelativeOrAbsoluteUriParser, null, H2StaticTable.Location, H3StaticTable.Location);
public static readonly KnownHeader MaxForwards = new KnownHeader("Max-Forwards", HttpHeaderType.Request | HttpHeaderType.NonTrailing, Int32NumberHeaderParser.Parser, null, H2StaticTable.MaxForwards);
public static readonly KnownHeader Origin = new KnownHeader("Origin", http3StaticTableIndex: H3StaticTable.Origin);
public static readonly KnownHeader P3P = new KnownHeader("P3P");
public static readonly KnownHeader Pragma = new KnownHeader("Pragma", HttpHeaderType.General | HttpHeaderType.NonTrailing, GenericHeaderParser.MultipleValueNameValueParser, new string[] { "no-cache" });
public static readonly KnownHeader ProxyAuthenticate = new KnownHeader("Proxy-Authenticate", HttpHeaderType.Response | HttpHeaderType.NonTrailing, GenericHeaderParser.MultipleValueAuthenticationParser, null, H2StaticTable.ProxyAuthenticate);
public static readonly KnownHeader ProxyAuthorization = new KnownHeader("Proxy-Authorization", HttpHeaderType.Request | HttpHeaderType.NonTrailing, GenericHeaderParser.SingleValueAuthenticationParser, null, H2StaticTable.ProxyAuthorization);
public static readonly KnownHeader ProxyConnection = new KnownHeader("Proxy-Connection");
public static readonly KnownHeader ProxySupport = new KnownHeader("Proxy-Support");
public static readonly KnownHeader PublicKeyPins = new KnownHeader("Public-Key-Pins");
public static readonly KnownHeader Range = new KnownHeader("Range", HttpHeaderType.Request | HttpHeaderType.NonTrailing, GenericHeaderParser.RangeParser, null, H2StaticTable.Range, H3StaticTable.RangeBytes0ToAll);
public static readonly KnownHeader Referer = new KnownHeader("Referer", HttpHeaderType.Request, UriHeaderParser.RelativeOrAbsoluteUriParser, null, H2StaticTable.Referer, H3StaticTable.Referer); // NB: The spelling-mistake "Referer" for "Referrer" must be matched.
public static readonly KnownHeader ReferrerPolicy = new KnownHeader("Referrer-Policy", HttpHeaderType.Custom, null, new string[] { "strict-origin-when-cross-origin", "origin-when-cross-origin", "strict-origin", "origin", "same-origin", "no-referrer-when-downgrade", "no-referrer", "unsafe-url" });
public static readonly KnownHeader Refresh = new KnownHeader("Refresh", H2StaticTable.Refresh);
public static readonly KnownHeader RetryAfter = new KnownHeader("Retry-After", HttpHeaderType.Response | HttpHeaderType.NonTrailing, GenericHeaderParser.RetryConditionParser, null, H2StaticTable.RetryAfter);
public static readonly KnownHeader SecWebSocketAccept = new KnownHeader("Sec-WebSocket-Accept");
public static readonly KnownHeader SecWebSocketExtensions = new KnownHeader("Sec-WebSocket-Extensions");
public static readonly KnownHeader SecWebSocketKey = new KnownHeader("Sec-WebSocket-Key");
public static readonly KnownHeader SecWebSocketProtocol = new KnownHeader("Sec-WebSocket-Protocol");
public static readonly KnownHeader SecWebSocketVersion = new KnownHeader("Sec-WebSocket-Version");
public static readonly KnownHeader Server = new KnownHeader("Server", HttpHeaderType.Response, ProductInfoHeaderParser.MultipleValueParser, null, H2StaticTable.Server, H3StaticTable.Server);
public static readonly KnownHeader ServerTiming = new KnownHeader("Server-Timing");
public static readonly KnownHeader SetCookie = new KnownHeader("Set-Cookie", HttpHeaderType.Custom | HttpHeaderType.NonTrailing, null, null, H2StaticTable.SetCookie, H3StaticTable.SetCookie);
public static readonly KnownHeader SetCookie2 = new KnownHeader("Set-Cookie2", HttpHeaderType.Custom | HttpHeaderType.NonTrailing, null, null);
public static readonly KnownHeader StrictTransportSecurity = new KnownHeader("Strict-Transport-Security", H2StaticTable.StrictTransportSecurity, H3StaticTable.StrictTransportSecurityMaxAge31536000);
public static readonly KnownHeader TE = new KnownHeader("TE", HttpHeaderType.Request | HttpHeaderType.NonTrailing, TransferCodingHeaderParser.MultipleValueWithQualityParser, new string[] { "trailers", "compress", "deflate", "gzip" });
public static readonly KnownHeader TSV = new KnownHeader("TSV");
public static readonly KnownHeader Trailer = new KnownHeader("Trailer", HttpHeaderType.General | HttpHeaderType.NonTrailing, GenericHeaderParser.TokenListParser);
public static readonly KnownHeader TransferEncoding = new KnownHeader("Transfer-Encoding", HttpHeaderType.General | HttpHeaderType.NonTrailing, TransferCodingHeaderParser.MultipleValueParser, new string[] { "chunked", "compress", "deflate", "gzip", "identity" }, H2StaticTable.TransferEncoding);
public static readonly KnownHeader Upgrade = new KnownHeader("Upgrade", HttpHeaderType.General, GenericHeaderParser.MultipleValueProductParser);
public static readonly KnownHeader UpgradeInsecureRequests = new KnownHeader("Upgrade-Insecure-Requests", HttpHeaderType.Custom, null, new string[] { "1" }, http3StaticTableIndex: H3StaticTable.UpgradeInsecureRequests1);
public static readonly KnownHeader UserAgent = new KnownHeader("User-Agent", HttpHeaderType.Request, ProductInfoHeaderParser.MultipleValueParser, null, H2StaticTable.UserAgent, H3StaticTable.UserAgent);
public static readonly KnownHeader Vary = new KnownHeader("Vary", HttpHeaderType.Response | HttpHeaderType.NonTrailing, GenericHeaderParser.TokenListParser, new string[] { "*" }, H2StaticTable.Vary, H3StaticTable.VaryAcceptEncoding);
public static readonly KnownHeader Via = new KnownHeader("Via", HttpHeaderType.General, GenericHeaderParser.MultipleValueViaParser, null, H2StaticTable.Via);
public static readonly KnownHeader WWWAuthenticate = new KnownHeader("WWW-Authenticate", HttpHeaderType.Response | HttpHeaderType.NonTrailing, GenericHeaderParser.MultipleValueAuthenticationParser, null, H2StaticTable.WwwAuthenticate);
public static readonly KnownHeader Warning = new KnownHeader("Warning", HttpHeaderType.General | HttpHeaderType.NonTrailing, GenericHeaderParser.MultipleValueWarningParser);
public static readonly KnownHeader XAspNetVersion = new KnownHeader("X-AspNet-Version");
public static readonly KnownHeader XCache = new KnownHeader("X-Cache");
public static readonly KnownHeader XContentDuration = new KnownHeader("X-Content-Duration");
public static readonly KnownHeader XContentTypeOptions = new KnownHeader("X-Content-Type-Options", HttpHeaderType.Custom, null, new string[] { "nosniff" }, http3StaticTableIndex: H3StaticTable.XContentTypeOptionsNoSniff);
public static readonly KnownHeader XFrameOptions = new KnownHeader("X-Frame-Options", HttpHeaderType.Custom, null, new string[] { "DENY", "SAMEORIGIN" }, http3StaticTableIndex: H3StaticTable.XFrameOptionsDeny);
public static readonly KnownHeader XMSEdgeRef = new KnownHeader("X-MSEdge-Ref");
public static readonly KnownHeader XPoweredBy = new KnownHeader("X-Powered-By");
public static readonly KnownHeader XRequestID = new KnownHeader("X-Request-ID");
public static readonly KnownHeader XUACompatible = new KnownHeader("X-UA-Compatible");
public static readonly KnownHeader XXssProtection = new KnownHeader("X-XSS-Protection", HttpHeaderType.Custom, null, new string[] { "0", "1", "1; mode=block" });
private static HttpHeaderParser? GetAltSvcHeaderParser() =>
#if TARGET_BROWSER
// Allow for the AltSvcHeaderParser to be trimmed on Browser since Alt-Svc is only for SocketsHttpHandler, which isn't used on Browser.
null;
#else
AltSvcHeaderParser.Parser;
#endif
// Helper interface for making GetCandidate generic over strings, utf8, etc
private interface IHeaderNameAccessor
{
int Length { get; }
char this[int index] { get; }
}
private readonly struct StringAccessor : IHeaderNameAccessor
{
private readonly string _string;
public StringAccessor(string s)
{
_string = s;
}
public int Length => _string.Length;
public char this[int index] => _string[index];
}
// Can't use Span here as it's unsupported.
private readonly unsafe struct BytePtrAccessor : IHeaderNameAccessor
{
private readonly byte* _p;
private readonly int _length;
public BytePtrAccessor(byte* p, int length)
{
_p = p;
_length = length;
}
public int Length => _length;
public char this[int index] => (char)_p[index];
}
/// <summary>
/// Find possible known header match via lookup on length and a distinguishing char for that length.
/// </summary>
/// <remarks>
/// Matching is case-insensitive. Because of this, we do not preserve the case of the original header,
/// whether from the wire or from the user explicitly setting a known header using a header name string.
/// </remarks>
private static KnownHeader? GetCandidate<T>(T key)
where T : struct, IHeaderNameAccessor // Enforce struct for performance
{
// Lookup is performed by first switching on the header name's length, and then switching
// on the most unique position in that length's string.
int length = key.Length;
switch (length)
{
case 2:
return TE; // TE
case 3:
switch (key[0] | 0x20)
{
case 'a': return Age; // [A]ge
case 'p': return P3P; // [P]3P
case 't': return TSV; // [T]SV
case 'v': return Via; // [V]ia
}
break;
case 4:
switch (key[0] | 0x20)
{
case 'd': return Date; // [D]ate
case 'e': return ETag; // [E]Tag
case 'f': return From; // [F]rom
case 'h': return Host; // [H]ost
case 'l': return Link; // [L]ink
case 'v': return Vary; // [V]ary
}
break;
case 5:
switch (key[0] | 0x20)
{
case 'a': return Allow; // [A]llow
case 'r': return Range; // [R]ange
}
break;
case 6:
switch (key[0] | 0x20)
{
case 'a': return Accept; // [A]ccept
case 'c': return Cookie; // [C]ookie
case 'e': return Expect; // [E]xpect
case 'o': return Origin; // [O]rigin
case 'p': return Pragma; // [P]ragma
case 's': return Server; // [S]erver
}
break;
case 7:
switch (key[0] | 0x20)
{
case ':': return PseudoStatus; // [:]status
case 'a': return AltSvc; // [A]lt-Svc
case 'c': return Cookie2; // [C]ookie2
case 'e': return Expires; // [E]xpires
case 'r':
switch (key[3] | 0x20)
{
case 'e': return Referer; // [R]ef[e]rer
case 'r': return Refresh; // [R]ef[r]esh
}
break;
case 't': return Trailer; // [T]railer
case 'u': return Upgrade; // [U]pgrade
case 'w': return Warning; // [W]arning
case 'x': return XCache; // [X]-Cache
}
break;
case 8:
switch (key[3] | 0x20)
{
case '-': return AltUsed; // Alt[-]Used
case 'a': return Location; // Loc[a]tion
case 'm': return IfMatch; // If-[M]atch
case 'r': return IfRange; // If-[R]ange
}
break;
case 9:
return ExpectCT; // Expect-CT
case 10:
switch (key[0] | 0x20)
{
case 'c': return Connection; // [C]onnection
case 'k': return KeepAlive; // [K]eep-Alive
case 's': return SetCookie; // [S]et-Cookie
case 'u': return UserAgent; // [U]ser-Agent
}
break;
case 11:
switch (key[0] | 0x20)
{
case 'c': return ContentMD5; // [C]ontent-MD5
case 'g': return GrpcStatus; // [g]rpc-status
case 'r': return RetryAfter; // [R]etry-After
case 's': return SetCookie2; // [S]et-Cookie2
}
break;
case 12:
switch (key[5] | 0x20)
{
case 'd': return XMSEdgeRef; // X-MSE[d]ge-Ref
case 'e': return XPoweredBy; // X-Pow[e]red-By
case 'm': return GrpcMessage; // grpc-[m]essage
case 'n': return ContentType; // Conte[n]t-Type
case 'o': return MaxForwards; // Max-F[o]rwards
case 't': return AcceptPatch; // Accep[t]-Patch
case 'u': return XRequestID; // X-Req[u]est-ID
}
break;
case 13:
switch (key[12] | 0x20)
{
case 'd': return LastModified; // Last-Modifie[d]
case 'e': return ContentRange; // Content-Rang[e]
case 'g':
switch (key[0] | 0x20)
{
case 's': return ServerTiming; // [S]erver-Timin[g]
case 'g': return GrpcEncoding; // [g]rpc-encodin[g]
}
break;
case 'h': return IfNoneMatch; // If-None-Matc[h]
case 'l': return CacheControl; // Cache-Contro[l]
case 'n': return Authorization; // Authorizatio[n]
case 's': return AcceptRanges; // Accept-Range[s]
case 't': return ProxySupport; // Proxy-Suppor[t]
}
break;
case 14:
switch (key[0] | 0x20)
{
case 'a': return AcceptCharset; // [A]ccept-Charset
case 'c': return ContentLength; // [C]ontent-Length
}
break;
case 15:
switch (key[7] | 0x20)
{
case '-': return XFrameOptions; // X-Frame[-]Options
case 'e': return AcceptEncoding; // Accept-[E]ncoding
case 'k': return PublicKeyPins; // Public-[K]ey-Pins
case 'l': return AcceptLanguage; // Accept-[L]anguage
case 'm': return XUACompatible; // X-UA-Co[m]patible
case 'r': return ReferrerPolicy; // Referre[r]-Policy
}
break;
case 16:
switch (key[11] | 0x20)
{
case 'a': return ContentLocation; // Content-Loc[a]tion
case 'c':
switch (key[0] | 0x20)
{
case 'p': return ProxyConnection; // [P]roxy-Conne[c]tion
case 'x': return XXssProtection; // [X]-XSS-Prote[c]tion
}
break;
case 'g': return ContentLanguage; // Content-Lan[g]uage
case 'i': return WWWAuthenticate; // WWW-Authent[i]cate
case 'o': return ContentEncoding; // Content-Enc[o]ding
case 'r': return XAspNetVersion; // X-AspNet-Ve[r]sion
}
break;
case 17:
switch (key[0] | 0x20)
{
case 'i': return IfModifiedSince; // [I]f-Modified-Since
case 's': return SecWebSocketKey; // [S]ec-WebSocket-Key
case 't': return TransferEncoding; // [T]ransfer-Encoding
}
break;
case 18:
switch (key[0] | 0x20)
{
case 'p': return ProxyAuthenticate; // [P]roxy-Authenticate
case 'x': return XContentDuration; // [X]-Content-Duration
}
break;
case 19:
switch (key[0] | 0x20)
{
case 'c': return ContentDisposition; // [C]ontent-Disposition
case 'i': return IfUnmodifiedSince; // [I]f-Unmodified-Since
case 'p': return ProxyAuthorization; // [P]roxy-Authorization
}
break;
case 20:
return SecWebSocketAccept; // Sec-WebSocket-Accept
case 21:
return SecWebSocketVersion; // Sec-WebSocket-Version
case 22:
switch (key[0] | 0x20)
{
case 'a': return AccessControlMaxAge; // [A]ccess-Control-Max-Age
case 's': return SecWebSocketProtocol; // [S]ec-WebSocket-Protocol
case 'x': return XContentTypeOptions; // [X]-Content-Type-Options
}
break;
case 23:
return ContentSecurityPolicy; // Content-Security-Policy
case 24:
return SecWebSocketExtensions; // Sec-WebSocket-Extensions
case 25:
switch (key[0] | 0x20)
{
case 's': return StrictTransportSecurity; // [S]trict-Transport-Security
case 'u': return UpgradeInsecureRequests; // [U]pgrade-Insecure-Requests
}
break;
case 27:
return AccessControlAllowOrigin; // Access-Control-Allow-Origin
case 28:
switch (key[21] | 0x20)
{
case 'h': return AccessControlAllowHeaders; // Access-Control-Allow-[H]eaders
case 'm': return AccessControlAllowMethods; // Access-Control-Allow-[M]ethods
}
break;
case 29:
return AccessControlExposeHeaders; // Access-Control-Expose-Headers
case 32:
return AccessControlAllowCredentials; // Access-Control-Allow-Credentials
}
return null;
}
internal static KnownHeader? TryGetKnownHeader(string name)
{
KnownHeader? candidate = GetCandidate(new StringAccessor(name));
if (candidate != null && StringComparer.OrdinalIgnoreCase.Equals(name, candidate.Name))
{
return candidate;
}
return null;
}
internal static unsafe KnownHeader? TryGetKnownHeader(ReadOnlySpan<byte> name)
{
fixed (byte* p = &MemoryMarshal.GetReference(name))
{
KnownHeader? candidate = GetCandidate(new BytePtrAccessor(p, name.Length));
if (candidate != null && ByteArrayHelpers.EqualsOrdinalAsciiIgnoreCase(candidate.Name, name))
{
return candidate;
}
}
return null;
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Private.CoreLib/src/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Boolean.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.Binary;
namespace System.Buffers.Text
{
public static partial class Utf8Formatter
{
/// <summary>
/// Formats a Boolean as a UTF8 string.
/// </summary>
/// <param name="value">Value to format</param>
/// <param name="destination">Buffer to write the UTF8-formatted value to</param>
/// <param name="bytesWritten">Receives the length of the formatted text in bytes</param>
/// <param name="format">The standard format to use</param>
/// <returns>
/// true for success. "bytesWritten" contains the length of the formatted text in bytes.
/// false if buffer was too short. Iteratively increase the size of the buffer and retry until it succeeds.
/// </returns>
/// <remarks>
/// Formats supported:
/// G (default) True/False
/// l true/false
/// </remarks>
/// <exceptions>
/// <cref>System.FormatException</cref> if the format is not valid for this data type.
/// </exceptions>
public static bool TryFormat(bool value, Span<byte> destination, out int bytesWritten, StandardFormat format = default)
{
char symbol = FormattingHelpers.GetSymbolOrDefault(format, 'G');
if (value)
{
if (symbol == 'G')
{
// By having each branch perform its own call to TryWriteUInt32BigEndian, we ensure that a
// constant value is passed to this routine, which means the compiler can reverse endianness
// at compile time instead of runtime if necessary.
const uint TrueValueUppercase = ('T' << 24) + ('r' << 16) + ('u' << 8) + ('e' << 0);
if (!BinaryPrimitives.TryWriteUInt32BigEndian(destination, TrueValueUppercase))
{
goto BufferTooSmall;
}
}
else if (symbol == 'l')
{
const uint TrueValueLowercase = ('t' << 24) + ('r' << 16) + ('u' << 8) + ('e' << 0);
if (!BinaryPrimitives.TryWriteUInt32BigEndian(destination, TrueValueLowercase))
{
goto BufferTooSmall;
}
}
else
{
goto BadFormat;
}
bytesWritten = 4;
return true;
}
else
{
if (symbol == 'G')
{
// This check can't be performed earlier because we need to throw if an invalid symbol is
// provided, even if the buffer is too small.
if ((uint)4 >= (uint)destination.Length)
{
goto BufferTooSmall;
}
const uint FalsValueUppercase = ('F' << 24) + ('a' << 16) + ('l' << 8) + ('s' << 0);
BinaryPrimitives.WriteUInt32BigEndian(destination, FalsValueUppercase);
}
else if (symbol == 'l')
{
if ((uint)4 >= (uint)destination.Length)
{
goto BufferTooSmall;
}
const uint FalsValueLowercase = ('f' << 24) + ('a' << 16) + ('l' << 8) + ('s' << 0);
BinaryPrimitives.WriteUInt32BigEndian(destination, FalsValueLowercase);
}
else
{
goto BadFormat;
}
destination[4] = (byte)'e';
bytesWritten = 5;
return true;
}
BufferTooSmall:
bytesWritten = 0;
return false;
BadFormat:
return FormattingHelpers.TryFormatThrowFormatException(out bytesWritten);
}
}
}
|
// 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.Binary;
namespace System.Buffers.Text
{
public static partial class Utf8Formatter
{
/// <summary>
/// Formats a Boolean as a UTF8 string.
/// </summary>
/// <param name="value">Value to format</param>
/// <param name="destination">Buffer to write the UTF8-formatted value to</param>
/// <param name="bytesWritten">Receives the length of the formatted text in bytes</param>
/// <param name="format">The standard format to use</param>
/// <returns>
/// true for success. "bytesWritten" contains the length of the formatted text in bytes.
/// false if buffer was too short. Iteratively increase the size of the buffer and retry until it succeeds.
/// </returns>
/// <remarks>
/// Formats supported:
/// G (default) True/False
/// l true/false
/// </remarks>
/// <exceptions>
/// <cref>System.FormatException</cref> if the format is not valid for this data type.
/// </exceptions>
public static bool TryFormat(bool value, Span<byte> destination, out int bytesWritten, StandardFormat format = default)
{
char symbol = FormattingHelpers.GetSymbolOrDefault(format, 'G');
if (value)
{
if (symbol == 'G')
{
// By having each branch perform its own call to TryWriteUInt32BigEndian, we ensure that a
// constant value is passed to this routine, which means the compiler can reverse endianness
// at compile time instead of runtime if necessary.
const uint TrueValueUppercase = ('T' << 24) + ('r' << 16) + ('u' << 8) + ('e' << 0);
if (!BinaryPrimitives.TryWriteUInt32BigEndian(destination, TrueValueUppercase))
{
goto BufferTooSmall;
}
}
else if (symbol == 'l')
{
const uint TrueValueLowercase = ('t' << 24) + ('r' << 16) + ('u' << 8) + ('e' << 0);
if (!BinaryPrimitives.TryWriteUInt32BigEndian(destination, TrueValueLowercase))
{
goto BufferTooSmall;
}
}
else
{
goto BadFormat;
}
bytesWritten = 4;
return true;
}
else
{
if (symbol == 'G')
{
// This check can't be performed earlier because we need to throw if an invalid symbol is
// provided, even if the buffer is too small.
if ((uint)4 >= (uint)destination.Length)
{
goto BufferTooSmall;
}
const uint FalsValueUppercase = ('F' << 24) + ('a' << 16) + ('l' << 8) + ('s' << 0);
BinaryPrimitives.WriteUInt32BigEndian(destination, FalsValueUppercase);
}
else if (symbol == 'l')
{
if ((uint)4 >= (uint)destination.Length)
{
goto BufferTooSmall;
}
const uint FalsValueLowercase = ('f' << 24) + ('a' << 16) + ('l' << 8) + ('s' << 0);
BinaryPrimitives.WriteUInt32BigEndian(destination, FalsValueLowercase);
}
else
{
goto BadFormat;
}
destination[4] = (byte)'e';
bytesWritten = 5;
return true;
}
BufferTooSmall:
bytesWritten = 0;
return false;
BadFormat:
return FormattingHelpers.TryFormatThrowFormatException(out bytesWritten);
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/HardwareIntrinsics/General/Vector64_1/ToVector128.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\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 ToVector128SByte()
{
var test = new VectorExtend__ToVector128SByte();
// 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 VectorExtend__ToVector128SByte
{
private static readonly int LargestVectorSize = 8;
private static readonly int ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
SByte[] values = new SByte[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSByte();
}
Vector64<SByte> value = Vector64.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
Vector128<SByte> result = value.ToVector128();
ValidateResult(result, values, isUnsafe: false);
Vector128<SByte> unsafeResult = value.ToVector128Unsafe();
ValidateResult(unsafeResult, values, isUnsafe: true);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
SByte[] values = new SByte[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSByte();
}
Vector64<SByte> value = Vector64.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
object result = typeof(Vector64)
.GetMethod(nameof(Vector64.ToVector128))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<SByte>)(result), values, isUnsafe: false);
object unsafeResult = typeof(Vector64)
.GetMethod(nameof(Vector64.ToVector128))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<SByte>)(unsafeResult), values, isUnsafe: true);
}
private void ValidateResult(Vector128<SByte> result, SByte[] values, bool isUnsafe, [CallerMemberName] string method = "")
{
SByte[] resultElements = new SByte[ElementCount * 2];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref resultElements[0]), result);
ValidateResult(resultElements, values, isUnsafe, method);
}
private void ValidateResult(SByte[] result, SByte[] values, bool isUnsafe, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if (result[i] != values[i])
{
succeeded = false;
break;
}
}
if (!isUnsafe)
{
for (int i = ElementCount; i < ElementCount * 2; i++)
{
if (result[i] != 0)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<SByte>.ToVector128{(isUnsafe ? "Unsafe" : "")}(): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
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.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void ToVector128SByte()
{
var test = new VectorExtend__ToVector128SByte();
// 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 VectorExtend__ToVector128SByte
{
private static readonly int LargestVectorSize = 8;
private static readonly int ElementCount = Unsafe.SizeOf<Vector64<SByte>>() / sizeof(SByte);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
SByte[] values = new SByte[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSByte();
}
Vector64<SByte> value = Vector64.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
Vector128<SByte> result = value.ToVector128();
ValidateResult(result, values, isUnsafe: false);
Vector128<SByte> unsafeResult = value.ToVector128Unsafe();
ValidateResult(unsafeResult, values, isUnsafe: true);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
SByte[] values = new SByte[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSByte();
}
Vector64<SByte> value = Vector64.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
object result = typeof(Vector64)
.GetMethod(nameof(Vector64.ToVector128))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<SByte>)(result), values, isUnsafe: false);
object unsafeResult = typeof(Vector64)
.GetMethod(nameof(Vector64.ToVector128))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<SByte>)(unsafeResult), values, isUnsafe: true);
}
private void ValidateResult(Vector128<SByte> result, SByte[] values, bool isUnsafe, [CallerMemberName] string method = "")
{
SByte[] resultElements = new SByte[ElementCount * 2];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref resultElements[0]), result);
ValidateResult(resultElements, values, isUnsafe, method);
}
private void ValidateResult(SByte[] result, SByte[] values, bool isUnsafe, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if (result[i] != values[i])
{
succeeded = false;
break;
}
}
if (!isUnsafe)
{
for (int i = ElementCount; i < ElementCount * 2; i++)
{
if (result[i] != 0)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<SByte>.ToVector128{(isUnsafe ? "Unsafe" : "")}(): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/coreclr/utilcode/comex.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ---------------------------------------------------------------------------
// COMEx.cpp
//
//
// ---------------------------------------------------------------------------
#include "stdafx.h"
#include "string.h"
#include "ex.h"
#include "holder.h"
#include "corerror.h"
// ---------------------------------------------------------------------------
// COMException class. Implements exception API for standard COM-based error info
// ---------------------------------------------------------------------------
COMException::~COMException()
{
WRAPPER_NO_CONTRACT;
if (m_pErrorInfo != NULL)
m_pErrorInfo->Release();
}
IErrorInfo *COMException::GetErrorInfo()
{
LIMITED_METHOD_CONTRACT;
IErrorInfo *pErrorInfo = m_pErrorInfo;
if (pErrorInfo != NULL)
pErrorInfo->AddRef();
return pErrorInfo;
}
void COMException::GetMessage(SString &string)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_NOTRIGGER;
if (m_pErrorInfo != NULL)
{
BSTRHolder message(NULL);
if (SUCCEEDED(m_pErrorInfo->GetDescription(&message)))
string.Set(message, SysStringLen(message));
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ---------------------------------------------------------------------------
// COMEx.cpp
//
//
// ---------------------------------------------------------------------------
#include "stdafx.h"
#include "string.h"
#include "ex.h"
#include "holder.h"
#include "corerror.h"
// ---------------------------------------------------------------------------
// COMException class. Implements exception API for standard COM-based error info
// ---------------------------------------------------------------------------
COMException::~COMException()
{
WRAPPER_NO_CONTRACT;
if (m_pErrorInfo != NULL)
m_pErrorInfo->Release();
}
IErrorInfo *COMException::GetErrorInfo()
{
LIMITED_METHOD_CONTRACT;
IErrorInfo *pErrorInfo = m_pErrorInfo;
if (pErrorInfo != NULL)
pErrorInfo->AddRef();
return pErrorInfo;
}
void COMException::GetMessage(SString &string)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_NOTRIGGER;
if (m_pErrorInfo != NULL)
{
BSTRHolder message(NULL);
if (SUCCEEDED(m_pErrorInfo->GetDescription(&message)))
string.Set(message, SysStringLen(message));
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNotation.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Xml.Schema
{
using System;
using System.Diagnostics;
internal sealed class SchemaNotation
{
internal const int SYSTEM = 0;
internal const int PUBLIC = 1;
private readonly XmlQualifiedName _name;
private string? _systemLiteral; // System literal
private string? _pubid; // pubid literal
internal SchemaNotation(XmlQualifiedName name)
{
_name = name;
}
internal XmlQualifiedName Name
{
get { return _name; }
}
internal string? SystemLiteral
{
get { return _systemLiteral; }
set { _systemLiteral = value; }
}
internal string? Pubid
{
get { return _pubid; }
set { _pubid = value; }
}
};
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Xml.Schema
{
using System;
using System.Diagnostics;
internal sealed class SchemaNotation
{
internal const int SYSTEM = 0;
internal const int PUBLIC = 1;
private readonly XmlQualifiedName _name;
private string? _systemLiteral; // System literal
private string? _pubid; // pubid literal
internal SchemaNotation(XmlQualifiedName name)
{
_name = name;
}
internal XmlQualifiedName Name
{
get { return _name; }
}
internal string? SystemLiteral
{
get { return _systemLiteral; }
set { _systemLiteral = value; }
}
internal string? Pubid
{
get { return _pubid; }
set { _pubid = value; }
}
};
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/coreclr/pal/src/libunwind/tests/Gtest-bt.c
|
/* libunwind - a platform-independent unwind library
Copyright (C) 2001-2004 Hewlett-Packard Co
Contributed by David Mosberger-Tang <[email protected]>
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. */
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "compiler.h"
#include <errno.h>
#if HAVE_EXECINFO_H
# include <execinfo.h>
#else
extern int backtrace (void **, int);
#endif
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ucontext.h>
#include <unistd.h>
#include <libunwind.h>
#define panic(args...) \
{ fprintf (stderr, args); exit (-1); }
#define SIG_STACK_SIZE 0x100000
int verbose;
int num_errors;
/* These variables are global because they
* cause the signal stack to overflow */
char buf[512], name[256];
unw_cursor_t cursor;
unw_context_t uc;
static void
do_backtrace (void)
{
unw_word_t ip, sp, off;
unw_proc_info_t pi;
int ret;
if (verbose)
printf ("\texplicit backtrace:\n");
unw_getcontext (&uc);
if (unw_init_local (&cursor, &uc) < 0)
panic ("unw_init_local failed!\n");
do
{
unw_get_reg (&cursor, UNW_REG_IP, &ip);
unw_get_reg (&cursor, UNW_REG_SP, &sp);
buf[0] = '\0';
if (unw_get_proc_name (&cursor, name, sizeof (name), &off) == 0)
{
if (off)
snprintf (buf, sizeof (buf), "<%s+0x%lx>", name, (long) off);
else
snprintf (buf, sizeof (buf), "<%s>", name);
}
if (verbose)
{
printf ("%016lx %-32s (sp=%016lx)\n", (long) ip, buf, (long) sp);
if (unw_get_proc_info (&cursor, &pi) == 0)
{
printf ("\tproc=0x%lx-0x%lx\n\thandler=0x%lx lsda=0x%lx gp=0x%lx",
(long) pi.start_ip, (long) pi.end_ip,
(long) pi.handler, (long) pi.lsda, (long) pi.gp);
}
#if UNW_TARGET_IA64
{
unw_word_t bsp;
unw_get_reg (&cursor, UNW_IA64_BSP, &bsp);
printf (" bsp=%lx", bsp);
}
#endif
printf ("\n");
}
ret = unw_step (&cursor);
if (ret < 0)
{
unw_get_reg (&cursor, UNW_REG_IP, &ip);
printf ("FAILURE: unw_step() returned %d for ip=%lx\n",
ret, (long) ip);
++num_errors;
}
}
while (ret > 0);
{
void *buffer[20];
int i, n;
if (verbose)
printf ("\n\tvia backtrace():\n");
n = backtrace (buffer, 20);
if (verbose)
for (i = 0; i < n; ++i)
printf ("[%d] ip=%p\n", i, buffer[i]);
}
}
void
foo (long val UNUSED)
{
do_backtrace ();
}
void
bar (long v)
{
extern long f (long);
int arr[v];
/* This is a vain attempt to use up lots of registers to force
the frame-chain info to be saved on the memory stack on ia64.
It happens to work with gcc v3.3.4 and gcc v3.4.1 but perhaps
not with any other compiler. */
foo (f (arr[0]) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + f (v))
))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
)))))))))))))))))))))))))))))))))))))))))))))))))))))));
}
void
sighandler (int signal, void *siginfo UNUSED, void *context)
{
ucontext_t *uc UNUSED;
int sp;
uc = context;
if (verbose)
{
printf ("sighandler: got signal %d, sp=%p", signal, &sp);
#if UNW_TARGET_IA64
# if defined(__linux__) || defined __sun
printf (" @ %lx", uc->uc_mcontext.sc_ip);
# else
{
uint16_t reason;
uint64_t ip;
__uc_get_reason (uc, &reason);
__uc_get_ip (uc, &ip);
printf (" @ %lx (reason=%d)", ip, reason);
}
# endif
#elif UNW_TARGET_X86
#if defined __linux__ || defined __sun
printf (" @ %lx", (unsigned long) uc->uc_mcontext.gregs[REG_EIP]);
#elif defined __FreeBSD__
printf (" @ %lx", (unsigned long) uc->uc_mcontext.mc_eip);
#endif
#elif UNW_TARGET_X86_64
#if defined __linux__ || defined __sun
printf (" @ %lx", (unsigned long) uc->uc_mcontext.gregs[REG_RIP]);
#elif defined __FreeBSD__
printf (" @ %lx", (unsigned long) uc->uc_mcontext.mc_rip);
#endif
#endif
printf ("\n");
}
do_backtrace();
}
int
main (int argc, char **argv UNUSED)
{
struct sigaction act;
stack_t stk;
verbose = (argc > 1);
if (verbose)
printf ("Normal backtrace:\n");
bar (1);
memset (&act, 0, sizeof (act));
act.sa_handler = (void (*)(int)) sighandler;
act.sa_flags = SA_SIGINFO;
if (sigaction (SIGTERM, &act, NULL) < 0)
panic ("sigaction: %s\n", strerror (errno));
if (verbose)
printf ("\nBacktrace across signal handler:\n");
kill (getpid (), SIGTERM);
if (verbose)
printf ("\nBacktrace across signal handler on alternate stack:\n");
stk.ss_sp = malloc (SIG_STACK_SIZE);
if (!stk.ss_sp)
panic ("failed to allocate %u bytes\n", SIG_STACK_SIZE);
stk.ss_size = SIG_STACK_SIZE;
stk.ss_flags = 0;
if (sigaltstack (&stk, NULL) < 0)
panic ("sigaltstack: %s\n", strerror (errno));
memset (&act, 0, sizeof (act));
act.sa_handler = (void (*)(int)) sighandler;
act.sa_flags = SA_ONSTACK | SA_SIGINFO;
if (sigaction (SIGTERM, &act, NULL) < 0)
panic ("sigaction: %s\n", strerror (errno));
kill (getpid (), SIGTERM);
if (num_errors > 0)
{
fprintf (stderr, "FAILURE: detected %d errors\n", num_errors);
exit (-1);
}
if (verbose)
printf ("SUCCESS.\n");
signal (SIGTERM, SIG_DFL);
stk.ss_flags = SS_DISABLE;
sigaltstack (&stk, NULL);
free (stk.ss_sp);
return 0;
}
|
/* libunwind - a platform-independent unwind library
Copyright (C) 2001-2004 Hewlett-Packard Co
Contributed by David Mosberger-Tang <[email protected]>
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. */
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "compiler.h"
#include <errno.h>
#if HAVE_EXECINFO_H
# include <execinfo.h>
#else
extern int backtrace (void **, int);
#endif
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ucontext.h>
#include <unistd.h>
#include <libunwind.h>
#define panic(args...) \
{ fprintf (stderr, args); exit (-1); }
#define SIG_STACK_SIZE 0x100000
int verbose;
int num_errors;
/* These variables are global because they
* cause the signal stack to overflow */
char buf[512], name[256];
unw_cursor_t cursor;
unw_context_t uc;
static void
do_backtrace (void)
{
unw_word_t ip, sp, off;
unw_proc_info_t pi;
int ret;
if (verbose)
printf ("\texplicit backtrace:\n");
unw_getcontext (&uc);
if (unw_init_local (&cursor, &uc) < 0)
panic ("unw_init_local failed!\n");
do
{
unw_get_reg (&cursor, UNW_REG_IP, &ip);
unw_get_reg (&cursor, UNW_REG_SP, &sp);
buf[0] = '\0';
if (unw_get_proc_name (&cursor, name, sizeof (name), &off) == 0)
{
if (off)
snprintf (buf, sizeof (buf), "<%s+0x%lx>", name, (long) off);
else
snprintf (buf, sizeof (buf), "<%s>", name);
}
if (verbose)
{
printf ("%016lx %-32s (sp=%016lx)\n", (long) ip, buf, (long) sp);
if (unw_get_proc_info (&cursor, &pi) == 0)
{
printf ("\tproc=0x%lx-0x%lx\n\thandler=0x%lx lsda=0x%lx gp=0x%lx",
(long) pi.start_ip, (long) pi.end_ip,
(long) pi.handler, (long) pi.lsda, (long) pi.gp);
}
#if UNW_TARGET_IA64
{
unw_word_t bsp;
unw_get_reg (&cursor, UNW_IA64_BSP, &bsp);
printf (" bsp=%lx", bsp);
}
#endif
printf ("\n");
}
ret = unw_step (&cursor);
if (ret < 0)
{
unw_get_reg (&cursor, UNW_REG_IP, &ip);
printf ("FAILURE: unw_step() returned %d for ip=%lx\n",
ret, (long) ip);
++num_errors;
}
}
while (ret > 0);
{
void *buffer[20];
int i, n;
if (verbose)
printf ("\n\tvia backtrace():\n");
n = backtrace (buffer, 20);
if (verbose)
for (i = 0; i < n; ++i)
printf ("[%d] ip=%p\n", i, buffer[i]);
}
}
void
foo (long val UNUSED)
{
do_backtrace ();
}
void
bar (long v)
{
extern long f (long);
int arr[v];
/* This is a vain attempt to use up lots of registers to force
the frame-chain info to be saved on the memory stack on ia64.
It happens to work with gcc v3.3.4 and gcc v3.4.1 but perhaps
not with any other compiler. */
foo (f (arr[0]) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v)
+ (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + (f (v) + f (v))
))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
)))))))))))))))))))))))))))))))))))))))))))))))))))))));
}
void
sighandler (int signal, void *siginfo UNUSED, void *context)
{
ucontext_t *uc UNUSED;
int sp;
uc = context;
if (verbose)
{
printf ("sighandler: got signal %d, sp=%p", signal, &sp);
#if UNW_TARGET_IA64
# if defined(__linux__) || defined __sun
printf (" @ %lx", uc->uc_mcontext.sc_ip);
# else
{
uint16_t reason;
uint64_t ip;
__uc_get_reason (uc, &reason);
__uc_get_ip (uc, &ip);
printf (" @ %lx (reason=%d)", ip, reason);
}
# endif
#elif UNW_TARGET_X86
#if defined __linux__ || defined __sun
printf (" @ %lx", (unsigned long) uc->uc_mcontext.gregs[REG_EIP]);
#elif defined __FreeBSD__
printf (" @ %lx", (unsigned long) uc->uc_mcontext.mc_eip);
#endif
#elif UNW_TARGET_X86_64
#if defined __linux__ || defined __sun
printf (" @ %lx", (unsigned long) uc->uc_mcontext.gregs[REG_RIP]);
#elif defined __FreeBSD__
printf (" @ %lx", (unsigned long) uc->uc_mcontext.mc_rip);
#endif
#endif
printf ("\n");
}
do_backtrace();
}
int
main (int argc, char **argv UNUSED)
{
struct sigaction act;
stack_t stk;
verbose = (argc > 1);
if (verbose)
printf ("Normal backtrace:\n");
bar (1);
memset (&act, 0, sizeof (act));
act.sa_handler = (void (*)(int)) sighandler;
act.sa_flags = SA_SIGINFO;
if (sigaction (SIGTERM, &act, NULL) < 0)
panic ("sigaction: %s\n", strerror (errno));
if (verbose)
printf ("\nBacktrace across signal handler:\n");
kill (getpid (), SIGTERM);
if (verbose)
printf ("\nBacktrace across signal handler on alternate stack:\n");
stk.ss_sp = malloc (SIG_STACK_SIZE);
if (!stk.ss_sp)
panic ("failed to allocate %u bytes\n", SIG_STACK_SIZE);
stk.ss_size = SIG_STACK_SIZE;
stk.ss_flags = 0;
if (sigaltstack (&stk, NULL) < 0)
panic ("sigaltstack: %s\n", strerror (errno));
memset (&act, 0, sizeof (act));
act.sa_handler = (void (*)(int)) sighandler;
act.sa_flags = SA_ONSTACK | SA_SIGINFO;
if (sigaction (SIGTERM, &act, NULL) < 0)
panic ("sigaction: %s\n", strerror (errno));
kill (getpid (), SIGTERM);
if (num_errors > 0)
{
fprintf (stderr, "FAILURE: detected %d errors\n", num_errors);
exit (-1);
}
if (verbose)
printf ("SUCCESS.\n");
signal (SIGTERM, SIG_DFL);
stk.ss_flags = SS_DISABLE;
sigaltstack (&stk, NULL);
free (stk.ss_sp);
return 0;
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/coreclr/pal/src/libunwind/include/tdep-x86_64/jmpbuf.h
|
/* libunwind - a platform-independent unwind library
Copyright (C) 2004 Hewlett-Packard Co
Contributed by David Mosberger-Tang <[email protected]>
This file is part of libunwind.
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. */
#if defined __linux__ || defined __sun
/* Use glibc's jump-buffer indices; NPTL peeks at SP:
https://sourceware.org/git/gitweb.cgi?p=glibc.git;a=blob;f=sysdeps/x86_64/jmpbuf-offsets.h;h=ea94a1f90554deecceaf995ca5ee485ae8bffab7;hb=HEAD */
#define JB_SP 6
#define JB_RP 7
#define JB_MASK_SAVED 8
#define JB_MASK 9
#elif defined __FreeBSD__
#define JB_SP 2
#define JB_RP 0
/* Pretend the ip cannot be 0 and mask is always saved */
#define JB_MASK_SAVED 0
#define JB_MASK 9
#endif
|
/* libunwind - a platform-independent unwind library
Copyright (C) 2004 Hewlett-Packard Co
Contributed by David Mosberger-Tang <[email protected]>
This file is part of libunwind.
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. */
#if defined __linux__ || defined __sun
/* Use glibc's jump-buffer indices; NPTL peeks at SP:
https://sourceware.org/git/gitweb.cgi?p=glibc.git;a=blob;f=sysdeps/x86_64/jmpbuf-offsets.h;h=ea94a1f90554deecceaf995ca5ee485ae8bffab7;hb=HEAD */
#define JB_SP 6
#define JB_RP 7
#define JB_MASK_SAVED 8
#define JB_MASK 9
#elif defined __FreeBSD__
#define JB_SP 2
#define JB_RP 0
/* Pretend the ip cannot be 0 and mask is always saved */
#define JB_MASK_SAVED 0
#define JB_MASK 9
#endif
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/mono/mono/mini/aot-compiler.h
|
/**
* \file
*/
#ifndef __MONO_AOT_COMPILER_H__
#define __MONO_AOT_COMPILER_H__
#include "mini.h"
int mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **aot_state);
int mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state);
void* mono_aot_readonly_field_override (MonoClassField *field);
gboolean mono_aot_direct_icalls_enabled_for_method (MonoCompile *cfg, MonoMethod *method);
gboolean mono_aot_is_shared_got_offset (int offset);
guint32 mono_aot_get_got_offset (MonoJumpInfo *ji);
char* mono_aot_get_method_name (MonoCompile *cfg);
char* mono_aot_get_mangled_method_name (MonoMethod *method);
gboolean mono_aot_is_direct_callable (MonoJumpInfo *patch_info);
gboolean mono_aot_is_externally_callable (MonoMethod *cmethod);
void mono_aot_mark_unused_llvm_plt_entry(MonoJumpInfo *patch_info);
char* mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data);
char* mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data);
int mono_aot_get_method_index (MonoMethod *method);
MonoJumpInfo* mono_aot_patch_info_dup (MonoJumpInfo* ji);
gboolean mono_aot_can_specialize (MonoMethod *method);
gboolean mono_aot_can_enter_interp (MonoMethod *method);
#endif
|
/**
* \file
*/
#ifndef __MONO_AOT_COMPILER_H__
#define __MONO_AOT_COMPILER_H__
#include "mini.h"
int mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options, gpointer **aot_state);
int mono_compile_deferred_assemblies (guint32 opts, const char *aot_options, gpointer **aot_state);
void* mono_aot_readonly_field_override (MonoClassField *field);
gboolean mono_aot_direct_icalls_enabled_for_method (MonoCompile *cfg, MonoMethod *method);
gboolean mono_aot_is_shared_got_offset (int offset);
guint32 mono_aot_get_got_offset (MonoJumpInfo *ji);
char* mono_aot_get_method_name (MonoCompile *cfg);
char* mono_aot_get_mangled_method_name (MonoMethod *method);
gboolean mono_aot_is_direct_callable (MonoJumpInfo *patch_info);
gboolean mono_aot_is_externally_callable (MonoMethod *cmethod);
void mono_aot_mark_unused_llvm_plt_entry(MonoJumpInfo *patch_info);
char* mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data);
char* mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data);
int mono_aot_get_method_index (MonoMethod *method);
MonoJumpInfo* mono_aot_patch_info_dup (MonoJumpInfo* ji);
gboolean mono_aot_can_specialize (MonoMethod *method);
gboolean mono_aot_can_enter_interp (MonoMethod *method);
#endif
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/GroupByQueryOperator.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// GroupByQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using IEnumerator = System.Collections.IEnumerator;
namespace System.Linq.Parallel
{
/// <summary>
/// The operator type for GroupBy statements. This operator groups the input based on
/// a key-selection routine, yielding one-to-many values of key-to-elements. The
/// implementation is very much like the hash join operator, in which we first build
/// a big hashtable of the input; then we just iterate over each unique key in the
/// hashtable, yielding it plus all of the elements with the same key.
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TGroupKey"></typeparam>
/// <typeparam name="TElement"></typeparam>
internal sealed class GroupByQueryOperator<TSource, TGroupKey, TElement> :
UnaryQueryOperator<TSource, IGrouping<TGroupKey, TElement>>
{
private readonly Func<TSource, TGroupKey> _keySelector; // Key selection function.
private readonly Func<TSource, TElement>? _elementSelector; // Optional element selection function.
private readonly IEqualityComparer<TGroupKey>? _keyComparer; // An optional key comparison object.
//---------------------------------------------------------------------------------------
// Initializes a new group by operator.
//
// Arguments:
// child - the child operator or data source from which to pull data
// keySelector - a delegate representing the key selector function
// elementSelector - a delegate representing the element selector function
// keyComparer - an optional key comparison routine
//
// Assumptions:
// keySelector must be non null.
// elementSelector must be non null.
//
internal GroupByQueryOperator(IEnumerable<TSource> child,
Func<TSource, TGroupKey> keySelector,
Func<TSource, TElement>? elementSelector,
IEqualityComparer<TGroupKey>? keyComparer)
: base(child)
{
Debug.Assert(child != null, "child data source cannot be null");
Debug.Assert(keySelector != null, "need a selector function");
Debug.Assert(elementSelector != null ||
typeof(TSource) == typeof(TElement), "need an element function if TSource!=TElement");
_keySelector = keySelector;
_elementSelector = elementSelector;
_keyComparer = keyComparer;
SetOrdinalIndexState(OrdinalIndexState.Shuffled);
}
internal override void WrapPartitionedStream<TKey>(
PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<IGrouping<TGroupKey, TElement>> recipient,
bool preferStriping, QuerySettings settings)
{
// Hash-repartition the source stream
if (Child.OutputOrdered)
{
WrapPartitionedStreamHelperOrdered<TKey>(
ExchangeUtilities.HashRepartitionOrdered<TSource, TGroupKey, TKey>(
inputStream, _keySelector, _keyComparer, null, settings.CancellationState.MergedCancellationToken),
recipient,
settings.CancellationState.MergedCancellationToken
);
}
else
{
WrapPartitionedStreamHelper<TKey, int>(
ExchangeUtilities.HashRepartition<TSource, TGroupKey, TKey>(
inputStream, _keySelector, _keyComparer, null, settings.CancellationState.MergedCancellationToken),
recipient,
settings.CancellationState.MergedCancellationToken
);
}
}
//---------------------------------------------------------------------------------------
// This is a helper method. WrapPartitionedStream decides what type TKey is going
// to be, and then call this method with that key as a generic parameter.
//
private void WrapPartitionedStreamHelper<TIgnoreKey, TKey>(
PartitionedStream<Pair<TSource, TGroupKey>, TKey> hashStream,
IPartitionedStreamRecipient<IGrouping<TGroupKey, TElement>> recipient,
CancellationToken cancellationToken)
{
int partitionCount = hashStream.PartitionCount;
PartitionedStream<IGrouping<TGroupKey, TElement>, TKey> outputStream =
new PartitionedStream<IGrouping<TGroupKey, TElement>, TKey>(partitionCount, hashStream.KeyComparer, OrdinalIndexState.Shuffled);
// If there is no element selector, we return a special identity enumerator. Otherwise,
// we return one that will apply the element selection function during enumeration.
for (int i = 0; i < partitionCount; i++)
{
if (_elementSelector == null)
{
Debug.Assert(typeof(TSource) == typeof(TElement));
var enumerator = new GroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TKey>(
hashStream[i], _keyComparer, cancellationToken);
outputStream[i] = (QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TKey>)(object)enumerator;
}
else
{
outputStream[i] = new GroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TKey>(
hashStream[i], _keyComparer, _elementSelector, cancellationToken);
}
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// This is a helper method. WrapPartitionedStream decides what type TKey is going
// to be, and then call this method with that key as a generic parameter.
//
private void WrapPartitionedStreamHelperOrdered<TKey>(
PartitionedStream<Pair<TSource, TGroupKey>, TKey> hashStream,
IPartitionedStreamRecipient<IGrouping<TGroupKey, TElement>> recipient,
CancellationToken cancellationToken)
{
int partitionCount = hashStream.PartitionCount;
PartitionedStream<IGrouping<TGroupKey, TElement>, TKey> outputStream =
new PartitionedStream<IGrouping<TGroupKey, TElement>, TKey>(partitionCount, hashStream.KeyComparer, OrdinalIndexState.Shuffled);
// If there is no element selector, we return a special identity enumerator. Otherwise,
// we return one that will apply the element selection function during enumeration.
IComparer<TKey> orderComparer = hashStream.KeyComparer;
for (int i = 0; i < partitionCount; i++)
{
if (_elementSelector == null)
{
Debug.Assert(typeof(TSource) == typeof(TElement));
var enumerator = new OrderedGroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TKey>(
hashStream[i], _keySelector, _keyComparer, orderComparer, cancellationToken);
outputStream[i] = (QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TKey>)(object)enumerator;
}
else
{
outputStream[i] = new OrderedGroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TKey>(
hashStream[i], _keySelector, _elementSelector, _keyComparer, orderComparer,
cancellationToken);
}
}
recipient.Receive(outputStream);
}
//-----------------------------------------------------------------------------------
// Override of the query operator base class's Open method.
//
internal override QueryResults<IGrouping<TGroupKey, TElement>> Open(QuerySettings settings, bool preferStriping)
{
// We just open our child operator. Do not propagate the preferStriping value, but instead explicitly
// set it to false. Regardless of whether the parent prefers striping or range partitioning, the output
// will be hash-partitioned.
QueryResults<TSource> childResults = Child.Open(settings, false);
return new UnaryQueryOperatorResults(childResults, this, settings, false);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<IGrouping<TGroupKey, TElement>> AsSequentialQuery(CancellationToken token)
{
IEnumerable<TSource> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token);
if (_elementSelector == null)
{
Debug.Assert(typeof(TElement) == typeof(TSource));
return (IEnumerable<IGrouping<TGroupKey, TElement>>)wrappedChild.GroupBy(_keySelector, _keyComparer);
}
else
{
return wrappedChild.GroupBy(_keySelector, _elementSelector, _keyComparer);
}
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
}
//---------------------------------------------------------------------------------------
// The enumerator type responsible for grouping elements and yielding the key-value sets.
//
// Assumptions:
// Just like the Join operator, this won't work properly at all if the analysis engine
// didn't choose to hash partition. We will simply not yield correct groupings.
//
internal abstract class GroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TOrderKey>
{
protected readonly QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> _source; // The data source to enumerate.
protected readonly IEqualityComparer<TGroupKey>? _keyComparer; // A key comparer.
protected readonly CancellationToken _cancellationToken;
private Mutables? _mutables; // All of the mutable state.
private sealed class Mutables
{
internal HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>>? _hashLookup; // The lookup with key-value mappings.
internal int _hashLookupIndex; // The current index within the lookup.
}
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
protected GroupByQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source,
IEqualityComparer<TGroupKey>? keyComparer, CancellationToken cancellationToken)
{
Debug.Assert(source != null);
_source = source;
_keyComparer = keyComparer;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// MoveNext will invoke the entire query sub-tree, accumulating results into a hash-
// table, upon the first call. Then for the first call and all subsequent calls, we will
// just enumerate the key-set from the hash-table, retrieving groupings of key-elements.
//
internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref IGrouping<TGroupKey, TElement> currentElement, [AllowNull] ref TOrderKey currentKey)
{
Debug.Assert(_source != null);
// Lazy-init the mutable state. This also means we haven't yet built our lookup of
// groupings, so we can go ahead and do that too.
Mutables? mutables = _mutables;
if (mutables == null)
{
mutables = _mutables = new Mutables();
// Build the hash lookup and start enumerating the lookup at the beginning.
mutables._hashLookup = BuildHashLookup();
mutables._hashLookupIndex = -1;
}
Debug.Assert(mutables._hashLookup != null);
// Now, with a hash lookup in hand, we just enumerate the keys. So long
// as the key-value lookup has elements, we have elements.
if (++mutables._hashLookupIndex < mutables._hashLookup.Count)
{
currentElement = new GroupByGrouping<TGroupKey, TElement>(
mutables._hashLookup[mutables._hashLookupIndex]);
return true;
}
return false;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected abstract HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> BuildHashLookup();
protected override void Dispose(bool disposing)
{
_source.Dispose();
}
}
//---------------------------------------------------------------------------------------
// A specialization of the group by enumerator for yielding elements with the identity
// function.
//
internal sealed class GroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TOrderKey> :
GroupByQueryOperatorEnumerator<TSource, TGroupKey, TSource, TOrderKey>
{
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal GroupByIdentityQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source,
IEqualityComparer<TGroupKey>? keyComparer, CancellationToken cancellationToken)
: base(source, keyComparer, cancellationToken)
{
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, ListChunk<TSource>> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, ListChunk<TSource>> hashlookup =
new HashLookup<Wrapper<TGroupKey>, ListChunk<TSource>>(new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair<TSource, TGroupKey> sourceElement = default(Pair<TSource, TGroupKey>);
TOrderKey sourceKeyUnused = default(TOrderKey)!;
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceKeyUnused))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
_cancellationToken.ThrowIfCancellationRequested();
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>(sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
ListChunk<TSource>? currentValue = null;
if (!hashlookup.TryGetValue(key, ref currentValue))
{
const int INITIAL_CHUNK_SIZE = 2;
currentValue = new ListChunk<TSource>(INITIAL_CHUNK_SIZE);
hashlookup.Add(key, currentValue);
}
Debug.Assert(currentValue != null);
// Call to the base class to yield the current value.
currentValue.Add(sourceElement.First);
}
return hashlookup;
}
}
//---------------------------------------------------------------------------------------
// A specialization of the group by enumerator for yielding elements with any arbitrary
// element selection function.
//
internal sealed class GroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
GroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey>
{
private readonly Func<TSource, TElement> _elementSelector; // Function to select elements.
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal GroupByElementSelectorQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source,
IEqualityComparer<TGroupKey>? keyComparer, Func<TSource, TElement> elementSelector, CancellationToken cancellationToken) :
base(source, keyComparer, cancellationToken)
{
Debug.Assert(elementSelector != null);
_elementSelector = elementSelector;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> hashlookup =
new HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>>(new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair<TSource, TGroupKey> sourceElement = default(Pair<TSource, TGroupKey>);
TOrderKey sourceKeyUnused = default(TOrderKey)!;
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceKeyUnused))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
_cancellationToken.ThrowIfCancellationRequested();
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>(sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
ListChunk<TElement>? currentValue = null;
if (!hashlookup.TryGetValue(key, ref currentValue))
{
const int INITIAL_CHUNK_SIZE = 2;
currentValue = new ListChunk<TElement>(INITIAL_CHUNK_SIZE);
hashlookup.Add(key, currentValue);
}
Debug.Assert(currentValue != null);
// Call to the base class to yield the current value.
currentValue.Add(_elementSelector(sourceElement.First));
}
return hashlookup;
}
}
//---------------------------------------------------------------------------------------
// Ordered version of the GroupBy operator.
//
internal abstract class OrderedGroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TOrderKey>
{
protected readonly QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> _source; // The data source to enumerate.
private readonly Func<TSource, TGroupKey> _keySelector; // The key selection routine.
protected readonly IEqualityComparer<TGroupKey>? _keyComparer; // The key comparison routine.
protected readonly IComparer<TOrderKey> _orderComparer; // The comparison routine for order keys.
protected readonly CancellationToken _cancellationToken;
private Mutables? _mutables; // All the mutable state.
private sealed class Mutables
{
internal HashLookup<Wrapper<TGroupKey>, GroupKeyData>? _hashLookup; // The lookup with key-value mappings.
internal int _hashLookupIndex; // The current index within the lookup.
}
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
protected OrderedGroupByQueryOperatorEnumerator(QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source,
Func<TSource, TGroupKey> keySelector, IEqualityComparer<TGroupKey>? keyComparer, IComparer<TOrderKey> orderComparer,
CancellationToken cancellationToken)
{
Debug.Assert(source != null);
Debug.Assert(keySelector != null);
_source = source;
_keySelector = keySelector;
_keyComparer = keyComparer;
_orderComparer = orderComparer;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// MoveNext will invoke the entire query sub-tree, accumulating results into a hash-
// table, upon the first call. Then for the first call and all subsequent calls, we will
// just enumerate the key-set from the hash-table, retrieving groupings of key-elements.
//
internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref IGrouping<TGroupKey, TElement> currentElement, [AllowNull] ref TOrderKey currentKey)
{
Debug.Assert(_source != null);
Debug.Assert(_keySelector != null);
// Lazy-init the mutable state. This also means we haven't yet built our lookup of
// groupings, so we can go ahead and do that too.
Mutables? mutables = _mutables;
if (mutables == null)
{
mutables = _mutables = new Mutables();
// Build the hash lookup and start enumerating the lookup at the beginning.
mutables._hashLookup = BuildHashLookup();
mutables._hashLookupIndex = -1;
}
Debug.Assert(mutables._hashLookup != null);
// Now, with a hash lookup in hand, we just enumerate the keys. So long
// as the key-value lookup has elements, we have elements.
if (++mutables._hashLookupIndex < mutables._hashLookup.Count)
{
GroupKeyData value = mutables._hashLookup[mutables._hashLookupIndex].Value;
currentElement = value._grouping;
currentKey = value._orderKey;
return true;
}
return false;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected abstract HashLookup<Wrapper<TGroupKey>, GroupKeyData> BuildHashLookup();
protected override void Dispose(bool disposing)
{
_source.Dispose();
}
//-----------------------------------------------------------------------------------
// A data structure that holds information about elements with a particular key.
//
// This information includes two parts:
// - An order key for the grouping.
// - The grouping itself. The grouping consists of elements and the grouping key.
//
protected sealed class GroupKeyData
{
internal TOrderKey _orderKey;
internal OrderedGroupByGrouping<TGroupKey, TOrderKey, TElement> _grouping;
internal GroupKeyData(TOrderKey orderKey, TGroupKey hashKey, IComparer<TOrderKey> orderComparer)
{
_orderKey = orderKey;
_grouping = new OrderedGroupByGrouping<TGroupKey, TOrderKey, TElement>(hashKey, orderComparer);
}
}
}
//---------------------------------------------------------------------------------------
// A specialization of the ordered GroupBy enumerator for yielding elements with the identity
// function.
//
internal sealed class OrderedGroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TOrderKey> :
OrderedGroupByQueryOperatorEnumerator<TSource, TGroupKey, TSource, TOrderKey>
{
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal OrderedGroupByIdentityQueryOperatorEnumerator(QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source,
Func<TSource, TGroupKey> keySelector, IEqualityComparer<TGroupKey>? keyComparer, IComparer<TOrderKey> orderComparer,
CancellationToken cancellationToken)
: base(source, keySelector, keyComparer, orderComparer, cancellationToken)
{
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, GroupKeyData> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, GroupKeyData> hashLookup = new HashLookup<Wrapper<TGroupKey>, GroupKeyData>(
new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair<TSource, TGroupKey> sourceElement = default(Pair<TSource, TGroupKey>);
TOrderKey sourceOrderKey = default(TOrderKey)!;
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceOrderKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
_cancellationToken.ThrowIfCancellationRequested();
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>(sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
GroupKeyData? currentValue = null;
if (hashLookup.TryGetValue(key, ref currentValue))
{
if (_orderComparer.Compare(sourceOrderKey, currentValue._orderKey) < 0)
{
currentValue._orderKey = sourceOrderKey;
}
}
else
{
currentValue = new GroupKeyData(sourceOrderKey, key.Value, _orderComparer);
hashLookup.Add(key, currentValue);
}
Debug.Assert(currentValue != null);
currentValue._grouping.Add(sourceElement.First, sourceOrderKey);
}
// Sort the elements within each group
for (int j = 0; j < hashLookup.Count; j++)
{
hashLookup[j].Value._grouping.DoneAdding();
}
return hashLookup;
}
}
//---------------------------------------------------------------------------------------
// A specialization of the ordered GroupBy enumerator for yielding elements with any arbitrary
// element selection function.
//
internal sealed class OrderedGroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
OrderedGroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey>
{
private readonly Func<TSource, TElement> _elementSelector; // Function to select elements.
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal OrderedGroupByElementSelectorQueryOperatorEnumerator(QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source,
Func<TSource, TGroupKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TGroupKey>? keyComparer, IComparer<TOrderKey> orderComparer,
CancellationToken cancellationToken) :
base(source, keySelector, keyComparer, orderComparer, cancellationToken)
{
Debug.Assert(elementSelector != null);
_elementSelector = elementSelector;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, GroupKeyData> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, GroupKeyData> hashLookup = new HashLookup<Wrapper<TGroupKey>, GroupKeyData>(
new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair<TSource, TGroupKey> sourceElement = default(Pair<TSource, TGroupKey>);
TOrderKey sourceOrderKey = default(TOrderKey)!;
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceOrderKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
_cancellationToken.ThrowIfCancellationRequested();
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>(sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
GroupKeyData? currentValue = null;
if (hashLookup.TryGetValue(key, ref currentValue))
{
if (_orderComparer.Compare(sourceOrderKey, currentValue._orderKey) < 0)
{
currentValue._orderKey = sourceOrderKey;
}
}
else
{
currentValue = new GroupKeyData(sourceOrderKey, key.Value, _orderComparer);
hashLookup.Add(key, currentValue);
}
Debug.Assert(currentValue != null);
// Call to the base class to yield the current value.
currentValue._grouping.Add(_elementSelector(sourceElement.First), sourceOrderKey);
}
// Sort the elements within each group
for (int j = 0; j < hashLookup.Count; j++)
{
hashLookup[j].Value._grouping.DoneAdding();
}
return hashLookup;
}
}
//---------------------------------------------------------------------------------------
// This little type implements the IGrouping<K,T> interface, and exposes a single
// key-to-many-values mapping.
//
internal sealed class GroupByGrouping<TGroupKey, TElement> : IGrouping<TGroupKey, TElement>
{
private readonly KeyValuePair<Wrapper<TGroupKey>, ListChunk<TElement>> _keyValues; // A key value pair.
//---------------------------------------------------------------------------------------
// Constructs a new grouping out of the key value pair.
//
internal GroupByGrouping(KeyValuePair<Wrapper<TGroupKey>, ListChunk<TElement>> keyValues)
{
Debug.Assert(keyValues.Value != null);
_keyValues = keyValues;
}
//---------------------------------------------------------------------------------------
// The key this mapping represents.
//
TGroupKey IGrouping<TGroupKey, TElement>.Key
{
get
{
return _keyValues.Key.Value;
}
}
//---------------------------------------------------------------------------------------
// Access to value enumerators.
//
IEnumerator<TElement> IEnumerable<TElement>.GetEnumerator()
{
Debug.Assert(_keyValues.Value != null);
return _keyValues.Value.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<TElement>)this).GetEnumerator();
}
}
/// <summary>
/// An ordered version of the grouping data structure. Represents an ordered group of elements that
/// have the same grouping key.
/// </summary>
internal sealed class OrderedGroupByGrouping<TGroupKey, TOrderKey, TElement> : IGrouping<TGroupKey, TElement>
{
private const int INITIAL_CHUNK_SIZE = 2;
private readonly TGroupKey _groupKey; // The group key for this grouping
private ListChunk<Pair<TOrderKey, TElement>>? _values; // Values in this group
private TElement[]? _sortedValues; // Sorted values (allocated in DoneAdding)
private readonly IComparer<TOrderKey> _orderComparer; // Comparer for order keys
/// <summary>
/// Constructs a new grouping
/// </summary>
internal OrderedGroupByGrouping(
TGroupKey groupKey,
IComparer<TOrderKey> orderComparer)
{
_groupKey = groupKey;
_values = new ListChunk<Pair<TOrderKey, TElement>>(INITIAL_CHUNK_SIZE);
_orderComparer = orderComparer;
}
/// <summary>
/// The key this grouping represents.
/// </summary>
TGroupKey IGrouping<TGroupKey, TElement>.Key
{
get
{
return _groupKey;
}
}
IEnumerator<TElement> IEnumerable<TElement>.GetEnumerator()
{
Debug.Assert(_sortedValues != null);
return ((IEnumerable<TElement>)_sortedValues).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<TElement>)this).GetEnumerator();
}
/// <summary>
/// Add an element
/// </summary>
internal void Add(TElement value, TOrderKey orderKey)
{
Debug.Assert(_values != null);
_values.Add(new Pair<TOrderKey, TElement>(orderKey, value));
}
/// <summary>
/// No more elements will be added, so we can sort the group now.
/// </summary>
internal void DoneAdding()
{
Debug.Assert(_values != null);
int count = _values.Count;
ListChunk<Pair<TOrderKey, TElement>>? curChunk = _values;
while ((curChunk = curChunk.Next) != null)
{
count += curChunk.Count;
}
TElement[] values = new TElement[count];
TOrderKey[] orderKeys = new TOrderKey[count];
int idx = 0;
foreach (Pair<TOrderKey, TElement> p in _values)
{
orderKeys[idx] = p.First;
values[idx] = p.Second;
idx++;
}
Array.Sort(orderKeys, values, _orderComparer);
_sortedValues = values;
#if DEBUG
_values = null; // Any future calls to Add() or DoneAdding() will fail
#endif
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// GroupByQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using IEnumerator = System.Collections.IEnumerator;
namespace System.Linq.Parallel
{
/// <summary>
/// The operator type for GroupBy statements. This operator groups the input based on
/// a key-selection routine, yielding one-to-many values of key-to-elements. The
/// implementation is very much like the hash join operator, in which we first build
/// a big hashtable of the input; then we just iterate over each unique key in the
/// hashtable, yielding it plus all of the elements with the same key.
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TGroupKey"></typeparam>
/// <typeparam name="TElement"></typeparam>
internal sealed class GroupByQueryOperator<TSource, TGroupKey, TElement> :
UnaryQueryOperator<TSource, IGrouping<TGroupKey, TElement>>
{
private readonly Func<TSource, TGroupKey> _keySelector; // Key selection function.
private readonly Func<TSource, TElement>? _elementSelector; // Optional element selection function.
private readonly IEqualityComparer<TGroupKey>? _keyComparer; // An optional key comparison object.
//---------------------------------------------------------------------------------------
// Initializes a new group by operator.
//
// Arguments:
// child - the child operator or data source from which to pull data
// keySelector - a delegate representing the key selector function
// elementSelector - a delegate representing the element selector function
// keyComparer - an optional key comparison routine
//
// Assumptions:
// keySelector must be non null.
// elementSelector must be non null.
//
internal GroupByQueryOperator(IEnumerable<TSource> child,
Func<TSource, TGroupKey> keySelector,
Func<TSource, TElement>? elementSelector,
IEqualityComparer<TGroupKey>? keyComparer)
: base(child)
{
Debug.Assert(child != null, "child data source cannot be null");
Debug.Assert(keySelector != null, "need a selector function");
Debug.Assert(elementSelector != null ||
typeof(TSource) == typeof(TElement), "need an element function if TSource!=TElement");
_keySelector = keySelector;
_elementSelector = elementSelector;
_keyComparer = keyComparer;
SetOrdinalIndexState(OrdinalIndexState.Shuffled);
}
internal override void WrapPartitionedStream<TKey>(
PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<IGrouping<TGroupKey, TElement>> recipient,
bool preferStriping, QuerySettings settings)
{
// Hash-repartition the source stream
if (Child.OutputOrdered)
{
WrapPartitionedStreamHelperOrdered<TKey>(
ExchangeUtilities.HashRepartitionOrdered<TSource, TGroupKey, TKey>(
inputStream, _keySelector, _keyComparer, null, settings.CancellationState.MergedCancellationToken),
recipient,
settings.CancellationState.MergedCancellationToken
);
}
else
{
WrapPartitionedStreamHelper<TKey, int>(
ExchangeUtilities.HashRepartition<TSource, TGroupKey, TKey>(
inputStream, _keySelector, _keyComparer, null, settings.CancellationState.MergedCancellationToken),
recipient,
settings.CancellationState.MergedCancellationToken
);
}
}
//---------------------------------------------------------------------------------------
// This is a helper method. WrapPartitionedStream decides what type TKey is going
// to be, and then call this method with that key as a generic parameter.
//
private void WrapPartitionedStreamHelper<TIgnoreKey, TKey>(
PartitionedStream<Pair<TSource, TGroupKey>, TKey> hashStream,
IPartitionedStreamRecipient<IGrouping<TGroupKey, TElement>> recipient,
CancellationToken cancellationToken)
{
int partitionCount = hashStream.PartitionCount;
PartitionedStream<IGrouping<TGroupKey, TElement>, TKey> outputStream =
new PartitionedStream<IGrouping<TGroupKey, TElement>, TKey>(partitionCount, hashStream.KeyComparer, OrdinalIndexState.Shuffled);
// If there is no element selector, we return a special identity enumerator. Otherwise,
// we return one that will apply the element selection function during enumeration.
for (int i = 0; i < partitionCount; i++)
{
if (_elementSelector == null)
{
Debug.Assert(typeof(TSource) == typeof(TElement));
var enumerator = new GroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TKey>(
hashStream[i], _keyComparer, cancellationToken);
outputStream[i] = (QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TKey>)(object)enumerator;
}
else
{
outputStream[i] = new GroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TKey>(
hashStream[i], _keyComparer, _elementSelector, cancellationToken);
}
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// This is a helper method. WrapPartitionedStream decides what type TKey is going
// to be, and then call this method with that key as a generic parameter.
//
private void WrapPartitionedStreamHelperOrdered<TKey>(
PartitionedStream<Pair<TSource, TGroupKey>, TKey> hashStream,
IPartitionedStreamRecipient<IGrouping<TGroupKey, TElement>> recipient,
CancellationToken cancellationToken)
{
int partitionCount = hashStream.PartitionCount;
PartitionedStream<IGrouping<TGroupKey, TElement>, TKey> outputStream =
new PartitionedStream<IGrouping<TGroupKey, TElement>, TKey>(partitionCount, hashStream.KeyComparer, OrdinalIndexState.Shuffled);
// If there is no element selector, we return a special identity enumerator. Otherwise,
// we return one that will apply the element selection function during enumeration.
IComparer<TKey> orderComparer = hashStream.KeyComparer;
for (int i = 0; i < partitionCount; i++)
{
if (_elementSelector == null)
{
Debug.Assert(typeof(TSource) == typeof(TElement));
var enumerator = new OrderedGroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TKey>(
hashStream[i], _keySelector, _keyComparer, orderComparer, cancellationToken);
outputStream[i] = (QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TKey>)(object)enumerator;
}
else
{
outputStream[i] = new OrderedGroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TKey>(
hashStream[i], _keySelector, _elementSelector, _keyComparer, orderComparer,
cancellationToken);
}
}
recipient.Receive(outputStream);
}
//-----------------------------------------------------------------------------------
// Override of the query operator base class's Open method.
//
internal override QueryResults<IGrouping<TGroupKey, TElement>> Open(QuerySettings settings, bool preferStriping)
{
// We just open our child operator. Do not propagate the preferStriping value, but instead explicitly
// set it to false. Regardless of whether the parent prefers striping or range partitioning, the output
// will be hash-partitioned.
QueryResults<TSource> childResults = Child.Open(settings, false);
return new UnaryQueryOperatorResults(childResults, this, settings, false);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<IGrouping<TGroupKey, TElement>> AsSequentialQuery(CancellationToken token)
{
IEnumerable<TSource> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token);
if (_elementSelector == null)
{
Debug.Assert(typeof(TElement) == typeof(TSource));
return (IEnumerable<IGrouping<TGroupKey, TElement>>)wrappedChild.GroupBy(_keySelector, _keyComparer);
}
else
{
return wrappedChild.GroupBy(_keySelector, _elementSelector, _keyComparer);
}
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
}
//---------------------------------------------------------------------------------------
// The enumerator type responsible for grouping elements and yielding the key-value sets.
//
// Assumptions:
// Just like the Join operator, this won't work properly at all if the analysis engine
// didn't choose to hash partition. We will simply not yield correct groupings.
//
internal abstract class GroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TOrderKey>
{
protected readonly QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> _source; // The data source to enumerate.
protected readonly IEqualityComparer<TGroupKey>? _keyComparer; // A key comparer.
protected readonly CancellationToken _cancellationToken;
private Mutables? _mutables; // All of the mutable state.
private sealed class Mutables
{
internal HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>>? _hashLookup; // The lookup with key-value mappings.
internal int _hashLookupIndex; // The current index within the lookup.
}
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
protected GroupByQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source,
IEqualityComparer<TGroupKey>? keyComparer, CancellationToken cancellationToken)
{
Debug.Assert(source != null);
_source = source;
_keyComparer = keyComparer;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// MoveNext will invoke the entire query sub-tree, accumulating results into a hash-
// table, upon the first call. Then for the first call and all subsequent calls, we will
// just enumerate the key-set from the hash-table, retrieving groupings of key-elements.
//
internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref IGrouping<TGroupKey, TElement> currentElement, [AllowNull] ref TOrderKey currentKey)
{
Debug.Assert(_source != null);
// Lazy-init the mutable state. This also means we haven't yet built our lookup of
// groupings, so we can go ahead and do that too.
Mutables? mutables = _mutables;
if (mutables == null)
{
mutables = _mutables = new Mutables();
// Build the hash lookup and start enumerating the lookup at the beginning.
mutables._hashLookup = BuildHashLookup();
mutables._hashLookupIndex = -1;
}
Debug.Assert(mutables._hashLookup != null);
// Now, with a hash lookup in hand, we just enumerate the keys. So long
// as the key-value lookup has elements, we have elements.
if (++mutables._hashLookupIndex < mutables._hashLookup.Count)
{
currentElement = new GroupByGrouping<TGroupKey, TElement>(
mutables._hashLookup[mutables._hashLookupIndex]);
return true;
}
return false;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected abstract HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> BuildHashLookup();
protected override void Dispose(bool disposing)
{
_source.Dispose();
}
}
//---------------------------------------------------------------------------------------
// A specialization of the group by enumerator for yielding elements with the identity
// function.
//
internal sealed class GroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TOrderKey> :
GroupByQueryOperatorEnumerator<TSource, TGroupKey, TSource, TOrderKey>
{
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal GroupByIdentityQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source,
IEqualityComparer<TGroupKey>? keyComparer, CancellationToken cancellationToken)
: base(source, keyComparer, cancellationToken)
{
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, ListChunk<TSource>> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, ListChunk<TSource>> hashlookup =
new HashLookup<Wrapper<TGroupKey>, ListChunk<TSource>>(new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair<TSource, TGroupKey> sourceElement = default(Pair<TSource, TGroupKey>);
TOrderKey sourceKeyUnused = default(TOrderKey)!;
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceKeyUnused))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
_cancellationToken.ThrowIfCancellationRequested();
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>(sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
ListChunk<TSource>? currentValue = null;
if (!hashlookup.TryGetValue(key, ref currentValue))
{
const int INITIAL_CHUNK_SIZE = 2;
currentValue = new ListChunk<TSource>(INITIAL_CHUNK_SIZE);
hashlookup.Add(key, currentValue);
}
Debug.Assert(currentValue != null);
// Call to the base class to yield the current value.
currentValue.Add(sourceElement.First);
}
return hashlookup;
}
}
//---------------------------------------------------------------------------------------
// A specialization of the group by enumerator for yielding elements with any arbitrary
// element selection function.
//
internal sealed class GroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
GroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey>
{
private readonly Func<TSource, TElement> _elementSelector; // Function to select elements.
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal GroupByElementSelectorQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source,
IEqualityComparer<TGroupKey>? keyComparer, Func<TSource, TElement> elementSelector, CancellationToken cancellationToken) :
base(source, keyComparer, cancellationToken)
{
Debug.Assert(elementSelector != null);
_elementSelector = elementSelector;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> hashlookup =
new HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>>(new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair<TSource, TGroupKey> sourceElement = default(Pair<TSource, TGroupKey>);
TOrderKey sourceKeyUnused = default(TOrderKey)!;
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceKeyUnused))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
_cancellationToken.ThrowIfCancellationRequested();
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>(sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
ListChunk<TElement>? currentValue = null;
if (!hashlookup.TryGetValue(key, ref currentValue))
{
const int INITIAL_CHUNK_SIZE = 2;
currentValue = new ListChunk<TElement>(INITIAL_CHUNK_SIZE);
hashlookup.Add(key, currentValue);
}
Debug.Assert(currentValue != null);
// Call to the base class to yield the current value.
currentValue.Add(_elementSelector(sourceElement.First));
}
return hashlookup;
}
}
//---------------------------------------------------------------------------------------
// Ordered version of the GroupBy operator.
//
internal abstract class OrderedGroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TOrderKey>
{
protected readonly QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> _source; // The data source to enumerate.
private readonly Func<TSource, TGroupKey> _keySelector; // The key selection routine.
protected readonly IEqualityComparer<TGroupKey>? _keyComparer; // The key comparison routine.
protected readonly IComparer<TOrderKey> _orderComparer; // The comparison routine for order keys.
protected readonly CancellationToken _cancellationToken;
private Mutables? _mutables; // All the mutable state.
private sealed class Mutables
{
internal HashLookup<Wrapper<TGroupKey>, GroupKeyData>? _hashLookup; // The lookup with key-value mappings.
internal int _hashLookupIndex; // The current index within the lookup.
}
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
protected OrderedGroupByQueryOperatorEnumerator(QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source,
Func<TSource, TGroupKey> keySelector, IEqualityComparer<TGroupKey>? keyComparer, IComparer<TOrderKey> orderComparer,
CancellationToken cancellationToken)
{
Debug.Assert(source != null);
Debug.Assert(keySelector != null);
_source = source;
_keySelector = keySelector;
_keyComparer = keyComparer;
_orderComparer = orderComparer;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// MoveNext will invoke the entire query sub-tree, accumulating results into a hash-
// table, upon the first call. Then for the first call and all subsequent calls, we will
// just enumerate the key-set from the hash-table, retrieving groupings of key-elements.
//
internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref IGrouping<TGroupKey, TElement> currentElement, [AllowNull] ref TOrderKey currentKey)
{
Debug.Assert(_source != null);
Debug.Assert(_keySelector != null);
// Lazy-init the mutable state. This also means we haven't yet built our lookup of
// groupings, so we can go ahead and do that too.
Mutables? mutables = _mutables;
if (mutables == null)
{
mutables = _mutables = new Mutables();
// Build the hash lookup and start enumerating the lookup at the beginning.
mutables._hashLookup = BuildHashLookup();
mutables._hashLookupIndex = -1;
}
Debug.Assert(mutables._hashLookup != null);
// Now, with a hash lookup in hand, we just enumerate the keys. So long
// as the key-value lookup has elements, we have elements.
if (++mutables._hashLookupIndex < mutables._hashLookup.Count)
{
GroupKeyData value = mutables._hashLookup[mutables._hashLookupIndex].Value;
currentElement = value._grouping;
currentKey = value._orderKey;
return true;
}
return false;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected abstract HashLookup<Wrapper<TGroupKey>, GroupKeyData> BuildHashLookup();
protected override void Dispose(bool disposing)
{
_source.Dispose();
}
//-----------------------------------------------------------------------------------
// A data structure that holds information about elements with a particular key.
//
// This information includes two parts:
// - An order key for the grouping.
// - The grouping itself. The grouping consists of elements and the grouping key.
//
protected sealed class GroupKeyData
{
internal TOrderKey _orderKey;
internal OrderedGroupByGrouping<TGroupKey, TOrderKey, TElement> _grouping;
internal GroupKeyData(TOrderKey orderKey, TGroupKey hashKey, IComparer<TOrderKey> orderComparer)
{
_orderKey = orderKey;
_grouping = new OrderedGroupByGrouping<TGroupKey, TOrderKey, TElement>(hashKey, orderComparer);
}
}
}
//---------------------------------------------------------------------------------------
// A specialization of the ordered GroupBy enumerator for yielding elements with the identity
// function.
//
internal sealed class OrderedGroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TOrderKey> :
OrderedGroupByQueryOperatorEnumerator<TSource, TGroupKey, TSource, TOrderKey>
{
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal OrderedGroupByIdentityQueryOperatorEnumerator(QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source,
Func<TSource, TGroupKey> keySelector, IEqualityComparer<TGroupKey>? keyComparer, IComparer<TOrderKey> orderComparer,
CancellationToken cancellationToken)
: base(source, keySelector, keyComparer, orderComparer, cancellationToken)
{
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, GroupKeyData> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, GroupKeyData> hashLookup = new HashLookup<Wrapper<TGroupKey>, GroupKeyData>(
new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair<TSource, TGroupKey> sourceElement = default(Pair<TSource, TGroupKey>);
TOrderKey sourceOrderKey = default(TOrderKey)!;
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceOrderKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
_cancellationToken.ThrowIfCancellationRequested();
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>(sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
GroupKeyData? currentValue = null;
if (hashLookup.TryGetValue(key, ref currentValue))
{
if (_orderComparer.Compare(sourceOrderKey, currentValue._orderKey) < 0)
{
currentValue._orderKey = sourceOrderKey;
}
}
else
{
currentValue = new GroupKeyData(sourceOrderKey, key.Value, _orderComparer);
hashLookup.Add(key, currentValue);
}
Debug.Assert(currentValue != null);
currentValue._grouping.Add(sourceElement.First, sourceOrderKey);
}
// Sort the elements within each group
for (int j = 0; j < hashLookup.Count; j++)
{
hashLookup[j].Value._grouping.DoneAdding();
}
return hashLookup;
}
}
//---------------------------------------------------------------------------------------
// A specialization of the ordered GroupBy enumerator for yielding elements with any arbitrary
// element selection function.
//
internal sealed class OrderedGroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
OrderedGroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey>
{
private readonly Func<TSource, TElement> _elementSelector; // Function to select elements.
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal OrderedGroupByElementSelectorQueryOperatorEnumerator(QueryOperatorEnumerator<Pair<TSource, TGroupKey>, TOrderKey> source,
Func<TSource, TGroupKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TGroupKey>? keyComparer, IComparer<TOrderKey> orderComparer,
CancellationToken cancellationToken) :
base(source, keySelector, keyComparer, orderComparer, cancellationToken)
{
Debug.Assert(elementSelector != null);
_elementSelector = elementSelector;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, GroupKeyData> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, GroupKeyData> hashLookup = new HashLookup<Wrapper<TGroupKey>, GroupKeyData>(
new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair<TSource, TGroupKey> sourceElement = default(Pair<TSource, TGroupKey>);
TOrderKey sourceOrderKey = default(TOrderKey)!;
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceOrderKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
_cancellationToken.ThrowIfCancellationRequested();
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>(sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
GroupKeyData? currentValue = null;
if (hashLookup.TryGetValue(key, ref currentValue))
{
if (_orderComparer.Compare(sourceOrderKey, currentValue._orderKey) < 0)
{
currentValue._orderKey = sourceOrderKey;
}
}
else
{
currentValue = new GroupKeyData(sourceOrderKey, key.Value, _orderComparer);
hashLookup.Add(key, currentValue);
}
Debug.Assert(currentValue != null);
// Call to the base class to yield the current value.
currentValue._grouping.Add(_elementSelector(sourceElement.First), sourceOrderKey);
}
// Sort the elements within each group
for (int j = 0; j < hashLookup.Count; j++)
{
hashLookup[j].Value._grouping.DoneAdding();
}
return hashLookup;
}
}
//---------------------------------------------------------------------------------------
// This little type implements the IGrouping<K,T> interface, and exposes a single
// key-to-many-values mapping.
//
internal sealed class GroupByGrouping<TGroupKey, TElement> : IGrouping<TGroupKey, TElement>
{
private readonly KeyValuePair<Wrapper<TGroupKey>, ListChunk<TElement>> _keyValues; // A key value pair.
//---------------------------------------------------------------------------------------
// Constructs a new grouping out of the key value pair.
//
internal GroupByGrouping(KeyValuePair<Wrapper<TGroupKey>, ListChunk<TElement>> keyValues)
{
Debug.Assert(keyValues.Value != null);
_keyValues = keyValues;
}
//---------------------------------------------------------------------------------------
// The key this mapping represents.
//
TGroupKey IGrouping<TGroupKey, TElement>.Key
{
get
{
return _keyValues.Key.Value;
}
}
//---------------------------------------------------------------------------------------
// Access to value enumerators.
//
IEnumerator<TElement> IEnumerable<TElement>.GetEnumerator()
{
Debug.Assert(_keyValues.Value != null);
return _keyValues.Value.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<TElement>)this).GetEnumerator();
}
}
/// <summary>
/// An ordered version of the grouping data structure. Represents an ordered group of elements that
/// have the same grouping key.
/// </summary>
internal sealed class OrderedGroupByGrouping<TGroupKey, TOrderKey, TElement> : IGrouping<TGroupKey, TElement>
{
private const int INITIAL_CHUNK_SIZE = 2;
private readonly TGroupKey _groupKey; // The group key for this grouping
private ListChunk<Pair<TOrderKey, TElement>>? _values; // Values in this group
private TElement[]? _sortedValues; // Sorted values (allocated in DoneAdding)
private readonly IComparer<TOrderKey> _orderComparer; // Comparer for order keys
/// <summary>
/// Constructs a new grouping
/// </summary>
internal OrderedGroupByGrouping(
TGroupKey groupKey,
IComparer<TOrderKey> orderComparer)
{
_groupKey = groupKey;
_values = new ListChunk<Pair<TOrderKey, TElement>>(INITIAL_CHUNK_SIZE);
_orderComparer = orderComparer;
}
/// <summary>
/// The key this grouping represents.
/// </summary>
TGroupKey IGrouping<TGroupKey, TElement>.Key
{
get
{
return _groupKey;
}
}
IEnumerator<TElement> IEnumerable<TElement>.GetEnumerator()
{
Debug.Assert(_sortedValues != null);
return ((IEnumerable<TElement>)_sortedValues).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<TElement>)this).GetEnumerator();
}
/// <summary>
/// Add an element
/// </summary>
internal void Add(TElement value, TOrderKey orderKey)
{
Debug.Assert(_values != null);
_values.Add(new Pair<TOrderKey, TElement>(orderKey, value));
}
/// <summary>
/// No more elements will be added, so we can sort the group now.
/// </summary>
internal void DoneAdding()
{
Debug.Assert(_values != null);
int count = _values.Count;
ListChunk<Pair<TOrderKey, TElement>>? curChunk = _values;
while ((curChunk = curChunk.Next) != null)
{
count += curChunk.Count;
}
TElement[] values = new TElement[count];
TOrderKey[] orderKeys = new TOrderKey[count];
int idx = 0;
foreach (Pair<TOrderKey, TElement> p in _values)
{
orderKeys[idx] = p.First;
values[idx] = p.Second;
idx++;
}
Array.Sort(orderKeys, values, _orderComparer);
_sortedValues = values;
#if DEBUG
_values = null; // Any future calls to Add() or DoneAdding() will fail
#endif
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Private.Xml/tests/Readers/ReaderSettings/TCMaxSettings.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using OLEDB.Test.ModuleCore;
namespace System.Xml.Tests
{
public partial class TCMaxSettings : TCXMLReaderBaseGeneral
{
// Type is XmlReaderTest.Common.TCMaxSettings
// Test Case
public override void AddChildren()
{
// for function v1
{
this.AddChild(new CVariation(v1) { Attribute = new Variation("MaxSettings: get default values") { Pri = 0 } });
}
// for function v2
{
this.AddChild(new CVariation(v2) { Attribute = new Variation("MaxSettings: set, get values") { Pri = 0 } });
}
// for function v3
{
this.AddChild(new CVariation(v3) { Attribute = new Variation("MaxSettings: set negative, get default values, set 10 and get 10") { Pri = 2 } });
}
// for function v9
{
this.AddChild(new CVariation(v9) { Attribute = new Variation("MaxCharactersFromEntities: set negative values, get default") { Param = 1, Pri = 2 } });
this.AddChild(new CVariation(v9) { Attribute = new Variation("MaxCharactersFromEntities: set max negative values, get default") { Param = 2, Pri = 2 } });
}
// for function v10
{
this.AddChild(new CVariation(v10) { Attribute = new Variation("MaxCharactersInDocument: set negative values, get default") { Param = 1, Pri = 2 } });
this.AddChild(new CVariation(v10) { Attribute = new Variation("MaxCharactersInDocument: set huge negative values, get default") { Param = 2, Pri = 2 } });
}
// for function v20
{
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<Root foo='& < > " ' A'/>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<A>truck</A>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<Root><!--\ud812\udd12--></Root>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<Root>񘍁<Elem>󏹄</Elem>𘀢</Root>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<X>t0<A>truck</A>t00</X>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<a:A xmlns:a='a'><C xmlns:p='nsc' /><B /></a:A>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<A xmlns:p='nsc'><p:C xmlns:a='a'><a:S /></p:C><B /></A>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<A xmlns='ns0'><![CDATA[tralala]]></A>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<A xmlns='ns0'><![CDATA[ja_a_hele]]><?PI?><X />text<Y /></A>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<A attr='1' a2='a2' a3='a3' xmlns='def' xmlns:p='ns' p:a3='pa3' />" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<!DOCTYPE doc [ <!ELEMENT doc ANY> <!ENTITY book 'a&a'>]><doc>&book;</doc>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<!DOCTYPE doc [ <!ELEMENT doc ANY> <!ENTITY book 'a%a'>]><doc>&book;</doc> " }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<?xml version='1.0'?><!DOCTYPE test [ <!ELEMENT test ANY> <!ELEMENT a ANY> <!ELEMENT b ANY> <!ELEMENT c ANY> <!ENTITY a '<a>&a;</a>'>]><test>&a;</test>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<!DOCTYPE ROOT [<!ENTITY a '&a;'>]><ROOT att='&a;'/>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<!DOCTYPE root [<!ELEMENT root ANY><!ENTITY e '\ud812\udd12'>]><root>&e;</root>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<!DOCTYPE root[<!ENTITY x 'somevalue'><!ELEMENT root ANY>]><root>value&x;</root>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<root>va</root>lue</root>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<Root a='&' b='&#65;' c='&#x43;' />" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<Root a='b"c' />" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<A />" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<Root a=' 	
' />" }, Pri = 2 } });
}
// for function v30
{
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<Root a='b"c' />" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<root>va</root>lue</root>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<Root a=' 	
' />" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<Root foo='& < > " ' A'/>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<Root a='&' b='&#65;' c='&#x43;' />" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<A />" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<A>truck</A>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<Root><!--\ud812\udd12--></Root>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<Root>񘍁<Elem>󏹄</Elem>𘀢</Root>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<X>t0<A>truck</A>t00</X>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<a:A xmlns:a='a'><C xmlns:p='nsc' /><B /></a:A>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<A xmlns:p='nsc'><p:C xmlns:a='a'><a:S /></p:C><B /></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<A xmlns='ns0'><![CDATA[tralala]]></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<A xmlns='ns0'><![CDATA[ja_a_hele]]><?PI?><X />text<Y /></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<A attr='1' a2='a2' a3='a3' xmlns='def' xmlns:p='ns' p:a3='pa3' />" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<!DOCTYPE root[<!ENTITY x 'somevalue'><!ELEMENT root ANY>]><root>value&x;</root>" }, Pri = 0 } });
}
// for function v40
{
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<Root a='b"c' />" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<Root a=' 	
' />" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<Root foo='& < > " ' A'/>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<X>t0<A>truck</A>t00</X>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<A>truck</A>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<Root><!--\ud812\udd12--></Root>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<Root>񘍁<Elem>󏹄</Elem>𘀢</Root>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<a:A xmlns:a='a'><C xmlns:p='nsc' /><B /></a:A>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<A xmlns:p='nsc'><p:C xmlns:a='a'><a:S /></p:C><B /></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<A xmlns='ns0'><![CDATA[tralala]]></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<A xmlns='ns0'><![CDATA[ja_a_hele]]><?PI?><X />text<Y /></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<A attr='1' a2='a2' a3='a3' xmlns='def' xmlns:p='ns' p:a3='pa3' />" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<!DOCTYPE root[<!ENTITY x 'somevalue'><!ELEMENT root ANY>]><root>value&x;</root>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<root>va</root>lue</root>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<Root a='&' b='&#65;' c='&#x43;' />" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<A />" }, Pri = 0 } });
}
// for function v50
{
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<Root><!--\ud812\udd12--></Root>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<Root foo='& < > " ' A'/>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<A />" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<A>truck</A>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<Root>񘍁<Elem>󏹄</Elem>𘀢</Root>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<X>t0<A>truck</A>t00</X>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<a:A xmlns:a='a'><C xmlns:p='nsc' /><B /></a:A>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<A xmlns:p='nsc'><p:C xmlns:a='a'><a:S /></p:C><B /></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<A xmlns='ns0'><![CDATA[tralala]]></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<A xmlns='ns0'><![CDATA[ja_a_hele]]><?PI?><X />text<Y /></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<A attr='1' a2='a2' a3='a3' xmlns='def' xmlns:p='ns' p:a3='pa3' />" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<!DOCTYPE root[<!ENTITY x 'somevalue'><!ELEMENT root ANY>]><root>value&x;</root>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<root>va</root>lue</root>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<Root a='&' b='&#65;' c='&#x43;' />" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<Root a='b"c' />" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<Root a=' 	
' />" }, Pri = 0 } });
}
// for function v60
{
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<root>va</root>lue</root>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<A attr='1' a2='a2' a3='a3' xmlns='def' xmlns:p='ns' p:a3='pa3' />" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<A />" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<A>truck</A>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<Root><!--\ud812\udd12--></Root>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<Root>񘍁<Elem>󏹄</Elem>𘀢</Root>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<!DOCTYPE root[<!ENTITY x 'somevalue'><!ELEMENT root ANY>]><root>value&x;</root>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<a:A xmlns:a='a'><C xmlns:p='nsc' /><B /></a:A>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<A xmlns:p='nsc'><p:C xmlns:a='a'><a:S /></p:C><B /></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<A xmlns='ns0'><![CDATA[tralala]]></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<Root a='&' b='&#65;' c='&#x43;' />" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<A xmlns='ns0'><![CDATA[ja_a_hele]]><?PI?><X />text<Y /></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<Root a='b"c' />" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<Root a=' 	
' />" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<Root foo='& < > " ' A'/>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<X>t0<A>truck</A>t00</X>" }, Pri = 0 } });
}
// for function v260
{
this.AddChild(new CVariation(v260) { Attribute = new Variation("nwf xml: MaxEnt = bigVal, MaxDoc = bigVal") { Params = new object[] { "" }, Pri = 2 } });
this.AddChild(new CVariation(v260) { Attribute = new Variation("nwf xml: MaxEnt = bigVal, MaxDoc = bigVal") { Params = new object[] { "<root><!--comment \ufffd\ufffd><!--comment \ufffd\ufffd>-->--></root>" }, Pri = 2 } });
this.AddChild(new CVariation(v260) { Attribute = new Variation("nwf xml: MaxEnt = bigVal, MaxDoc = bigVal") { Params = new object[] { string.Format("<!-- http://www.w3.org is bound to n1 and n2 -->{0}<x xmlns:n1=\"http://www.w3.org\"{0} xmlns:n2=\"http://www.w3.org\" >{0} <bad n1:a=\"1\" n2:a=\"2\" /></x>", Environment.NewLine) }, Pri = 2 } });
this.AddChild(new CVariation(v260) { Attribute = new Variation("nwf xml: MaxEnt = bigVal, MaxDoc = bigVal") { Params = new object[] { "<!DOCTYPE ROOT [<!ENTITY a '&a;'>]><ROOT att='&a;'/>" }, Pri = 2 } });
this.AddChild(new CVariation(v260) { Attribute = new Variation("nwf xml: MaxEnt = bigVal, MaxDoc = bigVal") { Params = new object[] { "<?xml version='1.0'?><!DOCTYPE test [ <!ELEMENT test ANY> <!ELEMENT a ANY> <!ELEMENT b ANY> <!ELEMENT c ANY> <!ENTITY a '<a>&a;</a>'>]><test>&a;</test>" }, Pri = 2 } });
this.AddChild(new CVariation(v260) { Attribute = new Variation("nwf xml: MaxEnt = bigVal, MaxDoc = bigVal") { Params = new object[] { "<?xml version='1.0'?><!DOCTYPE test [ <!ELEMENT test ANY> <!ELEMENT a ANY> <!ELEMENT b ANY> <!ELEMENT c ANY> <!ENTITY a '<a>&</a>'>]><test>&a;<test>" }, Pri = 2 } });
this.AddChild(new CVariation(v260) { Attribute = new Variation("nwf xml: MaxEnt = bigVal, MaxDoc = bigVal") { Params = new object[] { "<q = 'a'/>" }, Pri = 2 } });
}
// for function v270
{
this.AddChild(new CVariation(v270) { Attribute = new Variation("nwf xml: MaxEnt = 1, MaxDoc = val") { Params = new object[] { "<!DOCTYPE ROOT [<!ENTITY a '&a;'>]><ROOT att='&a;'/>", 10 }, Pri = 2 } });
this.AddChild(new CVariation(v270) { Attribute = new Variation("nwf xml: MaxEnt = 1, MaxDoc = val") { Params = new object[] { "<q = 'a'/>", 5 }, Pri = 2 } });
this.AddChild(new CVariation(v270) { Attribute = new Variation("nwf xml: MaxEnt = 1, MaxDoc = val") { Params = new object[] { "<?xml version='1.0'?><!DOCTYPE test [ <!ELEMENT test ANY> <!ELEMENT a ANY> <!ELEMENT b ANY> <!ELEMENT c ANY> <!ENTITY a '<a>&a;</a>'>]><test>&a;</test>", 25 }, Pri = 2 } });
this.AddChild(new CVariation(v270) { Attribute = new Variation("nwf xml: MaxEnt = 1, MaxDoc = val") { Params = new object[] { "<?xml version='1.0'?><!DOCTYPE test [ <!ELEMENT test ANY> <!ELEMENT a ANY> <!ELEMENT b ANY> <!ELEMENT c ANY> <!ENTITY a '<a>&</a>'>]><test>&a;<test>", 26 }, Pri = 2 } });
this.AddChild(new CVariation(v270) { Attribute = new Variation("nwf xml: MaxEnt = 1, MaxDoc = val") { Params = new object[] { "<root><!--comment \ufffd\ufffd><!--comment \ufffd\ufffd>-->--></root>", 18 }, Pri = 2 } });
this.AddChild(new CVariation(v270) { Attribute = new Variation("nwf xml: MaxEnt = 1, MaxDoc = val") { Params = new object[] { string.Format("<!-- http://www.w3.org is bound to n1 and n2 -->{0}<x xmlns:n1=\"http://www.w3.org\"{0} xmlns:n2=\"http://www.w3.org\" >{0} <bad n1:a=\"1\" n2:a=\"2\" /></x>", Environment.NewLine), 35 }, Pri = 2 } });
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using OLEDB.Test.ModuleCore;
namespace System.Xml.Tests
{
public partial class TCMaxSettings : TCXMLReaderBaseGeneral
{
// Type is XmlReaderTest.Common.TCMaxSettings
// Test Case
public override void AddChildren()
{
// for function v1
{
this.AddChild(new CVariation(v1) { Attribute = new Variation("MaxSettings: get default values") { Pri = 0 } });
}
// for function v2
{
this.AddChild(new CVariation(v2) { Attribute = new Variation("MaxSettings: set, get values") { Pri = 0 } });
}
// for function v3
{
this.AddChild(new CVariation(v3) { Attribute = new Variation("MaxSettings: set negative, get default values, set 10 and get 10") { Pri = 2 } });
}
// for function v9
{
this.AddChild(new CVariation(v9) { Attribute = new Variation("MaxCharactersFromEntities: set negative values, get default") { Param = 1, Pri = 2 } });
this.AddChild(new CVariation(v9) { Attribute = new Variation("MaxCharactersFromEntities: set max negative values, get default") { Param = 2, Pri = 2 } });
}
// for function v10
{
this.AddChild(new CVariation(v10) { Attribute = new Variation("MaxCharactersInDocument: set negative values, get default") { Param = 1, Pri = 2 } });
this.AddChild(new CVariation(v10) { Attribute = new Variation("MaxCharactersInDocument: set huge negative values, get default") { Param = 2, Pri = 2 } });
}
// for function v20
{
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<Root foo='& < > " ' A'/>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<A>truck</A>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<Root><!--\ud812\udd12--></Root>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<Root>񘍁<Elem>󏹄</Elem>𘀢</Root>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<X>t0<A>truck</A>t00</X>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<a:A xmlns:a='a'><C xmlns:p='nsc' /><B /></a:A>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<A xmlns:p='nsc'><p:C xmlns:a='a'><a:S /></p:C><B /></A>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<A xmlns='ns0'><![CDATA[tralala]]></A>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<A xmlns='ns0'><![CDATA[ja_a_hele]]><?PI?><X />text<Y /></A>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<A attr='1' a2='a2' a3='a3' xmlns='def' xmlns:p='ns' p:a3='pa3' />" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<!DOCTYPE doc [ <!ELEMENT doc ANY> <!ENTITY book 'a&a'>]><doc>&book;</doc>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<!DOCTYPE doc [ <!ELEMENT doc ANY> <!ENTITY book 'a%a'>]><doc>&book;</doc> " }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<?xml version='1.0'?><!DOCTYPE test [ <!ELEMENT test ANY> <!ELEMENT a ANY> <!ELEMENT b ANY> <!ELEMENT c ANY> <!ENTITY a '<a>&a;</a>'>]><test>&a;</test>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<!DOCTYPE ROOT [<!ENTITY a '&a;'>]><ROOT att='&a;'/>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<!DOCTYPE root [<!ELEMENT root ANY><!ENTITY e '\ud812\udd12'>]><root>&e;</root>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<!DOCTYPE root[<!ENTITY x 'somevalue'><!ELEMENT root ANY>]><root>value&x;</root>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<root>va</root>lue</root>" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<Root a='&' b='&#65;' c='&#x43;' />" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<Root a='b"c' />" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<A />" }, Pri = 2 } });
this.AddChild(new CVariation(v20) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length - 1") { Params = new object[] { "<Root a=' 	
' />" }, Pri = 2 } });
}
// for function v30
{
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<Root a='b"c' />" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<root>va</root>lue</root>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<Root a=' 	
' />" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<Root foo='& < > " ' A'/>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<Root a='&' b='&#65;' c='&#x43;' />" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<A />" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<A>truck</A>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<Root><!--\ud812\udd12--></Root>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<Root>񘍁<Elem>󏹄</Elem>𘀢</Root>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<X>t0<A>truck</A>t00</X>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<a:A xmlns:a='a'><C xmlns:p='nsc' /><B /></a:A>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<A xmlns:p='nsc'><p:C xmlns:a='a'><a:S /></p:C><B /></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<A xmlns='ns0'><![CDATA[tralala]]></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<A xmlns='ns0'><![CDATA[ja_a_hele]]><?PI?><X />text<Y /></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<A attr='1' a2='a2' a3='a3' xmlns='def' xmlns:p='ns' p:a3='pa3' />" }, Pri = 0 } });
this.AddChild(new CVariation(v30) { Attribute = new Variation("MaxEnt not set, MaxDoc = length") { Params = new object[] { "<!DOCTYPE root[<!ENTITY x 'somevalue'><!ELEMENT root ANY>]><root>value&x;</root>" }, Pri = 0 } });
}
// for function v40
{
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<Root a='b"c' />" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<Root a=' 	
' />" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<Root foo='& < > " ' A'/>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<X>t0<A>truck</A>t00</X>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<A>truck</A>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<Root><!--\ud812\udd12--></Root>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<Root>񘍁<Elem>󏹄</Elem>𘀢</Root>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<a:A xmlns:a='a'><C xmlns:p='nsc' /><B /></a:A>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<A xmlns:p='nsc'><p:C xmlns:a='a'><a:S /></p:C><B /></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<A xmlns='ns0'><![CDATA[tralala]]></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<A xmlns='ns0'><![CDATA[ja_a_hele]]><?PI?><X />text<Y /></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<A attr='1' a2='a2' a3='a3' xmlns='def' xmlns:p='ns' p:a3='pa3' />" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<!DOCTYPE root[<!ENTITY x 'somevalue'><!ELEMENT root ANY>]><root>value&x;</root>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<root>va</root>lue</root>" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<Root a='&' b='&#65;' c='&#x43;' />" }, Pri = 0 } });
this.AddChild(new CVariation(v40) { Attribute = new Variation("MaxEnt = 1, MaxDoc = length") { Params = new object[] { "<A />" }, Pri = 0 } });
}
// for function v50
{
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<Root><!--\ud812\udd12--></Root>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<Root foo='& < > " ' A'/>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<A />" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<A>truck</A>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<Root>񘍁<Elem>󏹄</Elem>𘀢</Root>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<X>t0<A>truck</A>t00</X>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<a:A xmlns:a='a'><C xmlns:p='nsc' /><B /></a:A>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<A xmlns:p='nsc'><p:C xmlns:a='a'><a:S /></p:C><B /></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<A xmlns='ns0'><![CDATA[tralala]]></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<A xmlns='ns0'><![CDATA[ja_a_hele]]><?PI?><X />text<Y /></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<A attr='1' a2='a2' a3='a3' xmlns='def' xmlns:p='ns' p:a3='pa3' />" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<!DOCTYPE root[<!ENTITY x 'somevalue'><!ELEMENT root ANY>]><root>value&x;</root>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<root>va</root>lue</root>" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<Root a='&' b='&#65;' c='&#x43;' />" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<Root a='b"c' />" }, Pri = 0 } });
this.AddChild(new CVariation(v50) { Attribute = new Variation("MaxEnt = 0, MaxDoc = 0") { Params = new object[] { "<Root a=' 	
' />" }, Pri = 0 } });
}
// for function v60
{
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<root>va</root>lue</root>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<A attr='1' a2='a2' a3='a3' xmlns='def' xmlns:p='ns' p:a3='pa3' />" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<A />" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<A>truck</A>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<Root><!--\ud812\udd12--></Root>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<Root>񘍁<Elem>󏹄</Elem>𘀢</Root>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<!DOCTYPE root[<!ENTITY x 'somevalue'><!ELEMENT root ANY>]><root>value&x;</root>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<a:A xmlns:a='a'><C xmlns:p='nsc' /><B /></a:A>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<A xmlns:p='nsc'><p:C xmlns:a='a'><a:S /></p:C><B /></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<A xmlns='ns0'><![CDATA[tralala]]></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<Root a='&' b='&#65;' c='&#x43;' />" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<A xmlns='ns0'><![CDATA[ja_a_hele]]><?PI?><X />text<Y /></A>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<Root a='b"c' />" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<Root a=' 	
' />" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<Root foo='& < > " ' A'/>" }, Pri = 0 } });
this.AddChild(new CVariation(v60) { Attribute = new Variation("MaxEnt not set, MaxDoc not set") { Params = new object[] { "<X>t0<A>truck</A>t00</X>" }, Pri = 0 } });
}
// for function v260
{
this.AddChild(new CVariation(v260) { Attribute = new Variation("nwf xml: MaxEnt = bigVal, MaxDoc = bigVal") { Params = new object[] { "" }, Pri = 2 } });
this.AddChild(new CVariation(v260) { Attribute = new Variation("nwf xml: MaxEnt = bigVal, MaxDoc = bigVal") { Params = new object[] { "<root><!--comment \ufffd\ufffd><!--comment \ufffd\ufffd>-->--></root>" }, Pri = 2 } });
this.AddChild(new CVariation(v260) { Attribute = new Variation("nwf xml: MaxEnt = bigVal, MaxDoc = bigVal") { Params = new object[] { string.Format("<!-- http://www.w3.org is bound to n1 and n2 -->{0}<x xmlns:n1=\"http://www.w3.org\"{0} xmlns:n2=\"http://www.w3.org\" >{0} <bad n1:a=\"1\" n2:a=\"2\" /></x>", Environment.NewLine) }, Pri = 2 } });
this.AddChild(new CVariation(v260) { Attribute = new Variation("nwf xml: MaxEnt = bigVal, MaxDoc = bigVal") { Params = new object[] { "<!DOCTYPE ROOT [<!ENTITY a '&a;'>]><ROOT att='&a;'/>" }, Pri = 2 } });
this.AddChild(new CVariation(v260) { Attribute = new Variation("nwf xml: MaxEnt = bigVal, MaxDoc = bigVal") { Params = new object[] { "<?xml version='1.0'?><!DOCTYPE test [ <!ELEMENT test ANY> <!ELEMENT a ANY> <!ELEMENT b ANY> <!ELEMENT c ANY> <!ENTITY a '<a>&a;</a>'>]><test>&a;</test>" }, Pri = 2 } });
this.AddChild(new CVariation(v260) { Attribute = new Variation("nwf xml: MaxEnt = bigVal, MaxDoc = bigVal") { Params = new object[] { "<?xml version='1.0'?><!DOCTYPE test [ <!ELEMENT test ANY> <!ELEMENT a ANY> <!ELEMENT b ANY> <!ELEMENT c ANY> <!ENTITY a '<a>&</a>'>]><test>&a;<test>" }, Pri = 2 } });
this.AddChild(new CVariation(v260) { Attribute = new Variation("nwf xml: MaxEnt = bigVal, MaxDoc = bigVal") { Params = new object[] { "<q = 'a'/>" }, Pri = 2 } });
}
// for function v270
{
this.AddChild(new CVariation(v270) { Attribute = new Variation("nwf xml: MaxEnt = 1, MaxDoc = val") { Params = new object[] { "<!DOCTYPE ROOT [<!ENTITY a '&a;'>]><ROOT att='&a;'/>", 10 }, Pri = 2 } });
this.AddChild(new CVariation(v270) { Attribute = new Variation("nwf xml: MaxEnt = 1, MaxDoc = val") { Params = new object[] { "<q = 'a'/>", 5 }, Pri = 2 } });
this.AddChild(new CVariation(v270) { Attribute = new Variation("nwf xml: MaxEnt = 1, MaxDoc = val") { Params = new object[] { "<?xml version='1.0'?><!DOCTYPE test [ <!ELEMENT test ANY> <!ELEMENT a ANY> <!ELEMENT b ANY> <!ELEMENT c ANY> <!ENTITY a '<a>&a;</a>'>]><test>&a;</test>", 25 }, Pri = 2 } });
this.AddChild(new CVariation(v270) { Attribute = new Variation("nwf xml: MaxEnt = 1, MaxDoc = val") { Params = new object[] { "<?xml version='1.0'?><!DOCTYPE test [ <!ELEMENT test ANY> <!ELEMENT a ANY> <!ELEMENT b ANY> <!ELEMENT c ANY> <!ENTITY a '<a>&</a>'>]><test>&a;<test>", 26 }, Pri = 2 } });
this.AddChild(new CVariation(v270) { Attribute = new Variation("nwf xml: MaxEnt = 1, MaxDoc = val") { Params = new object[] { "<root><!--comment \ufffd\ufffd><!--comment \ufffd\ufffd>-->--></root>", 18 }, Pri = 2 } });
this.AddChild(new CVariation(v270) { Attribute = new Variation("nwf xml: MaxEnt = 1, MaxDoc = val") { Params = new object[] { string.Format("<!-- http://www.w3.org is bound to n1 and n2 -->{0}<x xmlns:n1=\"http://www.w3.org\"{0} xmlns:n2=\"http://www.w3.org\" >{0} <bad n1:a=\"1\" n2:a=\"2\" /></x>", Environment.NewLine), 35 }, Pri = 2 } });
}
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/WarpMode.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Drawing.Drawing2D
{
public enum WarpMode
{
Perspective = 0,
Bilinear = 1
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Drawing.Drawing2D
{
public enum WarpMode
{
Perspective = 0,
Bilinear = 1
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LogLevel.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
{
/// <summary>
/// Defines logging severity levels.
/// </summary>
public enum LogLevel
{
/// <summary>
/// Logs that contain the most detailed messages. These messages may contain sensitive application data.
/// These messages are disabled by default and should never be enabled in a production environment.
/// </summary>
Trace = 0,
/// <summary>
/// Logs that are used for interactive investigation during development. These logs should primarily contain
/// information useful for debugging and have no long-term value.
/// </summary>
Debug = 1,
/// <summary>
/// Logs that track the general flow of the application. These logs should have long-term value.
/// </summary>
Information = 2,
/// <summary>
/// Logs that highlight an abnormal or unexpected event in the application flow, but do not otherwise cause the
/// application execution to stop.
/// </summary>
Warning = 3,
/// <summary>
/// Logs that highlight when the current flow of execution is stopped due to a failure. These should indicate a
/// failure in the current activity, not an application-wide failure.
/// </summary>
Error = 4,
/// <summary>
/// Logs that describe an unrecoverable application or system crash, or a catastrophic failure that requires
/// immediate attention.
/// </summary>
Critical = 5,
/// <summary>
/// Not used for writing log messages. Specifies that a logging category should not write any messages.
/// </summary>
None = 6,
}
}
|
// 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
{
/// <summary>
/// Defines logging severity levels.
/// </summary>
public enum LogLevel
{
/// <summary>
/// Logs that contain the most detailed messages. These messages may contain sensitive application data.
/// These messages are disabled by default and should never be enabled in a production environment.
/// </summary>
Trace = 0,
/// <summary>
/// Logs that are used for interactive investigation during development. These logs should primarily contain
/// information useful for debugging and have no long-term value.
/// </summary>
Debug = 1,
/// <summary>
/// Logs that track the general flow of the application. These logs should have long-term value.
/// </summary>
Information = 2,
/// <summary>
/// Logs that highlight an abnormal or unexpected event in the application flow, but do not otherwise cause the
/// application execution to stop.
/// </summary>
Warning = 3,
/// <summary>
/// Logs that highlight when the current flow of execution is stopped due to a failure. These should indicate a
/// failure in the current activity, not an application-wide failure.
/// </summary>
Error = 4,
/// <summary>
/// Logs that describe an unrecoverable application or system crash, or a catastrophic failure that requires
/// immediate attention.
/// </summary>
Critical = 5,
/// <summary>
/// Not used for writing log messages. Specifies that a logging category should not write any messages.
/// </summary>
None = 6,
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Diagnostics.Debug/tests/EmptyAttributeTests.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.Diagnostics.Tests
{
public class EmptyAttributeTests
{
[Fact]
public void Ctor_Default_DoesNotThrow()
{
new DebuggerStepperBoundaryAttribute();
new DebuggerHiddenAttribute();
new DebuggerNonUserCodeAttribute();
new DebuggerStepThroughAttribute();
}
}
}
|
// 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.Diagnostics.Tests
{
public class EmptyAttributeTests
{
[Fact]
public void Ctor_Default_DoesNotThrow()
{
new DebuggerStepperBoundaryAttribute();
new DebuggerHiddenAttribute();
new DebuggerNonUserCodeAttribute();
new DebuggerStepThroughAttribute();
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/CoffHeader.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Reflection.PortableExecutable
{
public sealed class CoffHeader
{
/// <summary>
/// The type of target machine.
/// </summary>
public Machine Machine { get; }
/// <summary>
/// The number of sections. This indicates the size of the section table, which immediately follows the headers.
/// </summary>
public short NumberOfSections { get; }
/// <summary>
/// The low 32 bits of the number of seconds since 00:00 January 1, 1970, that indicates when the file was created.
/// </summary>
public int TimeDateStamp { get; }
/// <summary>
/// The file pointer to the COFF symbol table, or zero if no COFF symbol table is present.
/// This value should be zero for a PE image.
/// </summary>
public int PointerToSymbolTable { get; }
/// <summary>
/// The number of entries in the symbol table. This data can be used to locate the string table,
/// which immediately follows the symbol table. This value should be zero for a PE image.
/// </summary>
public int NumberOfSymbols { get; }
/// <summary>
/// The size of the optional header, which is required for executable files but not for object files.
/// This value should be zero for an object file.
/// </summary>
public short SizeOfOptionalHeader { get; }
/// <summary>
/// The flags that indicate the attributes of the file.
/// </summary>
public Characteristics Characteristics { get; }
internal const int Size =
sizeof(short) + // Machine
sizeof(short) + // NumberOfSections
sizeof(int) + // TimeDateStamp:
sizeof(int) + // PointerToSymbolTable
sizeof(int) + // NumberOfSymbols
sizeof(short) + // SizeOfOptionalHeader:
sizeof(ushort); // Characteristics
internal CoffHeader(ref PEBinaryReader reader)
{
Machine = (Machine)reader.ReadUInt16();
NumberOfSections = reader.ReadInt16();
TimeDateStamp = reader.ReadInt32();
PointerToSymbolTable = reader.ReadInt32();
NumberOfSymbols = reader.ReadInt32();
SizeOfOptionalHeader = reader.ReadInt16();
Characteristics = (Characteristics)reader.ReadUInt16();
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Reflection.PortableExecutable
{
public sealed class CoffHeader
{
/// <summary>
/// The type of target machine.
/// </summary>
public Machine Machine { get; }
/// <summary>
/// The number of sections. This indicates the size of the section table, which immediately follows the headers.
/// </summary>
public short NumberOfSections { get; }
/// <summary>
/// The low 32 bits of the number of seconds since 00:00 January 1, 1970, that indicates when the file was created.
/// </summary>
public int TimeDateStamp { get; }
/// <summary>
/// The file pointer to the COFF symbol table, or zero if no COFF symbol table is present.
/// This value should be zero for a PE image.
/// </summary>
public int PointerToSymbolTable { get; }
/// <summary>
/// The number of entries in the symbol table. This data can be used to locate the string table,
/// which immediately follows the symbol table. This value should be zero for a PE image.
/// </summary>
public int NumberOfSymbols { get; }
/// <summary>
/// The size of the optional header, which is required for executable files but not for object files.
/// This value should be zero for an object file.
/// </summary>
public short SizeOfOptionalHeader { get; }
/// <summary>
/// The flags that indicate the attributes of the file.
/// </summary>
public Characteristics Characteristics { get; }
internal const int Size =
sizeof(short) + // Machine
sizeof(short) + // NumberOfSections
sizeof(int) + // TimeDateStamp:
sizeof(int) + // PointerToSymbolTable
sizeof(int) + // NumberOfSymbols
sizeof(short) + // SizeOfOptionalHeader:
sizeof(ushort); // Characteristics
internal CoffHeader(ref PEBinaryReader reader)
{
Machine = (Machine)reader.ReadUInt16();
NumberOfSections = reader.ReadInt16();
TimeDateStamp = reader.ReadInt32();
PointerToSymbolTable = reader.ReadInt32();
NumberOfSymbols = reader.ReadInt32();
SizeOfOptionalHeader = reader.ReadInt16();
Characteristics = (Characteristics)reader.ReadUInt16();
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/OSGroups.json
|
{
"runtimes": {
"Unix" : {
},
"Browser" : {
},
"Linux": {
"#import": [
"Unix"
]
},
"OSX": {
"#import": [
"Unix"
]
},
"MacCatalyst": {
"#import": [
"iOS"
]
},
"iOS": {
"#import": [
"Unix"
]
},
"iOSSimulator": {
"#import": [
"iOS"
]
},
"tvOS": {
"#import": [
"Unix"
]
},
"tvOSSimulator": {
"#import": [
"tvOS"
]
},
"Android": {
"#import": [
"Linux"
]
},
"FreeBSD": {
"#import": [
"Unix"
]
},
"NetBSD": {
"#import": [
"Unix"
]
},
"illumos": {
"#import": [
"Unix"
]
},
"Solaris": {
"#import": [
"Unix"
]
}
}
}
|
{
"runtimes": {
"Unix" : {
},
"Browser" : {
},
"Linux": {
"#import": [
"Unix"
]
},
"OSX": {
"#import": [
"Unix"
]
},
"MacCatalyst": {
"#import": [
"iOS"
]
},
"iOS": {
"#import": [
"Unix"
]
},
"iOSSimulator": {
"#import": [
"iOS"
]
},
"tvOS": {
"#import": [
"Unix"
]
},
"tvOSSimulator": {
"#import": [
"tvOS"
]
},
"Android": {
"#import": [
"Linux"
]
},
"FreeBSD": {
"#import": [
"Unix"
]
},
"NetBSD": {
"#import": [
"Unix"
]
},
"illumos": {
"#import": [
"Unix"
]
},
"Solaris": {
"#import": [
"Unix"
]
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/Microsoft.Extensions.DependencyInjection.Specification.Tests/src/Fakes/FakeDisposeCallback.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
namespace Microsoft.Extensions.DependencyInjection.Specification.Fakes
{
public class FakeDisposeCallback
{
public List<object> Disposed { get; } = new List<object>();
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
namespace Microsoft.Extensions.DependencyInjection.Specification.Fakes
{
public class FakeDisposeCallback
{
public List<object> Disposed { get; } = new List<object>();
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/Interop/COM/NativeClients/DefaultInterfaces.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<CMakeProjectReference Include="DefaultInterfaces/CMakeLists.txt" />
<ProjectReference Include="../NETServer/NETServer.DefaultInterfaces.ilproj" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<CMakeProjectReference Include="DefaultInterfaces/CMakeLists.txt" />
<ProjectReference Include="../NETServer/NETServer.DefaultInterfaces.ilproj" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.ComponentModel.TypeConverter/tests/SettingsBindableAttributeTests.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using Xunit;
namespace System.ComponentModel.Tests
{
public class SettingsBindableAttributeTests
{
[Theory]
[InlineData(true)]
[InlineData(false)]
public void Ctor_Bool(bool bindable)
{
var attribute = new SettingsBindableAttribute(bindable);
Assert.Equal(bindable, attribute.Bindable);
Assert.False(attribute.IsDefaultAttribute());
}
[Fact]
public void Yes_Get_ReturnsExpected()
{
SettingsBindableAttribute attribute = SettingsBindableAttribute.Yes;
Assert.Same(attribute, SettingsBindableAttribute.Yes);
Assert.True(attribute.Bindable);
Assert.False(attribute.IsDefaultAttribute());
}
[Fact]
public void No_Get_ReturnsExpected()
{
SettingsBindableAttribute attribute = SettingsBindableAttribute.No;
Assert.Same(attribute, SettingsBindableAttribute.No);
Assert.False(attribute.Bindable);
Assert.False(attribute.IsDefaultAttribute());
}
public static IEnumerable<object[]> Equals_TestData()
{
var attribute = new SettingsBindableAttribute(true);
yield return new object[] { attribute, attribute, true };
yield return new object[] { attribute, new SettingsBindableAttribute(true), true };
yield return new object[] { attribute, new SettingsBindableAttribute(false), false };
yield return new object[] { new SettingsBindableAttribute(false), new SettingsBindableAttribute(false), true };
yield return new object[] { new SettingsBindableAttribute(false), new SettingsBindableAttribute(true), false };
yield return new object[] { attribute, new object(), false };
yield return new object[] { attribute, null, false };
}
[Theory]
[MemberData(nameof(Equals_TestData))]
public void Equals_Object_ReturnsExpected(SettingsBindableAttribute attribute, object other, bool expected)
{
Assert.Equal(expected, attribute.Equals(other));
if (other is SettingsBindableAttribute)
{
Assert.Equal(expected, attribute.GetHashCode().Equals(other.GetHashCode()));
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using Xunit;
namespace System.ComponentModel.Tests
{
public class SettingsBindableAttributeTests
{
[Theory]
[InlineData(true)]
[InlineData(false)]
public void Ctor_Bool(bool bindable)
{
var attribute = new SettingsBindableAttribute(bindable);
Assert.Equal(bindable, attribute.Bindable);
Assert.False(attribute.IsDefaultAttribute());
}
[Fact]
public void Yes_Get_ReturnsExpected()
{
SettingsBindableAttribute attribute = SettingsBindableAttribute.Yes;
Assert.Same(attribute, SettingsBindableAttribute.Yes);
Assert.True(attribute.Bindable);
Assert.False(attribute.IsDefaultAttribute());
}
[Fact]
public void No_Get_ReturnsExpected()
{
SettingsBindableAttribute attribute = SettingsBindableAttribute.No;
Assert.Same(attribute, SettingsBindableAttribute.No);
Assert.False(attribute.Bindable);
Assert.False(attribute.IsDefaultAttribute());
}
public static IEnumerable<object[]> Equals_TestData()
{
var attribute = new SettingsBindableAttribute(true);
yield return new object[] { attribute, attribute, true };
yield return new object[] { attribute, new SettingsBindableAttribute(true), true };
yield return new object[] { attribute, new SettingsBindableAttribute(false), false };
yield return new object[] { new SettingsBindableAttribute(false), new SettingsBindableAttribute(false), true };
yield return new object[] { new SettingsBindableAttribute(false), new SettingsBindableAttribute(true), false };
yield return new object[] { attribute, new object(), false };
yield return new object[] { attribute, null, false };
}
[Theory]
[MemberData(nameof(Equals_TestData))]
public void Equals_Object_ReturnsExpected(SettingsBindableAttribute attribute, object other, bool expected)
{
Assert.Equal(expected, attribute.Equals(other));
if (other is SettingsBindableAttribute)
{
Assert.Equal(expected, attribute.GetHashCode().Equals(other.GetHashCode()));
}
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/tests/JIT/Directed/leave/filter2_r.ilproj
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="filter2.il" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="filter2.il" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Runtime/tests/System/DateTimeTests.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Tests
{
public class DateTimeTests
{
[Fact]
public static void MaxValue()
{
VerifyDateTime(DateTime.MaxValue, 9999, 12, 31, 23, 59, 59, 999, DateTimeKind.Unspecified);
}
[Fact]
public static void MinValue()
{
VerifyDateTime(DateTime.MinValue, 1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified);
}
[Fact]
public static void Ctor_Long()
{
VerifyDateTime(new DateTime(999999999999999999), 3169, 11, 16, 9, 46, 39, 999, DateTimeKind.Unspecified);
}
[Fact]
public static void Ctor_Long_DateTimeKind()
{
VerifyDateTime(new DateTime(999999999999999999, DateTimeKind.Utc), 3169, 11, 16, 9, 46, 39, 999, DateTimeKind.Utc);
}
public static IEnumerable<object[]> Ctor_InvalidTicks_TestData()
{
yield return new object[] { DateTime.MinValue.Ticks - 1 };
yield return new object[] { DateTime.MaxValue.Ticks + 1 };
}
[Theory]
[MemberData(nameof(Ctor_InvalidTicks_TestData))]
public void Ctor_InvalidTicks_ThrowsArgumentOutOfRangeException(long ticks)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("ticks", () => new DateTime(ticks));
AssertExtensions.Throws<ArgumentOutOfRangeException>("ticks", () => new DateTime(ticks, DateTimeKind.Utc));
}
[Fact]
public void Ctor_Int_Int_Int()
{
var dateTime = new DateTime(2012, 6, 11);
VerifyDateTime(dateTime, 2012, 6, 11, 0, 0, 0, 0, DateTimeKind.Unspecified);
}
[Fact]
public void Ctor_Int_Int_Int_Calendar()
{
var dateTime = new DateTime(2012, 6, 11, new GregorianCalendar());
VerifyDateTime(dateTime, 2012, 6, 11, 0, 0, 0, 0, DateTimeKind.Unspecified);
}
[Fact]
public void Ctor_Int_Int_Int_Int_Int_Int()
{
var dateTime = new DateTime(2012, 12, 31, 13, 50, 10);
VerifyDateTime(dateTime, 2012, 12, 31, 13, 50, 10, 0, DateTimeKind.Unspecified);
}
[Fact]
public void Ctor_Int_Int_Int_Int_Int_Int_DateTimeKind()
{
var dateTime = new DateTime(1986, 8, 15, 10, 20, 5, DateTimeKind.Local);
VerifyDateTime(dateTime, 1986, 8, 15, 10, 20, 5, 0, DateTimeKind.Local);
}
[Fact]
public void Ctor_Int_Int_Int_Int_Int_Int_Calendar()
{
var dateTime = new DateTime(2012, 12, 31, 13, 50, 10, new GregorianCalendar());
VerifyDateTime(dateTime, 2012, 12, 31, 13, 50, 10, 0, DateTimeKind.Unspecified);
}
public static IEnumerable<object[]> Ctor_Int_Int_Int_Int_Int_Int_Int_Int_TestData()
{
yield return new object[] { 1986, 8, 15, 10, 20, 5, 600 };
yield return new object[] { 1986, 2, 28, 10, 20, 5, 600 };
yield return new object[] { 1986, 12, 31, 10, 20, 5, 600 };
yield return new object[] { 2000, 2, 28, 10, 20, 5, 600 };
yield return new object[] { 2000, 2, 29, 10, 20, 5, 600 };
yield return new object[] { 2000, 12, 31, 10, 20, 5, 600 };
yield return new object[] { 1900, 2, 28, 10, 20, 5, 600 };
yield return new object[] { 1900, 12, 31, 10, 20, 5, 600 };
}
[Theory]
[MemberData(nameof(Ctor_Int_Int_Int_Int_Int_Int_Int_Int_TestData))]
public void Ctor_Int_Int_Int_Int_Int_Int_Int(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
var dateTime = new DateTime(year, month, day, hour, minute, second, millisecond);
VerifyDateTime(dateTime, year, month, day, hour, minute, second, millisecond, DateTimeKind.Unspecified);
}
[Theory]
[MemberData(nameof(Ctor_Int_Int_Int_Int_Int_Int_Int_Int_TestData))]
public void Ctor_Int_Int_Int_Int_Int_Int_Int_Calendar(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
var dateTime = new DateTime(year, month, day, hour, minute, second, millisecond, new GregorianCalendar());
VerifyDateTime(dateTime, year, month, day, hour, minute, second, millisecond, DateTimeKind.Unspecified);
}
[Theory]
[MemberData(nameof(Ctor_Int_Int_Int_Int_Int_Int_Int_Int_TestData))]
public void Ctor_Int_Int_Int_Int_Int_Int_Int_Int_DateTimeKind(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
var dateTime = new DateTime(year, month, day, hour, minute, second, millisecond, DateTimeKind.Local);
VerifyDateTime(dateTime, year, month, day, hour, minute, second, millisecond, DateTimeKind.Local);
}
[Theory]
[MemberData(nameof(Ctor_Int_Int_Int_Int_Int_Int_Int_Int_TestData))]
public void Ctor_Int_Int_Int_Int_Int_Int_Int_Int_Calendar_DateTimeKind(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
var dateTime = new DateTime(year, month, day, hour, minute, second, millisecond, new GregorianCalendar(), DateTimeKind.Local);
VerifyDateTime(dateTime, year, month, day, hour, minute, second, millisecond, DateTimeKind.Local);
}
[Theory]
[InlineData(0)]
[InlineData(10000)]
public void Ctor_InvalidYear_ThrowsArgumentOutOfRangeException(int year)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(year, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(year, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(year, 1, 1, 1, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(year, 1, 1, 1, 1, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(year, 1, 1, 1, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(year, 1, 1, 1, 1, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(year, 1, 1, 1, 1, 1, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(year, 1, 1, 1, 1, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(year, 1, 1, 1, 1, 1, 1, new GregorianCalendar(), DateTimeKind.Utc));
}
[Theory]
[InlineData(0)]
[InlineData(13)]
public void Ctor_InvalidMonth_ThrowsArgumentOutOfRangeException(int month)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, month, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, month, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, month, 1, 1, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, month, 1, 1, 1, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, month, 1, 1, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, month, 1, 1, 1, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, month, 1, 1, 1, 1, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, month, 1, 1, 1, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, month, 1, 1, 1, 1, 1, new GregorianCalendar(), DateTimeKind.Utc));
}
[Theory]
[InlineData(0)]
[InlineData(32)]
public void Ctor_InvalidDay_ThrowsArgumentOutOfRangeException(int day)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, day));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, day, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, day, 1, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, day, 1, 1, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, day, 1, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, day, 1, 1, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, day, 1, 1, 1, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, day, 1, 1, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, day, 1, 1, 1, 1, new GregorianCalendar(), DateTimeKind.Utc));
}
[Theory]
[InlineData(-1)]
[InlineData(24)]
public void Ctor_InvalidHour_ThrowsArgumentOutOfRangeException(int hour)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, hour, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, hour, 1, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, hour, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, hour, 1, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, hour, 1, 1, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, hour, 1, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, hour, 1, 1, 1, new GregorianCalendar(), DateTimeKind.Utc));
}
[Theory]
[InlineData(-1)]
[InlineData(60)]
public void Ctor_InvalidMinute_ThrowsArgumentOutOfRangeException(int minute)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, minute, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, minute, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, minute, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, minute, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, minute, 1, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, minute, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, minute, 1, 1, new GregorianCalendar(), DateTimeKind.Utc));
}
[Theory]
[InlineData(-1)]
[InlineData(60)]
public void Ctor_InvalidSecond_ThrowsArgumentOutOfRangeException(int second)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, second));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, second, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, second, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, second, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, second, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, second, 1, new GregorianCalendar(), DateTimeKind.Utc));
}
[Theory]
[InlineData(-1)]
[InlineData(1000)]
public void Ctor_InvalidMillisecond_ThrowsArgumentOutOfRangeException(int millisecond)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTime(1, 1, 1, 1, 1, 1, millisecond));
AssertExtensions.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTime(1, 1, 1, 1, 1, 1, millisecond, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTime(1, 1, 1, 1, 1, 1, millisecond, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTime(1, 1, 1, 1, 1, 1, millisecond, new GregorianCalendar(), DateTimeKind.Utc));
}
[Theory]
[InlineData(DateTimeKind.Unspecified - 1)]
[InlineData(DateTimeKind.Local + 1)]
public void Ctor_InvalidDateTimeKind_ThrowsArgumentException(DateTimeKind kind)
{
AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(0, kind));
AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(1, 1, 1, 1, 1, 1, kind));
AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(1, 1, 1, 1, 1, 1, 1, kind));
AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(1, 1, 1, 1, 1, 1, 1, new GregorianCalendar(), kind));
}
[Fact]
public void Ctor_NullCalendar_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("calendar", () => new DateTime(1, 1, 1, null));
AssertExtensions.Throws<ArgumentNullException>("calendar", () => new DateTime(1, 1, 1, 1, 1, 1, null));
AssertExtensions.Throws<ArgumentNullException>("calendar", () => new DateTime(1, 1, 1, 1, 1, 1, 1, null));
AssertExtensions.Throws<ArgumentNullException>("calendar", () => new DateTime(1, 1, 1, 1, 1, 1, 1, null, DateTimeKind.Local));
}
[Theory]
[InlineData(2004, 1, 31)]
[InlineData(2004, 2, 29)]
[InlineData(2004, 3, 31)]
[InlineData(2004, 4, 30)]
[InlineData(2004, 5, 31)]
[InlineData(2004, 6, 30)]
[InlineData(2004, 7, 31)]
[InlineData(2004, 8, 31)]
[InlineData(2004, 9, 30)]
[InlineData(2004, 10, 31)]
[InlineData(2004, 11, 30)]
[InlineData(2004, 12, 31)]
[InlineData(2005, 1, 31)]
[InlineData(2005, 2, 28)]
[InlineData(2005, 3, 31)]
[InlineData(2005, 4, 30)]
[InlineData(2005, 5, 31)]
[InlineData(2005, 6, 30)]
[InlineData(2005, 7, 31)]
[InlineData(2005, 8, 31)]
[InlineData(2005, 9, 30)]
[InlineData(2005, 10, 31)]
[InlineData(2005, 11, 30)]
[InlineData(2005, 12, 31)]
public void DaysInMonth_Invoke_ReturnsExpected(int year, int month, int expected)
{
Assert.Equal(expected, DateTime.DaysInMonth(year, month));
}
[Theory]
[InlineData(0)]
[InlineData(13)]
public void DaysInMonth_InvalidMonth_ThrowsArgumentOutOfRangeException(int month)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("month", () => DateTime.DaysInMonth(1, month));
}
[Theory]
[InlineData(0)]
[InlineData(10000)]
public void DaysInMonth_InvalidYear_ThrowsArgumentOutOfRangeException(int year)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("year", () => DateTime.DaysInMonth(year, 1));
}
[Theory]
[InlineData(2004, true)]
[InlineData(2000, true)]
[InlineData(1900, false)]
[InlineData(2005, false)]
public void IsLeapYear_Invoke_ReturnsExpected(int year, bool expected)
{
Assert.Equal(expected, DateTime.IsLeapYear(year));
}
[Theory]
[InlineData(0)]
[InlineData(10000)]
public void IsLeapYear_InvalidYear_ThrowsArgumentOutOfRangeException(int year)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("year", () => DateTime.IsLeapYear(year));
}
public static IEnumerable<object[]> IsDaylightSavingTime_TestData()
{
yield return new object[] { new DateTime(2018, 11, 24, 0, 0, 0, DateTimeKind.Utc), false };
yield return new object[] { DateTime.MinValue, false };
yield return new object[] { DateTime.MaxValue, false };
}
[Theory]
[MemberData(nameof(IsDaylightSavingTime_TestData))]
public void IsDaylightSavingTime_Invoke_ReturnsExpected(DateTime date, bool expected)
{
Assert.Equal(expected, date.IsDaylightSavingTime());
}
public static IEnumerable<object[]> Add_TimeSpan_TestData()
{
yield return new object[] { new DateTime(1000), new TimeSpan(10), new DateTime(1010) };
yield return new object[] { new DateTime(1000), TimeSpan.Zero, new DateTime(1000) };
yield return new object[] { new DateTime(1000), new TimeSpan(-10), new DateTime(990) };
}
[Theory]
[MemberData(nameof(Add_TimeSpan_TestData))]
public void Add_TimeSpan_ReturnsExpected(DateTime dateTime, TimeSpan timeSpan, DateTime expected)
{
Assert.Equal(expected, dateTime.Add(timeSpan));
Assert.Equal(expected, dateTime + timeSpan);
}
public static IEnumerable<object[]> Add_TimeSpanOutOfRange_TestData()
{
yield return new object[] { DateTime.Now, TimeSpan.MaxValue };
yield return new object[] { DateTime.Now, TimeSpan.MinValue };
yield return new object[] { DateTime.MaxValue, new TimeSpan(1) };
yield return new object[] { DateTime.MinValue, new TimeSpan(-1) };
}
[Theory]
[MemberData(nameof(Add_TimeSpanOutOfRange_TestData))]
public void Add_TimeSpan_NewDateOutOfRange_ThrowsArgumentOutOfRangeException(DateTime date, TimeSpan value)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => date.Add(value));
AssertExtensions.Throws<ArgumentOutOfRangeException>("t", () => date + value);
}
public static IEnumerable<object[]> AddYears_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 10, new DateTime(1996, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -10, new DateTime(1976, 8, 15, 10, 20, 5, 70) };
}
[Theory]
[MemberData(nameof(AddYears_TestData))]
public void AddYears_Invoke_ReturnsExpected(DateTime dateTime, int years, DateTime expected)
{
Assert.Equal(expected, dateTime.AddYears(years));
}
public static IEnumerable<object[]> AddYears_OutOfRange_TestData()
{
yield return new object[] { DateTime.Now, 10001 };
yield return new object[] { DateTime.Now, -10001 };
yield return new object[] { DateTime.MaxValue, 1 };
yield return new object[] { DateTime.MinValue, -1 };
}
[Theory]
[MemberData(nameof(AddYears_OutOfRange_TestData))]
public static void AddYears_NewDateOutOfRange_ThrowsArgumentOutOfRangeException(DateTime date, int years)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => date.AddYears(years));
}
public static IEnumerable<object[]> AddMonths_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 2, new DateTime(1986, 10, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 31, 10, 20, 5, 70), 1, new DateTime(1986, 9, 30, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 9, 30, 10, 20, 5, 70), 1, new DateTime(1986, 10, 30, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -2, new DateTime(1986, 6, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1900, 2, 28, 10, 20, 5, 70), 1, new DateTime(1900, 3, 28, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1900, 1, 31, 10, 20, 5, 70), 1, new DateTime(1900, 2, 28, 10, 20, 5, 70) };
yield return new object[] { new DateTime(2000, 1, 31, 10, 20, 5, 70), 1, new DateTime(2000, 2, 29, 10, 20, 5, 70) };
yield return new object[] { new DateTime(2000, 2, 29, 10, 20, 5, 70), 1, new DateTime(2000, 3, 29, 10, 20, 5, 70) };
yield return new object[] { new DateTime(2004, 1, 31, 10, 20, 5, 70), 1, new DateTime(2004, 2, 29, 10, 20, 5, 70) };
yield return new object[] { new DateTime(2004, 2, 29, 10, 20, 5, 70), 1, new DateTime(2004, 3, 29, 10, 20, 5, 70) };
yield return new object[] { new DateTime(2000, 12, 31), 1, new DateTime(2001, 1, 31) };
}
[Theory]
[MemberData(nameof(AddMonths_TestData))]
public void AddMonths_Invoke_ReturnsExpected(DateTime dateTime, int months, DateTime expected)
{
Assert.Equal(expected, dateTime.AddMonths(months));
}
public static IEnumerable<object[]> AddMonths_OutOfRange_TestData()
{
yield return new object[] { DateTime.Now, 120001 };
yield return new object[] { DateTime.Now, -120001 };
yield return new object[] { DateTime.MaxValue, 1 };
yield return new object[] { DateTime.MinValue, -1 };
}
[Theory]
[MemberData(nameof(AddMonths_OutOfRange_TestData))]
public void AddMonths_NewDateOutOfRange_ThrowsArgumentOutOfRangeException(DateTime date, int months)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => date.AddMonths(months));
}
public static IEnumerable<object[]> AddDays_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 2, new DateTime(1986, 8, 17, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 2, new DateTime(1986, 8, 17, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -2, new DateTime(1986, 8, 13, 10, 20, 5, 70) };
}
[Theory]
[MemberData(nameof(AddDays_TestData))]
public void AddDays_Invoke_ReturnsExpected(DateTime dateTime, double days, DateTime expected)
{
Assert.Equal(expected, dateTime.AddDays(days));
}
public static IEnumerable<object[]> AddDays_OutOfRange_TestData()
{
yield return new object[] { DateTime.MaxValue, 1 };
yield return new object[] { DateTime.MinValue, -1 };
yield return new object[] { DateTime.Now, double.MaxValue };
yield return new object[] { DateTime.Now, double.MinValue };
}
[Theory]
[MemberData(nameof(AddDays_OutOfRange_TestData))]
public void AddDays_NewDateOutOfRange_ThrowsArgumentOutOfRangeException(DateTime date, double days)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => date.AddDays(days));
}
public static IEnumerable<object[]> AddHours_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 3, new DateTime(1986, 8, 15, 13, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -3, new DateTime(1986, 8, 15, 7, 20, 5, 70) };
}
[Theory]
[MemberData(nameof(AddHours_TestData))]
public void AddHours_Invoke_RetunsExpected(DateTime dateTime, double hours, DateTime expected)
{
Assert.Equal(expected, dateTime.AddHours(hours));
}
public static IEnumerable<object[]> AddHours_OutOfRange_TestData()
{
yield return new object[] { DateTime.MaxValue, 1 };
yield return new object[] { DateTime.MinValue, -1 };
yield return new object[] { DateTime.Now, double.MaxValue };
yield return new object[] { DateTime.Now, double.MinValue };
}
[Theory]
[MemberData(nameof(AddHours_OutOfRange_TestData))]
public void AddHours_NewDateOutOfRange_ThrowsArgumentOutOfRangeException(DateTime date, double hours)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => date.AddHours(hours));
}
public static IEnumerable<object[]> AddMinutes_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 5, new DateTime(1986, 8, 15, 10, 25, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -5, new DateTime(1986, 8, 15, 10, 15, 5, 70) };
}
[Theory]
[MemberData(nameof(AddMinutes_TestData))]
public void AddMinutes_Invoke_ReturnsExpected(DateTime dateTime, double minutes, DateTime expected)
{
Assert.Equal(expected, dateTime.AddMinutes(minutes));
}
public static IEnumerable<object[]> AddMinutes_OutOfRange_TestData()
{
yield return new object[] { DateTime.MaxValue, 1 };
yield return new object[] { DateTime.MinValue, -1 };
yield return new object[] { DateTime.Now, double.MaxValue };
yield return new object[] { DateTime.Now, double.MinValue };
}
[Theory]
[MemberData(nameof(AddMinutes_OutOfRange_TestData))]
public void AddMinutes_NewDateOutOfRange_ThrowsArgumentOutOfRangeException(DateTime date, double minutes)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => date.AddMinutes(minutes));
}
public static IEnumerable<object[]> AddSeconds_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 30, new DateTime(1986, 8, 15, 10, 20, 35, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -3, new DateTime(1986, 8, 15, 10, 20, 2, 70) };
}
[Theory]
[MemberData(nameof(AddSeconds_TestData))]
public void AddSeconds_Invoke_ReturnsExpected(DateTime dateTime, double seconds, DateTime expected)
{
Assert.Equal(expected, dateTime.AddSeconds(seconds));
}
public static IEnumerable<object[]> AddSeconds_OutOfRange_TestData()
{
yield return new object[] { DateTime.MaxValue, 1 };
yield return new object[] { DateTime.MinValue, -1 };
yield return new object[] { DateTime.Now, double.MaxValue };
yield return new object[] { DateTime.Now, double.MinValue };
}
[Theory]
[MemberData(nameof(AddSeconds_OutOfRange_TestData))]
public void AddSeconds_NewDateOutOfRange_ThrowsArgumentOutOfRangeException(DateTime date, double seconds)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => date.AddSeconds(seconds));
}
public static IEnumerable<object[]> AddMilliseconds_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 10, new DateTime(1986, 8, 15, 10, 20, 5, 80) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -10, new DateTime(1986, 8, 15, 10, 20, 5, 60) };
}
[Theory]
[MemberData(nameof(AddMilliseconds_TestData))]
public void AddMilliseconds_Invoke_ReturnsExpected(DateTime dateTime, double milliseconds, DateTime expected)
{
Assert.Equal(expected, dateTime.AddMilliseconds(milliseconds));
}
public static IEnumerable<object[]> AddMillseconds_OutOfRange_TestData()
{
yield return new object[] { DateTime.MaxValue, 1 };
yield return new object[] { DateTime.MinValue, -1 };
yield return new object[] { DateTime.Now, double.MaxValue };
yield return new object[] { DateTime.Now, double.MinValue };
}
[Theory]
[MemberData(nameof(AddMillseconds_OutOfRange_TestData))]
public void AddMilliseconds_NewDateOutOfRange_ThrowsArgumentOutOfRangeException(DateTime date, double milliseconds)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => date.AddMilliseconds(milliseconds));
}
public static IEnumerable<object[]> AddTicks_TestData()
{
yield return new object[] { new DateTime(1000), 10, new DateTime(1010) };
yield return new object[] { new DateTime(1000), 0, new DateTime(1000) };
yield return new object[] { new DateTime(1000), -10, new DateTime(990) };
}
[Theory]
[MemberData(nameof(AddTicks_TestData))]
public void AddTicks_Invoke_ReturnsExpected(DateTime dateTime, long ticks, DateTime expected)
{
Assert.Equal(expected, dateTime.AddTicks(ticks));
}
public static IEnumerable<object[]> AddTicks_OutOfRange_TestData()
{
yield return new object[] { DateTime.MaxValue, 1 };
yield return new object[] { DateTime.MinValue, -1 };
yield return new object[] { DateTime.Now, long.MaxValue };
yield return new object[] { DateTime.Now, long.MinValue };
}
[Theory]
[MemberData(nameof(AddTicks_OutOfRange_TestData))]
public void AddTicks_NewDateOutOfRange_ThrowsArgumentOutOfRangeException(DateTime date, long ticks)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => date.AddTicks(ticks));
}
public static IEnumerable<object[]> CompareTo_TestData()
{
yield return new object[] { new DateTime(10), new DateTime(10), 0 };
yield return new object[] { new DateTime(10), new DateTime(11), -1 };
yield return new object[] { new DateTime(10), new DateTime(9), 1 };
yield return new object[] { new DateTime(10), null, 1 };
}
[Theory]
[MemberData(nameof(CompareTo_TestData))]
public void CompareTo_Invoke_ReturnsExpected(DateTime date, object other, int expected)
{
if (other is DateTime otherDate)
{
Assert.Equal(expected, date.CompareTo(otherDate));
Assert.Equal(expected, DateTime.Compare(date, otherDate));
Assert.Equal(expected > 0, date > otherDate);
Assert.Equal(expected >= 0, date >= otherDate);
Assert.Equal(expected < 0, date < otherDate);
Assert.Equal(expected <= 0, date <= otherDate);
}
Assert.Equal(expected, date.CompareTo(other));
}
[Fact]
public void CompareTo_NotDateTime_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>(null, () => DateTime.Now.CompareTo(new object()));
}
public static IEnumerable<object[]> Equals_TestData()
{
yield return new object[] { new DateTime(10), new DateTime(10), true };
yield return new object[] { new DateTime(10), new DateTime(11), false };
yield return new object[] { new DateTime(10), new DateTime(9), false };
yield return new object[] { new DateTime(10), new object(), false };
yield return new object[] { new DateTime(10), null, false };
}
[Theory]
[MemberData(nameof(Equals_TestData))]
public void Equals_Invoke_ReturnsExpected(DateTime date, object other, bool expected)
{
if (other is DateTime otherDate)
{
Assert.Equal(expected, date.Equals(otherDate));
Assert.Equal(expected, DateTime.Equals(date, otherDate));
Assert.Equal(expected, date.GetHashCode().Equals(otherDate.GetHashCode()));
Assert.Equal(expected, date == otherDate);
Assert.Equal(!expected, date != otherDate);
}
Assert.Equal(expected, date.Equals(other));
}
[Fact]
public void DayOfWeek_Get_ReturnsExpected()
{
var dateTime = new DateTime(2012, 6, 18);
Assert.Equal(DayOfWeek.Monday, dateTime.DayOfWeek);
}
[Fact]
public void DayOfYear_Get_ReturnsExpected()
{
var dateTime = new DateTime(2012, 6, 18);
Assert.Equal(170, dateTime.DayOfYear);
}
[Fact]
public void TimeOfDay_Get_ReturnsExpected()
{
var dateTime = new DateTime(2012, 6, 18, 10, 5, 1, 0);
TimeSpan ts = dateTime.TimeOfDay;
DateTime newDate = dateTime.Subtract(ts);
Assert.Equal(new DateTime(2012, 6, 18, 0, 0, 0, 0).Ticks, newDate.Ticks);
Assert.Equal(dateTime.Ticks, newDate.Add(ts).Ticks);
}
[Fact]
public void Today_Get_ReturnsExpected()
{
DateTime today = DateTime.Today;
DateTime now = DateTime.Now;
VerifyDateTime(today, now.Year, now.Month, now.Day, 0, 0, 0, 0, DateTimeKind.Local);
today = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, DateTimeKind.Utc);
Assert.Equal(DateTimeKind.Utc, today.Kind);
Assert.False(today.IsDaylightSavingTime());
}
public static IEnumerable<object[]> Subtract_TimeSpan_TestData()
{
var dateTime = new DateTime(2012, 6, 18, 10, 5, 1, 0, DateTimeKind.Utc);
yield return new object[] { dateTime, new TimeSpan(10, 5, 1), new DateTime(2012, 6, 18, 0, 0, 0, 0, DateTimeKind.Utc) };
yield return new object[] { dateTime, new TimeSpan(-10, -5, -1), new DateTime(2012, 6, 18, 20, 10, 2, 0, DateTimeKind.Utc) };
}
[Theory]
[MemberData(nameof(Subtract_TimeSpan_TestData))]
public void Subtract_TimeSpan_ReturnsExpected(DateTime dateTime, TimeSpan timeSpan, DateTime expected)
{
Assert.Equal(expected, dateTime.Subtract(timeSpan));
Assert.Equal(expected, dateTime - timeSpan);
}
public static IEnumerable<object[]> Subtract_OutOfRangeTimeSpan_TestData()
{
yield return new object[] { DateTime.Now, TimeSpan.MinValue };
yield return new object[] { DateTime.Now, TimeSpan.MaxValue };
yield return new object[] { DateTime.MaxValue, new TimeSpan(-1) };
yield return new object[] { DateTime.MinValue, new TimeSpan(1) };
}
[Theory]
[MemberData(nameof(Subtract_OutOfRangeTimeSpan_TestData))]
public static void Subtract_OutOfRangeTimeSpan_ThrowsArgumentOutOfRangeException(DateTime date, TimeSpan value)
{
Assert.Throws<ArgumentOutOfRangeException>(() => date.Subtract(value));
Assert.Throws<ArgumentOutOfRangeException>(() => date - value);
}
public static IEnumerable<object[]> Subtract_DateTime_TestData()
{
var dateTime1 = new DateTime(1996, 6, 3, 22, 15, 0, DateTimeKind.Utc);
var dateTime2 = new DateTime(1996, 12, 6, 13, 2, 0, DateTimeKind.Utc);
var dateTime3 = new DateTime(1996, 10, 12, 8, 42, 0, DateTimeKind.Utc);
yield return new object[] { dateTime2, dateTime1, new TimeSpan(185, 14, 47, 0) };
yield return new object[] { dateTime1, dateTime2, new TimeSpan(-185, -14, -47, 0) };
yield return new object[] { dateTime1, dateTime2, new TimeSpan(-185, -14, -47, 0) };
}
[Theory]
[MemberData(nameof(Subtract_DateTime_TestData))]
public void Subtract_DateTime_ReturnsExpected(DateTime dateTime1, DateTime dateTime2, TimeSpan expected)
{
Assert.Equal(expected, dateTime1.Subtract(dateTime2));
Assert.Equal(expected, dateTime1 - dateTime2);
}
public static IEnumerable<object[]> ToOADate_TestData()
{
yield return new object[] { new DateTime(1), 0 };
yield return new object[] { new DateTime((long)10000 * 1000 * 60 * 60 * 24 - 1), 1 };
yield return new object[] { new DateTime(100, 1, 1), -657434 };
yield return new object[] { new DateTime(1889, 11, 24, 23, 59, 59, 999).AddTicks(1), -3687 };
yield return new object[] { new DateTime(1889, 11, 24, 17, 57, 30, 12), -3688.74826402778 };
yield return new object[] { new DateTime(1889, 11, 24).AddTicks(1), -3688 };
yield return new object[] { new DateTime(1899, 12, 30), 0 };
yield return new object[] { new DateTime(2018, 11, 24), 43428 };
yield return new object[] { new DateTime(2018, 11, 24, 17, 57, 30, 12), 43428.74826 };
yield return new object[] { new DateTime(2018, 11, 24, 23, 59, 59, 999).AddTicks(1), 43429 };
yield return new object[] { DateTime.MinValue, 0 };
yield return new object[] { DateTime.MaxValue, 2958466 };
}
[Theory]
[MemberData(nameof(ToOADate_TestData))]
public void ToOADate_Invoke_ReturnsExpected(DateTime date, double expected)
{
Assert.Equal(expected, date.ToOADate(), 5);
}
public static IEnumerable<object[]> ToOADate_Overflow_TestData()
{
yield return new object[] { new DateTime((long)10000 * 1000 * 60 * 60 * 24) };
yield return new object[] { new DateTime(100, 1, 1).AddTicks(-1) };
}
[Theory]
[MemberData(nameof(ToOADate_Overflow_TestData))]
public void ToOADate_SmallDate_ThrowsOverflowException(DateTime date)
{
Assert.Throws<OverflowException>(() => date.ToOADate());
}
public static IEnumerable<object[]> FromOADate_TestData()
{
yield return new object[] { -1.5, new DateTime(1899, 12, 29, 12, 0, 0) };
yield return new object[] { -1, new DateTime(1899, 12, 29) };
yield return new object[] { 0, new DateTime(1899, 12, 30) };
yield return new object[] { 1, new DateTime(1899, 12, 31) };
yield return new object[] { 1.5, new DateTime(1899, 12, 31, 12, 0, 0) };
yield return new object[] { -657434.99999999, new DateTime(100, 1, 1, 23, 59, 59, 999) };
yield return new object[] { -657434.9999999999, new DateTime(99, 12, 31) };
yield return new object[] { 2958465.999999994, new DateTime(9999, 12, 31, 23, 59, 59, 999) };
}
[Theory]
[MemberData(nameof(FromOADate_TestData))]
public void FromOADate_Invoke_ReturnsExpected(double value, DateTime expected)
{
DateTime actual = DateTime.FromOADate(value);
Assert.Equal(expected, actual);
Assert.Equal(DateTimeKind.Unspecified, actual.Kind);
}
[Theory]
[InlineData(-657435)]
[InlineData(2958466)]
[InlineData(-657434.99999999995)]
[InlineData(2958465.999999995)]
[InlineData(double.NaN)]
public void FromOADate_InvalidValue_ThrowsArgumentException(double value)
{
AssertExtensions.Throws<ArgumentException>(null, () => DateTime.FromOADate(value));
}
public static IEnumerable<object[]> ToBinary_TestData()
{
const long Ticks = 123456789101112;
DateTime local = new DateTime(Ticks, DateTimeKind.Local);
TimeSpan offset = TimeZoneInfo.Local.GetUtcOffset(local);
long localTicks = local.Ticks - offset.Ticks;
if (localTicks < 0)
{
localTicks |= 0x4000000000000000;
}
yield return new object[] { new DateTime(Ticks, DateTimeKind.Utc), Ticks | ((long)DateTimeKind.Utc << 62) };
yield return new object[] { new DateTime(Ticks, DateTimeKind.Unspecified), Ticks | (( long)DateTimeKind.Unspecified << 62) };
yield return new object[] { local, localTicks | ((long)DateTimeKind.Local << 62) };
yield return new object[] { DateTime.MaxValue, 3155378975999999999 };
yield return new object[] { DateTime.MinValue, 0 };
}
[Theory]
[MemberData(nameof(ToBinary_TestData))]
public void ToBinary_Invoke_ReturnsExpected(DateTime date, long expected)
{
Assert.Equal(expected, date.ToBinary());
}
public static IEnumerable<object[]> FromBinary_TestData()
{
yield return new object[] { new DateTime(2018, 12, 24, 17, 34, 30, 12) };
yield return new object[] { new DateTime(2018, 12, 24, 17, 34, 30, 12, DateTimeKind.Local) };
yield return new object[] { DateTime.Today };
yield return new object[] { DateTime.MinValue };
yield return new object[] { DateTime.MaxValue };
}
[Theory]
[MemberData(nameof(FromBinary_TestData))]
public void FromBinary_Invoke_ReturnsExpected(DateTime date)
{
Assert.Equal(date, DateTime.FromBinary(date.ToBinary()));
}
[Theory]
[InlineData(3155378976000000000)]
[InlineData(long.MaxValue)]
[InlineData(3155378976000000000 | ((long)DateTimeKind.Utc << 62))]
public void FromBinary_OutOfRangeTicks_ThrowsArgumentException(long dateData)
{
AssertExtensions.Throws<ArgumentException>("dateData", () => DateTime.FromBinary(dateData));
}
public static IEnumerable<object[]> ToFileTime_TestData()
{
yield return new object[] { new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc) };
yield return new object[] { new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddTicks(1) };
yield return new object[] { new DateTime(2018, 12, 24, 0, 0, 0, DateTimeKind.Utc) };
yield return new object[] { new DateTime(2018, 11, 24, 17, 57, 30, 12, DateTimeKind.Utc) };
yield return new object[] { new DateTime(2018, 12, 24, 0, 0, 0, DateTimeKind.Local) };
yield return new object[] { new DateTime(2018, 11, 24, 17, 57, 30, 12, DateTimeKind.Local) };
}
[Theory]
[MemberData(nameof(ToFileTime_TestData))]
public void ToFileTime_Invoke_ReturnsExpected(DateTime date)
{
long fileTime = date.ToFileTime();
DateTime fromFileTime = date.Kind == DateTimeKind.Utc ? DateTime.FromFileTimeUtc(fileTime) : DateTime.FromFileTime(fileTime);
Assert.Equal(date, fromFileTime);
}
public static IEnumerable<object[]> ToFileTime_Overflow_TestData()
{
yield return new object[] { DateTime.MinValue };
yield return new object[] { new DateTime(1600, 12, 31) };
}
[Theory]
[MemberData(nameof(ToFileTime_Overflow_TestData))]
public void ToFileTime_SmallDate_ThrowsArgumentOutOfRangeException(DateTime date)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => date.ToFileTime());
}
public static IEnumerable<object[]> FromFileTime_TestData()
{
yield return new object[] { 0, new DateTime(1601, 1, 1) };
yield return new object[] { 2650467743999999999, DateTime.MaxValue };
yield return new object[] { 131875558500120000, new DateTime(2018, 11, 24, 17, 57, 30, 12) };
}
[Theory]
[MemberData(nameof(FromFileTime_TestData))]
public void FromFileTime_Invoke_ReturnsExpected(long fileTime, DateTime expected)
{
DateTime actual = DateTime.FromFileTime(fileTime);
Assert.Equal(expected.ToLocalTime(), actual);
Assert.Equal(DateTimeKind.Local, actual.Kind);
}
[Theory]
[InlineData(-1)]
[InlineData(2650467744000000000)]
public void FromFileTime_OutOfRange_ThrowsArgumentOutOfRangeException(long fileTime)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("fileTime", () => DateTime.FromFileTime(fileTime));
}
public static IEnumerable<object[]> ToFileTimeUtc_TestData()
{
DateTime local = new DateTime(2018, 12, 24, 0, 0, 0, DateTimeKind.Local);
DateTime localToUtc = TimeZoneInfo.ConvertTimeToUtc(local);
yield return new object[] { new DateTime(1601, 1, 1), 0 };
yield return new object[] { new DateTime(1601, 1, 1).AddTicks(1), 1 };
yield return new object[] { new DateTime(2018, 12, 24), 131900832000000000 };
yield return new object[] { local, localToUtc.ToFileTimeUtc() };
yield return new object[] { new DateTime(2018, 11, 24, 17, 57, 30, 12), 131875558500120000 };
yield return new object[] { DateTime.MaxValue, 2650467743999999999 };
}
[Theory]
[MemberData(nameof(ToFileTimeUtc_TestData))]
public void ToFileTimeUtc_Invoke_ReturnsExpected(DateTime date, long expected)
{
Assert.Equal(expected, date.ToFileTimeUtc());
}
public static IEnumerable<object[]> ToFileTimeUtc_Overflow_TestData()
{
yield return new object[] { DateTime.MinValue };
yield return new object[] { new DateTime(1600, 12, 31) };
}
[Theory]
[MemberData(nameof(ToFileTimeUtc_Overflow_TestData))]
public void ToFileTimeUtc_SmallDate_ThrowsArgumentOutOfRangeException(DateTime date)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => date.ToFileTimeUtc());
}
public static IEnumerable<object[]> FromFileTimeUtc_TestData()
{
yield return new object[] { 0, new DateTime(1601, 1, 1) };
yield return new object[] { 2650467743999999999, DateTime.MaxValue };
yield return new object[] { 131875558500120000, new DateTime(2018, 11, 24, 17, 57, 30, 12) };
}
[Theory]
[MemberData(nameof(FromFileTimeUtc_TestData))]
public void FromFileTimeUtc_Invoke_ReturnsExpected(long fileTime, DateTime expected)
{
DateTime actual = DateTime.FromFileTimeUtc(fileTime);
Assert.Equal(expected, actual);
Assert.Equal(DateTimeKind.Utc, actual.Kind);
}
[Theory]
[InlineData(-1)]
[InlineData(2650467744000000000)]
public void FromFileTimeUtc_OutOfRange_ThrowsArgumentOutOfRangeException(long fileTime)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("fileTime", () => DateTime.FromFileTimeUtc(fileTime));
}
[Fact]
public static void Parse_String()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString();
DateTime result = DateTime.Parse(expectedString);
Assert.Equal(expectedString, result.ToString());
}
[Fact]
public static void Parse_String_FormatProvider()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString();
DateTime result = DateTime.Parse(expectedString, null);
Assert.Equal(expectedString, result.ToString());
}
[Fact]
public static void Parse_String_FormatProvider_DateTimeStyles()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString();
DateTime result = DateTime.Parse(expectedString, null, DateTimeStyles.None);
Assert.Equal(expectedString, result.ToString());
}
[Fact]
public static void Parse_Japanese()
{
var expected = new DateTime(2012, 12, 21, 10, 8, 6);
var cultureInfo = new CultureInfo("ja-JP");
string expectedString = string.Format(cultureInfo, "{0}", expected);
Assert.Equal(expected, DateTime.Parse(expectedString, cultureInfo));
}
private static bool IsNotOSXOrBrowser => !PlatformDetection.IsOSXLike && !PlatformDetection.IsBrowser;
[ConditionalTheory(nameof(IsNotOSXOrBrowser))]
[InlineData("ar")]
[InlineData("ar-EG")]
[InlineData("ar-IQ")]
[InlineData("ar-SA")]
[InlineData("ar-YE")]
public static void DateTimeParsingWithBiDiCultureTest(string cultureName)
{
DateTime dt = new DateTime(2021, 11, 30, 14, 30, 40);
CultureInfo ci = CultureInfo.GetCultureInfo(cultureName);
string formatted = dt.ToString("d", ci);
Assert.Equal(dt.Date, DateTime.Parse(formatted, ci));
formatted = dt.ToString("g", ci);
DateTime parsed = DateTime.Parse(formatted, ci);
Assert.Equal(dt.Date, parsed.Date);
Assert.Equal(dt.Hour, parsed.Hour);
Assert.Equal(dt.Minute, parsed.Minute);
}
[Fact]
public static void DateTimeParsingWithSpaceTimeSeparators()
{
DateTime dt = new DateTime(2021, 11, 30, 14, 30, 40);
CultureInfo ci = CultureInfo.GetCultureInfo("en-US");
// It is possible we find some cultures use such formats. dz-BT is example of that
string formatted = dt.ToString("yyyy/MM/dd hh mm tt", ci);
DateTime parsed = DateTime.Parse(formatted, ci);
Assert.Equal(dt.Hour, parsed.Hour);
Assert.Equal(dt.Minute, parsed.Minute);
formatted = dt.ToString("yyyy/MM/dd hh mm ss tt", ci);
parsed = DateTime.Parse(formatted, ci);
Assert.Equal(dt, parsed);
}
[Fact]
public static void Parse_InvalidArguments_Throws()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.Parse(null));
AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.Parse(null, new MyFormatter()));
AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.Parse((string)null, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
Assert.Throws<FormatException>(() => DateTime.Parse(""));
Assert.Throws<FormatException>(() => DateTime.Parse("", new MyFormatter()));
Assert.Throws<FormatException>(() => DateTime.Parse("", new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
Assert.Throws<FormatException>(() => DateTime.Parse("2020-5-7T09:37:00.0000000-07:00c"));
Assert.Throws<FormatException>(() => DateTime.Parse("2020-5-7T09:37:00.0000000-07:00c", new MyFormatter()));
Assert.Throws<FormatException>(() => DateTime.Parse("2020-5-7T09:37:00.0000000-07:00c", new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
Assert.Throws<FormatException>(() => DateTime.Parse("2020-5-7T09:37:00.0000000+00:00#"));
Assert.Throws<FormatException>(() => DateTime.Parse("2020-5-7T09:37:00.0000000+00:00#", new MyFormatter()));
Assert.Throws<FormatException>(() => DateTime.Parse("2020-5-7T09:37:00.0000000+00:00#", new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
Assert.Throws<FormatException>(() => DateTime.Parse("2020-5-7T09:37:00.0000000+00:00#\0"));
Assert.Throws<FormatException>(() => DateTime.Parse("2020-5-7T09:37:00.0000000+00:00#\0", new MyFormatter()));
Assert.Throws<FormatException>(() => DateTime.Parse("2020-5-7T09:37:00.0000000+00:00#\0", new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
}
[Theory]
[InlineData(null)]
[InlineData("")]
public static void TryParse_NullOrEmptyString_ReturnsFalse(string input)
{
Assert.False(DateTime.TryParse(input, out DateTime result));
Assert.False(DateTime.TryParse(input, new MyFormatter(), DateTimeStyles.None, out result));
}
[Fact]
public static void ParseExact_InvalidArguments_Throws()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.ParseExact(null, "d", new MyFormatter()));
AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.ParseExact((string)null, "d", new MyFormatter(), DateTimeStyles.None));
AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.ParseExact((string)null, new[] { "d" }, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
Assert.Throws<FormatException>(() => DateTime.ParseExact("", "d", new MyFormatter()));
Assert.Throws<FormatException>(() => DateTime.ParseExact("", "d", new MyFormatter(), DateTimeStyles.None));
Assert.Throws<FormatException>(() => DateTime.ParseExact("", new[] { "d" }, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
AssertExtensions.Throws<ArgumentNullException>("format", () => DateTime.ParseExact("123", null, new MyFormatter()));
AssertExtensions.Throws<ArgumentNullException>("format", () => DateTime.ParseExact("123", (string)null, new MyFormatter(), DateTimeStyles.None));
AssertExtensions.Throws<ArgumentNullException>("formats", () => DateTime.ParseExact("123", (string[])null, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
Assert.Throws<FormatException>(() => DateTime.ParseExact("123", "", new MyFormatter()));
Assert.Throws<FormatException>(() => DateTime.ParseExact("123", "", new MyFormatter(), DateTimeStyles.None));
Assert.Throws<FormatException>(() => DateTime.ParseExact("123", new string[0], new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
Assert.Throws<FormatException>(() => DateTime.ParseExact("123", new string[] { null }, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
Assert.Throws<FormatException>(() => DateTime.ParseExact("123", new[] { "" }, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
}
[Fact]
public static void TryParseExact_InvalidArguments_ReturnsFalse()
{
Assert.False(DateTime.TryParseExact((string)null, "d", new MyFormatter(), DateTimeStyles.None, out DateTime result));
Assert.False(DateTime.TryParseExact((string)null, new[] { "d" }, new MyFormatter(), DateTimeStyles.None, out result));
Assert.False(DateTime.TryParseExact("", "d", new MyFormatter(), DateTimeStyles.None, out result));
Assert.False(DateTime.TryParseExact("", new[] { "d" }, new MyFormatter(), DateTimeStyles.None, out result));
Assert.False(DateTime.TryParseExact("abc", (string)null, new MyFormatter(), DateTimeStyles.None, out result));
Assert.False(DateTime.TryParseExact("abc", (string[])null, new MyFormatter(), DateTimeStyles.None, out result));
Assert.False(DateTime.TryParseExact("abc", "", new MyFormatter(), DateTimeStyles.None, out result));
Assert.False(DateTime.TryParseExact("abc", new string[0], new MyFormatter(), DateTimeStyles.None, out result));
Assert.False(DateTime.TryParseExact("abc", new string[] { null }, new MyFormatter(), DateTimeStyles.None, out result));
Assert.False(DateTime.TryParseExact("abc", new[] { "" }, new MyFormatter(), DateTimeStyles.None, out result));
Assert.False(DateTime.TryParseExact("abc", new[] { "" }, new MyFormatter(), DateTimeStyles.None, out result));
}
[Fact]
public static void TryParse_String()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("g");
DateTime result;
Assert.True(DateTime.TryParse(expectedString, out result));
Assert.Equal(expectedString, result.ToString("g"));
}
[Fact]
public static void TryParse_String_FormatProvider_DateTimeStyles_U()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("u");
DateTime result;
Assert.True(DateTime.TryParse(expectedString, null, DateTimeStyles.AdjustToUniversal, out result));
Assert.Equal(expectedString, result.ToString("u"));
}
[Fact]
public static void TryParse_String_FormatProvider_DateTimeStyles_G()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("g");
DateTime result;
Assert.True(DateTime.TryParse(expectedString, null, DateTimeStyles.AdjustToUniversal, out result));
Assert.Equal(expectedString, result.ToString("g"));
}
[Fact]
public static void TryParse_TimeDesignators_NetCore()
{
DateTime result;
Assert.True(DateTime.TryParse("4/21 5am", new CultureInfo("en-US"), DateTimeStyles.None, out result));
Assert.Equal(4, result.Month);
Assert.Equal(21, result.Day);
Assert.Equal(5, result.Hour);
Assert.True(DateTime.TryParse("4/21 5pm", new CultureInfo("en-US"), DateTimeStyles.None, out result));
Assert.Equal(4, result.Month);
Assert.Equal(21, result.Day);
Assert.Equal(17, result.Hour);
}
public static IEnumerable<object[]> StandardFormatSpecifiers()
{
yield return new object[] { "d" };
yield return new object[] { "D" };
yield return new object[] { "f" };
yield return new object[] { "F" };
yield return new object[] { "g" };
yield return new object[] { "G" };
yield return new object[] { "m" };
yield return new object[] { "M" };
yield return new object[] { "o" };
yield return new object[] { "O" };
yield return new object[] { "r" };
yield return new object[] { "R" };
yield return new object[] { "s" };
yield return new object[] { "t" };
yield return new object[] { "T" };
yield return new object[] { "u" };
yield return new object[] { "U" };
yield return new object[] { "y" };
yield return new object[] { "Y" };
}
[Theory]
[MemberData(nameof(StandardFormatSpecifiers))]
public static void ParseExact_ToStringThenParseExactRoundtrip_Success(string standardFormat)
{
var r = new Random(42);
for (int i = 0; i < 200; i++) // test with a bunch of random dates
{
DateTime dt = new DateTime(DateTime.MinValue.Ticks + (long)(r.NextDouble() * (DateTime.MaxValue.Ticks - DateTime.MinValue.Ticks)), DateTimeKind.Unspecified);
string expected = dt.ToString(standardFormat);
Assert.Equal(expected, DateTime.ParseExact(expected, standardFormat, null).ToString(standardFormat));
Assert.Equal(expected, DateTime.ParseExact(expected, standardFormat, null, DateTimeStyles.None).ToString(standardFormat));
Assert.Equal(expected, DateTime.ParseExact(expected, new[] { standardFormat }, null, DateTimeStyles.None).ToString(standardFormat));
Assert.Equal(expected, DateTime.ParseExact(expected, new[] { standardFormat }, null, DateTimeStyles.AllowWhiteSpaces).ToString(standardFormat));
Assert.True(DateTime.TryParseExact(expected, standardFormat, null, DateTimeStyles.None, out DateTime actual));
Assert.Equal(expected, actual.ToString(standardFormat));
Assert.True(DateTime.TryParseExact(expected, new[] { standardFormat }, null, DateTimeStyles.None, out actual));
Assert.Equal(expected, actual.ToString(standardFormat));
// Should also parse with Parse, though may not round trip exactly
DateTime.Parse(expected);
}
}
public static IEnumerable<object[]> InvalidFormatSpecifierRoundtripPairs()
{
yield return new object[] { "d", "f" };
yield return new object[] { "o", "r" };
yield return new object[] { "u", "y" };
}
[Theory]
[MemberData(nameof(InvalidFormatSpecifierRoundtripPairs))]
public static void ParseExact_ToStringThenParseExact_RoundtripWithOtherFormat_Fails(string toStringFormat, string parseFormat)
{
DateTime dt = DateTime.Now;
string expected = dt.ToString(toStringFormat);
Assert.Throws<FormatException>(() => DateTime.ParseExact(expected, parseFormat, null));
Assert.Throws<FormatException>(() => DateTime.ParseExact(expected, parseFormat, null, DateTimeStyles.None));
Assert.Throws<FormatException>(() => DateTime.ParseExact(expected, new[] { parseFormat }, null, DateTimeStyles.None));
Assert.False(DateTime.TryParseExact(expected, parseFormat, null, DateTimeStyles.None, out DateTime result));
Assert.False(DateTime.TryParseExact(expected, new[] { parseFormat }, null, DateTimeStyles.None, out result));
}
[Theory]
[MemberData(nameof(ParseExact_TestData_R))]
public static void ParseExact_String_String_FormatProvider_DateTimeStyles_R(DateTime dt, string input)
{
Assert.Equal(DateTimeKind.Unspecified, DateTime.ParseExact(input, "r", null).Kind);
Assert.Equal(dt.ToString("r"), DateTime.ParseExact(input, "r", null).ToString("r"));
Assert.Equal(dt.ToString("r"), DateTime.ParseExact(input, "r", null, DateTimeStyles.None).ToString("r"));
const string Whitespace = " \t\r\n ";
Assert.Equal(dt.ToString("r"), DateTime.ParseExact(Whitespace + input, "r", null, DateTimeStyles.AllowLeadingWhite).ToString("r"));
Assert.Equal(dt.ToString("r"), DateTime.ParseExact(input + Whitespace, "r", null, DateTimeStyles.AllowTrailingWhite).ToString("r"));
Assert.Equal(dt.ToString("r"), DateTime.ParseExact(
Whitespace +
input +
Whitespace, "r", null, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite).ToString("r"));
Assert.Equal(dt.ToString("r"), DateTime.ParseExact(
input.Substring(0, 4) +
Whitespace +
input.Substring(4), "r", null, DateTimeStyles.AllowInnerWhite).ToString("r"));
Assert.Equal(dt.ToString("r"), DateTime.ParseExact(
Whitespace +
input.Substring(0, 4) +
Whitespace +
input.Substring(4) +
Whitespace, "r", null, DateTimeStyles.AllowWhiteSpaces).ToString("r"));
}
public static IEnumerable<object[]> ParseExact_TestData_R()
{
// Lowest, highest, and random DateTime in lower, upper, and normal casing
var pairs = new(DateTime, string)[]
{
(DateTime.MaxValue, "Fri, 31 Dec 9999 23:59:59"),
(DateTime.MinValue, "Mon, 01 Jan 0001 00:00:00"),
(new DateTime(1906, 8, 15, 7, 24, 5, 300), "Wed, 15 Aug 1906 07:24:05"),
};
foreach ((DateTime, string) pair in pairs)
{
yield return new object[] { pair.Item1, pair.Item2 + " GMT" };
yield return new object[] { pair.Item1, pair.Item2.ToLowerInvariant() + " GMT" };
yield return new object[] { pair.Item1, pair.Item2.ToUpperInvariant() + " GMT" };
}
// All months
DateTime dt = DateTime.UtcNow;
for (int i = 0; i < 12; i++)
{
dt = dt.AddMonths(1);
yield return new object[] { dt, dt.ToString("R") };
}
// All days
for (int i = 0; i < 7; i++)
{
dt = dt.AddDays(1);
yield return new object[] { dt, dt.ToString("R") };
}
}
[Theory]
[MemberData(nameof(ParseExact_TestData_InvalidData_R))]
public static void ParseExact_InvalidData_R(string invalidString)
{
Assert.Throws<FormatException>(() => DateTime.ParseExact(invalidString, "r", null));
Assert.Throws<FormatException>(() => DateTime.ParseExact(invalidString, "r", null, DateTimeStyles.None));
Assert.Throws<FormatException>(() => DateTime.ParseExact(invalidString, new string[] { "r" }, null, DateTimeStyles.None));
}
public static IEnumerable<object[]> ParseExact_TestData_InvalidData_R()
{
yield return new object[] { "Thu, 15 Aug 1906 07:24:05 GMT" }; // invalid day of week
yield return new object[] { "Ste, 15 Aug 1906 07:24:05 GMT" }; // invalid day of week
yield return new object[] { "We, 15 Aug 1906 07:24:05 GMT" }; // too short day of week
yield return new object[] { "Wedn, 15 Aug 1906 07:24:05 GMT" }; // too long day of week
yield return new object[] { "Wed, 32 Aug 1906 07:24:05 GMT" }; // too large day
yield return new object[] { "Wed, -1 Aug 1906 07:24:05 GMT" }; // too small day
yield return new object[] { "Wed, 15 Au 1906 07:24:05 GMT" }; // too small month
yield return new object[] { "Wed, 15 August 1906 07:24:05 GMT" }; // too large month
yield return new object[] { "Wed, 15 Aug -1 07:24:05 GMT" }; // too small year
yield return new object[] { "Wed, 15 Aug 10000 07:24:05 GMT" }; // too large year
yield return new object[] { "Wed, 15 Aug 1906 24:24:05 GMT" }; // too large hour
yield return new object[] { "Wed, 15 Aug 1906 07:60:05 GMT" }; // too large minute
yield return new object[] { "Wed, 15 Aug 1906 07:24:60 GMT" }; // too large second
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 STE" }; // invalid timezone
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 GM" }; // too short timezone
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 GMTT" }; // too long timezone
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 gmt" }; // wrong casing
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 Z" }; // zulu invalid
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 UTC" }; // UTC invalid
yield return new object[] { " Wed, 15 Aug 1906 07:24:05 GMT" }; // whitespace before
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 GMT " }; // whitespace after
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 GMT" }; // extra whitespace middle
yield return new object[] { "Wed, 15 Aug 1906 07: 24:05 GMT" }; // extra whitespace middle
yield return new object[] { "Wed,\t15 Aug 1906 07:24:05 GMT" }; // wrong whitespace for first space
yield return new object[] { "Wed, 15\tAug 1906 07:24:05 GMT" }; // wrong whitespace for second space
yield return new object[] { "Wed, 15 Aug\t1906 07:24:05 GMT" }; // wrong whitespace for third space
yield return new object[] { "Wed, 15 Aug 1906\t07:24:05 GMT" }; // wrong whitespace for fourth space
yield return new object[] { "Wed, 15 Aug 1906 07:24:05\tGMT" }; // wrong whitespace for fifth space
yield return new object[] { "Wed; 15 Aug 1906 07:24:05 GMT" }; // wrong comma
yield return new object[] { "Wed\x642C 15 Aug 1906 07:24:05 GMT" }; // wrong comma
yield return new object[] { "Wed, 15 Aug 1906 07;24:05 GMT" }; // wrong first colon
yield return new object[] { "Wed, 15 Aug 1906 07:24;05 GMT" }; // wrong second colon
yield return new object[] { "\x2057ed, 15 Aug 1906 07:24:05 GMT" }; // invalid characters to validate ASCII checks on day of week
yield return new object[] { "W\x5765d, 15 Aug 1906 07:24:05 GMT" }; // invalid characters to validate ASCII checks on day of week
yield return new object[] { "We\x6564, 15 Aug 1906 07:24:05 GMT" }; // invalid characters to validate ASCII checks on day of week
yield return new object[] { "Wed, 15 \x2041ug 1906 07:24:05 GMT" }; // invalid characters to validate ASCII checks on month
yield return new object[] { "Wed, 15 A\x4175g 1906 07:24:05 GMT" }; // invalid characters to validate ASCII checks on month
yield return new object[] { "Wed, 15 Au\x7567 1906 07:24:05 GMT" }; // invalid characters to validate ASCII checks on month
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 \x2047MT" }; // invalid characters to validate ASCII checks on GMT
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 G\x474DT" }; // invalid characters to validate ASCII checks on GMT
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 GM\x4D54" }; // invalid characters to validate ASCII checks on GMT
yield return new object[] { "Wed, A5 Aug 1906 07:24:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 1A Aug 1906 07:24:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug A906 07:24:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug 1A06 07:24:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug 19A6 07:24:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug 190A 07:24:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug 1906 A7:24:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug 1906 0A:24:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug 1906 07:A4:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug 1906 07:2A:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug 1906 07:24:A5 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug 1906 07:24:0A GMT" }; // invalid digits
}
[Theory]
[MemberData(nameof(ParseExact_TestData_O))]
public static void ParseExact_String_String_FormatProvider_DateTimeStyles_O(DateTime dt, string input)
{
string expectedString;
if (input.Length == 27) // no timezone
{
Assert.Equal(DateTimeKind.Unspecified, DateTime.ParseExact(input, "o", null).Kind);
expectedString = dt.ToString("o");
}
else // "Z" or +/- offset
{
Assert.Equal(DateTimeKind.Local, DateTime.ParseExact(input, "o", null).Kind);
expectedString = dt.ToLocalTime().ToString("o");
}
Assert.Equal(expectedString, DateTime.ParseExact(input, "o", null).ToString("o"));
Assert.Equal(expectedString, DateTime.ParseExact(input, "o", null, DateTimeStyles.None).ToString("o"));
const string Whitespace = " \t\r\n ";
Assert.Equal(expectedString, DateTime.ParseExact(Whitespace + input, "o", null, DateTimeStyles.AllowLeadingWhite).ToString("o"));
Assert.Equal(expectedString, DateTime.ParseExact(input + Whitespace, "o", null, DateTimeStyles.AllowTrailingWhite).ToString("o"));
Assert.Equal(expectedString, DateTime.ParseExact(
Whitespace +
input +
Whitespace, "o", null, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite).ToString("o"));
Assert.Equal(expectedString, DateTime.ParseExact(
input.Substring(0, 27) +
Whitespace +
input.Substring(27), "o", null, DateTimeStyles.AllowInnerWhite).ToString("o"));
Assert.Equal(expectedString, DateTime.ParseExact(
Whitespace +
input.Substring(0, 27) +
Whitespace +
input.Substring(27) +
Whitespace, "o", null, DateTimeStyles.AllowWhiteSpaces).ToString("o"));
}
public static IEnumerable<object[]> ParseExact_TestData_O()
{
// Arbitrary DateTime in each of Unspecified, Utc, and Local kinds.
foreach (DateTimeKind kind in new[] { DateTimeKind.Unspecified, DateTimeKind.Utc, DateTimeKind.Local })
{
var dt = new DateTime(1234567891234567891, kind);
yield return new object[] { dt, dt.ToString("o") };
}
// Min and max in each of Unspecified, Utc, and Local kinds.
foreach (DateTime dt in new[] { DateTime.MinValue, DateTime.MaxValue })
{
yield return new object[] { dt, dt.ToString("o") };
yield return new object[] { dt.ToUniversalTime(), dt.ToUniversalTime().ToString("o") };
yield return new object[] { dt.ToLocalTime(), dt.ToLocalTime().ToString("o") };
}
// 1-digit offset hour is accepted due to legacy/compat
yield return new object[] { new DateTime(636664076235238523, DateTimeKind.Utc), "2018-07-05T18:36:43.5238523+1:23" };
}
[Theory]
[MemberData(nameof(ParseExact_TestData_InvalidData_O))]
public static void ParseExact_InvalidData_O(string invalidString)
{
Assert.Throws<FormatException>(() => DateTime.ParseExact(invalidString, "o", null));
Assert.Throws<FormatException>(() => DateTime.ParseExact(invalidString, "o", null, DateTimeStyles.None));
Assert.Throws<FormatException>(() => DateTime.ParseExact(invalidString, new string[] { "o" }, null, DateTimeStyles.None));
}
public static IEnumerable<object[]> ParseExact_TestData_InvalidData_O()
{
yield return new object[] { " 2018-07-05T18:36:43.5238523" }; // whitespace before
yield return new object[] { " 2018-07-05T18:36:43.5238523Z" }; // whitespace before
yield return new object[] { " 2018-07-05T18:36:43.5238523+00:00" }; // whitespace before
yield return new object[] { "2018-07-05T18:36:43.5238523 " }; // whitespace after
yield return new object[] { "2018-07-05T18:36:43.5238523Z " }; // whitespace after
yield return new object[] { "2018-07-05T18:36:43.5238523+00:00 " }; // whitespace after
yield return new object[] { "2018-07-05T18:36:43.5238523 Z" }; // whitespace inside
yield return new object[] { "2018-07-05T18:36:43.5238523 +00:00" }; // whitespace inside
yield return new object[] { "201-07-05T18:36:43.5238523" }; // too short year
yield return new object[] { "20181-07-05T18:36:43.5238523" }; // too long year
yield return new object[] { "2018-7-05T18:36:43.5238523" }; // too short month
yield return new object[] { "2018-017-05T18:36:43.5238523" }; // too long month
yield return new object[] { "2018-07-5T18:36:43.5238523" }; // too short day
yield return new object[] { "2018-07-015T18:36:43.5238523" }; // too long day
yield return new object[] { "2018-07-05T018:36:43.5238523" }; // too long hour
yield return new object[] { "2018-07-05T8:36:43.5238523" }; // too short hour
yield return new object[] { "2018-07-05T18:6:43.5238523" }; // too short minute
yield return new object[] { "2018-07-05T18:036:43.5238523" }; // too long minute
yield return new object[] { "2018-07-05T18:06:3.5238523" }; // too short second
yield return new object[] { "2018-07-05T18:36:043.5238523" }; // too long second
yield return new object[] { "2018-07-05T18:06:03.238523" }; // too short fraction
yield return new object[] { "2018-07-05T18:36:43.15238523" }; // too long fraction
yield return new object[] { "2018-07-05T18:36:43.5238523+001:00" }; // too long offset hour
yield return new object[] { "2018-07-05T18:36:43.5238523+01:0" }; // too short offset minute
yield return new object[] { "2018-07-05T18:36:43.5238523+01:000" }; // too long offset minute
yield return new object[] { "2018=07-05T18:36:43.5238523" }; // invalid first hyphen
yield return new object[] { "2018-07=05T18:36:43.5238523" }; // invalid second hyphen
yield return new object[] { "2018-07-05A18:36:43.5238523" }; // invalid T
yield return new object[] { "2018-07-05T18;36:43.5238523" }; // invalid first colon
yield return new object[] { "2018-07-05T18:36;43.5238523" }; // invalid second colon
yield return new object[] { "2018-07-05T18:36:43,5238523" }; // invalid period
yield return new object[] { "2018-07-05T18:36:43.5238523,00:00" }; // invalid +/-/Z
yield return new object[] { "2018-07-05T18:36:43.5238523+00;00" }; // invalid third colon
yield return new object[] { "2018-07-05T18:36:43.5238523+1;00" }; // invalid colon with 1-digit offset hour
yield return new object[] { "a018-07-05T18:36:43.5238523" }; // invalid digits
yield return new object[] { "2a18-07-05T18:36:43.5238523" }; // invalid digits
yield return new object[] { "20a8-07-05T18:36:43.5238523" }; // invalid digits
yield return new object[] { "201a-07-05T18:36:43.5238523" }; // invalid digits
yield return new object[] { "2018-a7-05T18:36:43.5238523" }; // invalid digits
yield return new object[] { "2018-0a-05T18:36:43.5238523" }; // invalid digits
yield return new object[] { "2018-07-a5T18:36:43.5238523" }; // invalid digits
yield return new object[] { "2018-07-0aT18:36:43.5238523" }; // invalid digits
yield return new object[] { "2018-07-05Ta8:36:43.5238523" }; // invalid digits
yield return new object[] { "2018-07-05T1a:36:43.5238523" }; // invalid digits
yield return new object[] { "2018-07-05T18:a6:43.5238523" }; // invalid digits
yield return new object[] { "2018-07-05T18:3a:43.5238523" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:a3.5238523" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:4a.5238523" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.a238523" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.5a38523" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.52a8523" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.523a523" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.5238a23" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.52385a3" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.523852a" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.5238523+a0:00" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.5238523+0a:00" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.5238523+00:a0" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.5238523+00:0a" }; // invalid digits
}
[Fact]
public static void ParseExact_String_String_FormatProvider_DateTimeStyles_CustomFormatProvider()
{
var formatter = new MyFormatter();
string dateBefore = DateTime.Now.ToString();
DateTime dateAfter = DateTime.ParseExact(dateBefore, "G", formatter, DateTimeStyles.AdjustToUniversal);
Assert.Equal(dateBefore, dateAfter.ToString());
}
[Fact]
public static void ParseExact_String_StringArray_FormatProvider_DateTimeStyles()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("g");
var formats = new string[] { "g" };
DateTime result = DateTime.ParseExact(expectedString, formats, null, DateTimeStyles.AdjustToUniversal);
Assert.Equal(expectedString, result.ToString("g"));
}
[Fact]
public static void TryParseExact_String_String_FormatProvider_DateTimeStyles_NullFormatProvider()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("g");
DateTime resulted;
Assert.True(DateTime.TryParseExact(expectedString, "g", null, DateTimeStyles.AdjustToUniversal, out resulted));
Assert.Equal(expectedString, resulted.ToString("g"));
}
[Fact]
public static void TryParseExact_String_StringArray_FormatProvider_DateTimeStyles()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("g");
var formats = new string[] { "g" };
DateTime result;
Assert.True(DateTime.TryParseExact(expectedString, formats, null, DateTimeStyles.AdjustToUniversal, out result));
Assert.Equal(expectedString, result.ToString("g"));
}
[Fact]
// Regression test for https://github.com/dotnet/runtime/issues/9565
public static void TryParseExact_EmptyAMPMDesignator()
{
var englishCulture = new CultureInfo("en-US");
englishCulture.DateTimeFormat.AMDesignator = "";
englishCulture.DateTimeFormat.PMDesignator = "";
Assert.False(DateTime.TryParseExact(" ", "%t", englishCulture, DateTimeStyles.None, out _));
}
[Fact]
public static void ParseExact_EscapedSingleQuotes()
{
DateTimeFormatInfo formatInfo;
if (PlatformDetection.IsBrowser)
{
formatInfo = DateTimeFormatInfo.GetInstance(new CultureInfo("id-ID"));
}
else
{
formatInfo = DateTimeFormatInfo.GetInstance(new CultureInfo("mt-MT"));
}
const string format = @"dddd, d' ta\' 'MMMM yyyy";
DateTime expected = new DateTime(1999, 2, 28, 17, 00, 01);
string formatted = expected.ToString(format, formatInfo);
DateTime actual = DateTime.ParseExact(formatted, format, formatInfo);
Assert.Equal(expected.Date, actual.Date);
}
[Theory]
[InlineData("fi-FI")]
[InlineData("nb-NO")]
[InlineData("nb-SJ")]
[InlineData("sr-Cyrl-XK")]
[InlineData("sr-Latn-ME")]
[InlineData("sr-Latn-RS")]
[InlineData("sr-Latn-XK")]
public static void Parse_SpecialCultures(string cultureName)
{
// Test DateTime parsing with cultures which has the date separator and time separator are same
CultureInfo cultureInfo;
try
{
cultureInfo = new CultureInfo(cultureName);
}
catch (CultureNotFoundException)
{
// Ignore un-supported culture in current platform
return;
}
var dateTime = new DateTime(2015, 11, 20, 11, 49, 50);
string dateString = dateTime.ToString(cultureInfo.DateTimeFormat.ShortDatePattern, cultureInfo);
DateTime parsedDate;
Assert.True(DateTime.TryParse(dateString, cultureInfo, DateTimeStyles.None, out parsedDate));
if (cultureInfo.DateTimeFormat.ShortDatePattern.Contains("yyyy") || HasDifferentDateTimeSeparators(cultureInfo.DateTimeFormat))
{
Assert.Equal(dateTime.Date, parsedDate);
}
else
{
// When the date separator and time separator are the same, DateTime.TryParse cannot
// tell the difference between a short date like dd.MM.yy and a short time
// like HH.mm.ss. So it assumes that if it gets 03.04.11, that must be a time
// and uses the current date to construct the date time.
DateTime now = DateTime.Now;
Assert.Equal(new DateTime(now.Year, now.Month, now.Day, dateTime.Day, dateTime.Month, dateTime.Year % 100), parsedDate);
}
dateString = dateTime.ToString(cultureInfo.DateTimeFormat.LongDatePattern, cultureInfo);
Assert.True(DateTime.TryParse(dateString, cultureInfo, DateTimeStyles.None, out parsedDate));
Assert.Equal(dateTime.Date, parsedDate);
dateString = dateTime.ToString(cultureInfo.DateTimeFormat.FullDateTimePattern, cultureInfo);
Assert.True(DateTime.TryParse(dateString, cultureInfo, DateTimeStyles.None, out parsedDate));
Assert.Equal(dateTime, parsedDate);
dateString = dateTime.ToString(cultureInfo.DateTimeFormat.LongTimePattern, cultureInfo);
Assert.True(DateTime.TryParse(dateString, cultureInfo, DateTimeStyles.None, out parsedDate));
Assert.Equal(dateTime.TimeOfDay, parsedDate.TimeOfDay);
}
private static bool HasDifferentDateTimeSeparators(DateTimeFormatInfo dateTimeFormat)
{
// Since .NET Core doesn't expose DateTimeFormatInfo DateSeparator and TimeSeparator properties,
// this method gets the separators using DateTime.ToString by passing in the invariant separators.
// The invariant separators will then get turned into the culture's separators by ToString,
// which are then compared.
var dateTime = new DateTime(2015, 11, 24, 17, 57, 29);
string separators = dateTime.ToString("/@:", dateTimeFormat);
int delimiterIndex = separators.IndexOf('@');
string dateSeparator = separators.Substring(0, delimiterIndex);
string timeSeparator = separators.Substring(delimiterIndex + 1);
return dateSeparator != timeSeparator;
}
[Fact]
public static void GetDateTimeFormats()
{
var allStandardFormats = new char[]
{
'd', 'D', 'f', 'F', 'g', 'G',
'm', 'M', 'o', 'O', 'r', 'R',
's', 't', 'T', 'u', 'U', 'y', 'Y',
};
var dateTime = new DateTime(2009, 7, 28, 5, 23, 15);
var formats = new List<string>();
foreach (char format in allStandardFormats)
{
string[] dates = dateTime.GetDateTimeFormats(format);
Assert.True(dates.Length > 0);
DateTime parsedDate;
Assert.True(DateTime.TryParseExact(dates[0], format.ToString(), CultureInfo.CurrentCulture, DateTimeStyles.None, out parsedDate));
formats.AddRange(dates);
}
List<string> actualFormats = dateTime.GetDateTimeFormats().ToList();
Assert.Equal(formats.OrderBy(t => t), actualFormats.OrderBy(t => t));
actualFormats = dateTime.GetDateTimeFormats(CultureInfo.CurrentCulture).ToList();
Assert.Equal(formats.OrderBy(t => t), actualFormats.OrderBy(t => t));
}
[Fact]
public static void GetDateTimeFormats_FormatSpecifier_InvalidFormat()
{
var dateTime = new DateTime(2009, 7, 28, 5, 23, 15);
Assert.Throws<FormatException>(() => dateTime.GetDateTimeFormats('x')); // No such format
}
private static void VerifyDateTime(DateTime dateTime, int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind)
{
Assert.Equal(year, dateTime.Year);
Assert.Equal(month, dateTime.Month);
Assert.Equal(day, dateTime.Day);
Assert.Equal(hour, dateTime.Hour);
Assert.Equal(minute, dateTime.Minute);
Assert.Equal(second, dateTime.Second);
Assert.Equal(millisecond, dateTime.Millisecond);
Assert.Equal(kind, dateTime.Kind);
}
private class MyFormatter : IFormatProvider
{
public object GetFormat(Type formatType)
{
return typeof(IFormatProvider) == formatType ? this : null;
}
}
[Fact]
public static void InvalidDateTimeStyles()
{
string strDateTime = "Thursday, August 31, 2006 1:14";
string[] formats = new string[] { "f" };
IFormatProvider provider = new CultureInfo("en-US");
DateTimeStyles style = DateTimeStyles.AssumeLocal | DateTimeStyles.AssumeUniversal;
AssertExtensions.Throws<ArgumentException>("style", () => DateTime.ParseExact(strDateTime, formats, provider, style));
}
[Fact]
public static void TestTryParseAtBoundaries()
{
Assert.True(DateTime.TryParse("9999-12-31T23:59:59.9999999", out var maxDateTime),
"DateTime parsing expected to succeed at the boundary DateTime.MaxValue");
Assert.Equal(DateTime.MaxValue, maxDateTime);
Assert.False(DateTime.TryParse("9999-12-31T23:59:59.999999999Z", out var dateTime),
"DateTime parsing expected to throw with any dates greater than DateTime.MaxValue");
}
public static IEnumerable<object[]> Parse_ValidInput_Succeeds_MemberData()
{
yield return new object[] { "1234 12", CultureInfo.InvariantCulture, new DateTime(1234, 12, 1, 0, 0, 0) };
yield return new object[] { "12 1234", CultureInfo.InvariantCulture, new DateTime(1234, 12, 1, 0, 0, 0) };
yield return new object[] { "12 1234 11", CultureInfo.InvariantCulture, new DateTime(1234, 12, 11, 0, 0, 0) };
yield return new object[] { "1234 12 13", CultureInfo.InvariantCulture, new DateTime(1234, 12, 13, 0, 0, 0) };
yield return new object[] { "12 13 1234", CultureInfo.InvariantCulture, new DateTime(1234, 12, 13, 0, 0, 0) };
yield return new object[] { "1 1 1", CultureInfo.InvariantCulture, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "2 2 2Z", CultureInfo.InvariantCulture, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2002, 2, 2, 0, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
yield return new object[] { "#10/10/2095#\0", CultureInfo.InvariantCulture, new DateTime(2095, 10, 10, 0, 0, 0) };
yield return new object[] { "2020-5-7T09:37:00.0000000+00:00\0", CultureInfo.InvariantCulture, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2020, 5, 7, 9, 37, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
yield return new object[] { "#2020-5-7T09:37:00.0000000+00:00#", CultureInfo.InvariantCulture, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2020, 5, 7, 9, 37, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
yield return new object[] { "#2020-5-7T09:37:00.0000000+00:00#\0", CultureInfo.InvariantCulture, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2020, 5, 7, 9, 37, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
yield return new object[] { "2020-5-7T09:37:00.0000000+00:00", CultureInfo.InvariantCulture, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2020, 5, 7, 9, 37, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
if (PlatformDetection.IsNotInvariantGlobalization)
{
DateTime today = DateTime.Today;
var hebrewCulture = new CultureInfo("he-IL");
hebrewCulture.DateTimeFormat.Calendar = new HebrewCalendar();
yield return new object[] { today.ToString(hebrewCulture), hebrewCulture, today };
CultureInfo culture;
if (PlatformDetection.IsBrowser)
{
culture = new CultureInfo("pl-PL");
}
else
{
culture = new CultureInfo("mn-MN");
}
yield return new object[] { today.ToString(culture), culture, today };
}
}
[Theory]
[MemberData(nameof(Parse_ValidInput_Succeeds_MemberData))]
public static void Parse_ValidInput_Succeeds(string input, CultureInfo culture, DateTime? expected)
{
Assert.Equal(expected, DateTime.Parse(input, culture));
}
public static IEnumerable<object[]> ParseExact_ValidInput_Succeeds_MemberData()
{
foreach (DateTimeStyles style in new[] { DateTimeStyles.None, DateTimeStyles.AllowWhiteSpaces })
{
yield return new object[] { "9", "%d", CultureInfo.InvariantCulture, style, new DateTime(DateTime.Now.Year, 1, 9, 0, 0, 0) };
yield return new object[] { "15", "dd", CultureInfo.InvariantCulture, style, new DateTime(DateTime.Now.Year, 1, 15, 0, 0, 0) };
yield return new object[] { "9", "%M", CultureInfo.InvariantCulture, style, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "09", "MM", CultureInfo.InvariantCulture, style, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "Sep", "MMM", CultureInfo.InvariantCulture, style, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "September", "MMMM", CultureInfo.InvariantCulture, style, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "1", "%y", CultureInfo.InvariantCulture, style, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "01", "yy", CultureInfo.InvariantCulture, style, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "2001", "yyyy", CultureInfo.InvariantCulture, style, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "3", "%H", CultureInfo.InvariantCulture, style, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "03", "HH", CultureInfo.InvariantCulture, style, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "3A", "ht", CultureInfo.InvariantCulture, style, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "03A", "hht", CultureInfo.InvariantCulture, style, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "3P", "ht", CultureInfo.InvariantCulture, style, DateTime.Today + TimeSpan.FromHours(12 + 3) };
yield return new object[] { "03P", "hht", CultureInfo.InvariantCulture, style, DateTime.Today + TimeSpan.FromHours(12 + 3) };
yield return new object[] { "2017-10-11 01:23:45Z", "u", CultureInfo.InvariantCulture, style, new DateTime(2017, 10, 11, 1, 23, 45) };
yield return new object[] { "9/8/2017 10:11:12 AM", "M/d/yyyy HH':'mm':'ss tt", CultureInfo.InvariantCulture, style, new DateTime(2017, 9, 8, 10, 11, 12) };
yield return new object[] { "9/8/2017 20:11:12 PM", "M/d/yyyy HH':'mm':'ss tt", CultureInfo.InvariantCulture, style, new DateTime(2017, 9, 8, 20, 11, 12) };
yield return new object[] { "Fri, 08 Sep 2017 11:18:19 -0000", "ddd, d MMM yyyy H:m:s zzz", new CultureInfo("en-US"), DateTimeStyles.AllowInnerWhite, new DateTime(2017, 9, 8, 11, 18, 19, DateTimeKind.Utc) };
yield return new object[] { "1234-05-06T07:00:00.8Z", "yyyy-MM-dd'T'HH:mm:ss.FFF'Z'", CultureInfo.InvariantCulture, style, new DateTime(1234, 5, 6, 7, 0, 0, 800) };
yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ss.FFF'Z'", CultureInfo.InvariantCulture, style, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ssFFF'Z'", CultureInfo.InvariantCulture, style, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ssFFF'Z'", CultureInfo.InvariantCulture, style, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ssFFFZ", CultureInfo.InvariantCulture, style, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1234, 5, 6, 7, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
yield return new object[] { "1234-05-06T07:00:00GMT", "yyyy-MM-dd'T'HH:mm:ssFFFZ", CultureInfo.InvariantCulture, style, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1234, 5, 6, 7, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
}
yield return new object[] { "9", "\" \"%d", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(DateTime.Now.Year, 1, 9, 0, 0, 0) };
yield return new object[] { "15", "\' \'dd", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(DateTime.Now.Year, 1, 15, 0, 0, 0) };
yield return new object[] { "9", "\" \"%M", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "09", "\" \"MM", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "Sep", "\" \"MMM", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "September", "\' \'MMMM", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "1", "\' \'%y", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "01", "\" \"yy", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "2001", "\" \"yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "3", "\" \"%H", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "03", "\" \"HH", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "3A", "\" \"ht", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "03A", "\" \"hht", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "3P", "\' \'ht", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, DateTime.Today + TimeSpan.FromHours(12 + 3) };
yield return new object[] { "03P", "\" \"hht", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, DateTime.Today + TimeSpan.FromHours(12 + 3) };
yield return new object[] { "2017-10-11 01:23:45Z", "u", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(2017, 10, 11, 1, 23, 45) };
yield return new object[] { "9/8/2017 10:11:12 AM", "\' \'M/d/yyyy HH':'mm':'ss tt", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(2017, 9, 8, 10, 11, 12) };
yield return new object[] { "9/8/2017 20:11:12 PM", "\" \"M/d/yyyy HH':'mm':'ss tt", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(2017, 9, 8, 20, 11, 12) };
yield return new object[] { "1234-05-06T07:00:00.8Z", "\" \"yyyy-MM-dd'T'HH:mm:ss.FFF'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(1234, 5, 6, 7, 0, 0, 800) };
yield return new object[] { "1234-05-06T07:00:00Z", "\" \"yyyy-MM-dd'T'HH:mm:ss.FFF'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
yield return new object[] { "1234-05-06T07:00:00Z", "\' \'yyyy-MM-dd'T'HH:mm:ssFFF'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
yield return new object[] { "1234-05-06T07:00:00Z", "\' \'yyyy-MM-dd'T'HH:mm:ssFFF'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
yield return new object[] { "1234-05-06T07:00:00Z", "\" \"yyyy-MM-dd'T'HH:mm:ssFFFZ", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1234, 5, 6, 7, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
yield return new object[] { "1234-05-06T07:00:00GMT", "\" \"yyyy-MM-dd'T'HH:mm:ssFFFZ", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1234, 5, 6, 7, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
yield return new object[] { "9", "%d\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(DateTime.Now.Year, 1, 9, 0, 0, 0) };
yield return new object[] { "15", "dd\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(DateTime.Now.Year, 1, 15, 0, 0, 0) };
yield return new object[] { "9", "%M\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "09", "MM\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "Sep", "MMM\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "September", "MMMM\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "1", "%y\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "01", "yy\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "2001", "yyyy\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "3", "%H\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "03", "HH\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "3A", "ht\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "03A", "hht\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "3P", "ht\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, DateTime.Today + TimeSpan.FromHours(12 + 3) };
yield return new object[] { "03P", "hht\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, DateTime.Today + TimeSpan.FromHours(12 + 3) };
yield return new object[] { "2017-10-11 01:23:45Z", "u", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(2017, 10, 11, 1, 23, 45) };
yield return new object[] { "9/8/2017 10:11:12 AM", "M/d/yyyy HH':'mm':'ss tt\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(2017, 9, 8, 10, 11, 12) };
yield return new object[] { "9/8/2017 20:11:12 PM", "M/d/yyyy HH':'mm':'ss tt\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(2017, 9, 8, 20, 11, 12) };
yield return new object[] { "1234-05-06T07:00:00.8Z", "yyyy-MM-dd'T'HH:mm:ss.FFF'Z'\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(1234, 5, 6, 7, 0, 0, 800) };
yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ss.FFF'Z'\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ssFFF'Z'\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ssFFF'Z'\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ssFFFZ\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1234, 5, 6, 7, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
yield return new object[] { "1234-05-06T07:00:00GMT", "yyyy-MM-dd'T'HH:mm:ssFFFZ\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1234, 5, 6, 7, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
yield return new object[] { "9/8/2017 10:11:12 AM ", "M/d/yyyy HH':'mm':'ss tt\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, new DateTime(2017, 9, 8, 10, 11, 12) };
yield return new object[] { "9/8/2017 10:11:12 AM ", "M/d/yyyy HH':'mm':'ss tt\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, new DateTime(2017, 9, 8, 10, 11, 12) };
yield return new object[] { "9/ 8 /2017 10:11:12 AM ", "M/d/yyyy HH':'mm':'ss tt\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, new DateTime(2017, 9, 8, 10, 11, 12) };
yield return new object[] { " 9 /8/2017 10:11:12 AM", "M/d/yyyy HH':'mm':'ss tt\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, new DateTime(2017, 9, 8, 10, 11, 12) };
yield return new object[] { "9/8/2017 10 : 11 : 12 AM", "M/d/yyyy HH':'mm':'ss tt\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, new DateTime(2017, 9, 8, 10, 11, 12) };
yield return new object[] { " 9 / 8 / 2017 10 : 11 : 12 AM", "M/d/yyyy HH':'mm':'ss tt\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, new DateTime(2017, 9, 8, 10, 11, 12) };
yield return new object[] { " 9 / 8 / 2017 10 : 11 : 12 AM", "M/d/yyyy HH':'mm':'ss tt\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, new DateTime(2017, 9, 8, 10, 11, 12) };
if (PlatformDetection.IsNotInvariantGlobalization)
{
var hebrewCulture = new CultureInfo("he-IL");
hebrewCulture.DateTimeFormat.Calendar = new HebrewCalendar();
DateTime today = DateTime.Today;
foreach (string pattern in hebrewCulture.DateTimeFormat.GetAllDateTimePatterns())
{
yield return new object[] { today.ToString(pattern, hebrewCulture), pattern, hebrewCulture, DateTimeStyles.None, null };
}
}
}
[Theory]
[MemberData(nameof(ParseExact_ValidInput_Succeeds_MemberData))]
public static void ParseExact_ValidInput_Succeeds(string input, string format, CultureInfo culture, DateTimeStyles style, DateTime? expected)
{
DateTime result1 = DateTime.ParseExact(input, format, culture, style);
DateTime result2 = DateTime.ParseExact(input, new[] { format }, culture, style);
Assert.True(DateTime.TryParseExact(input, format, culture, style, out DateTime result3));
Assert.True(DateTime.TryParseExact(input, new[] { format }, culture, style, out DateTime result4));
Assert.Equal(result1, result2);
Assert.Equal(result1, result3);
Assert.Equal(result1, result4);
if (expected != null) // some inputs don't roundtrip well
{
// Normalize values to make comparison easier
if (expected.Value.Kind != DateTimeKind.Utc)
{
expected = expected.Value.ToUniversalTime();
}
if (result1.Kind != DateTimeKind.Utc)
{
result1 = result1.ToUniversalTime();
}
Assert.Equal(expected, result1);
}
}
public static IEnumerable<object[]> ParseExact_InvalidInputs_Fail_MemberData()
{
yield return new object[] { "6/28/2004 13:00:00 AM", "M/d/yyyy HH':'mm':'ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "6/28/2004 03:00:00 PM", "M/d/yyyy HH':'mm':'ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "1", "dd", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "99", "dd", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "123", "dd", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "1", "mm", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "99", "mm", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "123", "mm", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "1", "ss", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "99", "ss", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "123", "ss", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "1", "MM", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "99", "MM", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "Fep", "MMM", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "Jantember", "MMMM", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "123", "YY", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "12345", "YYYY", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "1", "HH", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "99", "HH", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "123", "HH", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "1", "hh", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "99", "hh", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "123", "hh", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "1", "ff", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "123", "ff", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "123456", "fffff", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "1234", "fffff", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "AM", "t", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "PM", "t", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "PM", "ttt", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "AAM", "tt", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "CM", "tt", CultureInfo.InvariantCulture, DateTimeStyles.None };
}
[Theory]
[MemberData(nameof(ParseExact_InvalidInputs_Fail_MemberData))]
public static void ParseExact_InvalidInputs_Fail(string input, string format, CultureInfo culture, DateTimeStyles style)
{
Assert.Throws<FormatException>(() => DateTime.ParseExact(input, format, culture, style));
Assert.Throws<FormatException>(() => DateTime.ParseExact(input, new[] { format }, culture, style));
Assert.False(DateTime.TryParseExact(input, format, culture, style, out DateTime result));
Assert.False(DateTime.TryParseExact(input, new[] { format }, culture, style, out result));
}
public static IEnumerable<object[]> ToString_MatchesExpected_MemberData()
{
// Randomly generated data on .NET Framework with:
// using System;
// class Program
// {
// static void Main()
// {
// var rand = new Random(42);
// var bytes = new byte[8];
// int i = 0;
// while (i < 40)
// {
// DateTimeKind kind = rand.Next(2) == 0 ? DateTimeKind.Utc : DateTimeKind.Unspecified;
// string format;
// switch (rand.Next(4))
// {
// case 0: format = "o"; break;
// case 1: format = "O"; break;
// case 2: format = "r"; break;
// default: format = "R"; break;
// }
//
// try
// {
// rand.NextBytes(bytes);
// long seed = BitConverter.ToInt64(bytes, 0);
// var dt = new DateTime(seed, kind);
// Console.WriteLine($"yield return new object[] {{ new DateTime({seed}, DateTimeKind.{kind}), \"{format}\", null, \"{dt.ToString(format)}\" }};");
// i++;
// }
// catch { }
// }
// }
//}
yield return new object[] { new DateTime(2688006240964947440, DateTimeKind.Utc), "O", null, "8518-12-15T08:01:36.4947440Z" };
yield return new object[] { new DateTime(2461197105169450509, DateTimeKind.Utc), "r", null, "Sun, 23 Mar 7800 18:15:16 GMT" };
yield return new object[] { new DateTime(71363981510699949, DateTimeKind.Unspecified), "R", null, "Fri, 23 Feb 0227 04:49:11 GMT" };
yield return new object[] { new DateTime(1678426538898407093, DateTimeKind.Unspecified), "R", null, "Fri, 22 Sep 5319 07:24:49 GMT" };
yield return new object[] { new DateTime(2689041307785948711, DateTimeKind.Utc), "o", null, "8522-03-27T07:52:58.5948711Z" };
yield return new object[] { new DateTime(996610247053299209, DateTimeKind.Unspecified), "r", null, "Thu, 19 Feb 3159 01:58:25 GMT" };
yield return new object[] { new DateTime(3105391438361510074, DateTimeKind.Unspecified), "R", null, "Fri, 06 Aug 9841 01:17:16 GMT" };
yield return new object[] { new DateTime(946433487657072106, DateTimeKind.Utc), "R", null, "Mon, 17 Feb 3000 03:06:05 GMT" };
yield return new object[] { new DateTime(2521748413631767931, DateTimeKind.Unspecified), "R", null, "Sat, 08 Feb 7992 07:02:43 GMT" };
yield return new object[] { new DateTime(49349519375012969, DateTimeKind.Utc), "R", null, "Fri, 20 May 0157 11:58:57 GMT" };
yield return new object[] { new DateTime(796677276139881359, DateTimeKind.Utc), "o", null, "2525-07-28T04:20:13.9881359Z" };
yield return new object[] { new DateTime(3022911536338429542, DateTimeKind.Unspecified), "R", null, "Mon, 24 Mar 9580 04:53:53 GMT" };
yield return new object[] { new DateTime(1144652135553351618, DateTimeKind.Utc), "R", null, "Tue, 04 Apr 3628 20:39:15 GMT" };
yield return new object[] { new DateTime(2570858096011770291, DateTimeKind.Unspecified), "o", null, "8147-09-23T04:53:21.1770291" };
yield return new object[] { new DateTime(15695724649124585, DateTimeKind.Unspecified), "R", null, "Tue, 27 Sep 0050 08:21:04 GMT" };
yield return new object[] { new DateTime(1503933934291527034, DateTimeKind.Unspecified), "O", null, "4766-10-12T06:37:09.1527034" };
yield return new object[] { new DateTime(2688603665097410101, DateTimeKind.Unspecified), "r", null, "Tue, 05 Nov 8520 19:08:29 GMT" };
yield return new object[] { new DateTime(1310336900529542610, DateTimeKind.Unspecified), "r", null, "Tue, 17 Apr 4153 15:14:12 GMT" };
yield return new object[] { new DateTime(2313720085584182693, DateTimeKind.Unspecified), "O", null, "7332-11-20T18:22:38.4182693" };
yield return new object[] { new DateTime(2291958603891779335, DateTimeKind.Unspecified), "o", null, "7263-12-05T20:46:29.1779335" };
yield return new object[] { new DateTime(262036413643976979, DateTimeKind.Unspecified), "o", null, "0831-05-12T21:16:04.3976979" };
yield return new object[] { new DateTime(684781207384421044, DateTimeKind.Utc), "O", null, "2170-12-26T20:12:18.4421044Z" };
yield return new object[] { new DateTime(1444462249169683325, DateTimeKind.Utc), "r", null, "Mon, 27 Apr 4578 07:21:56 GMT" };
yield return new object[] { new DateTime(1155518137384061537, DateTimeKind.Unspecified), "r", null, "Sun, 10 Sep 3662 06:02:18 GMT" };
yield return new object[] { new DateTime(2333390479532380569, DateTimeKind.Unspecified), "O", null, "7395-03-22T10:12:33.2380569" };
yield return new object[] { new DateTime(2217528014591554502, DateTimeKind.Unspecified), "R", null, "Sat, 26 Jan 7028 08:24:19 GMT" };
yield return new object[] { new DateTime(2764551324904480205, DateTimeKind.Utc), "O", null, "8761-07-08T04:21:30.4480205Z" };
yield return new object[] { new DateTime(2880903932678729712, DateTimeKind.Utc), "O", null, "9130-03-23T13:14:27.8729712Z" };
yield return new object[] { new DateTime(507699902578704433, DateTimeKind.Utc), "O", null, "1609-11-02T15:04:17.8704433Z" };
yield return new object[] { new DateTime(2429953022324426129, DateTimeKind.Utc), "O", null, "7701-03-20T15:03:52.4426129Z" };
yield return new object[] { new DateTime(603147512164908366, DateTimeKind.Unspecified), "O", null, "1912-04-20T09:33:36.4908366" };
yield return new object[] { new DateTime(2900400428644841236, DateTimeKind.Utc), "R", null, "Thu, 02 Jan 9192 22:34:24 GMT" };
yield return new object[] { new DateTime(1710845568474490805, DateTimeKind.Utc), "O", null, "5422-06-16T08:00:47.4490805Z" };
yield return new object[] { new DateTime(2988999715803714268, DateTimeKind.Utc), "r", null, "Sun, 06 Oct 9472 09:53:00 GMT" };
yield return new object[] { new DateTime(1068133489112689365, DateTimeKind.Utc), "r", null, "Wed, 12 Oct 3385 14:41:51 GMT" };
yield return new object[] { new DateTime(798784044525059284, DateTimeKind.Unspecified), "R", null, "Mon, 31 Mar 2532 13:40:52 GMT" };
yield return new object[] { new DateTime(2561736813034040593, DateTimeKind.Utc), "O", null, "8118-10-28T03:55:03.4040593Z" };
yield return new object[] { new DateTime(1677975383149674547, DateTimeKind.Utc), "o", null, "5318-04-18T03:18:34.9674547Z" };
yield return new object[] { new DateTime(1101778442151366156, DateTimeKind.Utc), "O", null, "3492-05-25T12:43:35.1366156Z" };
yield return new object[] { new DateTime(221550163152616218, DateTimeKind.Utc), "r", null, "Sun, 25 Jan 0703 19:11:55 GMT" };
// Year patterns
if (PlatformDetection.IsNotInvariantGlobalization)
{
var enUS = new CultureInfo("en-US");
var thTH = new CultureInfo("th-TH");
yield return new object[] { new DateTime(1234, 5, 6), "yy", enUS, "34" };
yield return new object[] { DateTime.MaxValue, "yy", thTH, "42" };
for (int i = 3; i < 20; i++)
{
yield return new object[] { new DateTime(1234, 5, 6), new string('y', i), enUS, 1234.ToString("D" + i) };
yield return new object[] { DateTime.MaxValue, new string('y', i), thTH, 10542.ToString("D" + i) };
}
}
else
{
var invariant = new CultureInfo("");
yield return new object[] { new DateTime(1234, 5, 6), "yy", invariant, "34" };
for (int i = 3; i < 20; i++)
{
yield return new object[] { new DateTime(1234, 5, 6), new string('y', i), invariant, 1234.ToString("D" + i) };
}
}
}
[Theory]
[MemberData(nameof(Parse_ValidInput_Succeeds_MemberData))]
public static void Parse_Span_ValidInput_Succeeds(string input, CultureInfo culture, DateTime? expected)
{
Assert.Equal(expected, DateTime.Parse(input.AsSpan(), culture));
}
[Theory]
[MemberData(nameof(ParseExact_ValidInput_Succeeds_MemberData))]
public static void ParseExact_Span_ValidInput_Succeeds(string input, string format, CultureInfo culture, DateTimeStyles style, DateTime? expected)
{
DateTime result1 = DateTime.ParseExact(input.AsSpan(), format, culture, style);
DateTime result2 = DateTime.ParseExact(input.AsSpan(), new[] { format }, culture, style);
Assert.True(DateTime.TryParseExact(input.AsSpan(), format, culture, style, out DateTime result3));
Assert.True(DateTime.TryParseExact(input.AsSpan(), new[] { format }, culture, style, out DateTime result4));
Assert.Equal(result1, result2);
Assert.Equal(result1, result3);
Assert.Equal(result1, result4);
if (expected != null) // some inputs don't roundtrip well
{
// Normalize values to make comparison easier
if (expected.Value.Kind != DateTimeKind.Utc)
{
expected = expected.Value.ToUniversalTime();
}
if (result1.Kind != DateTimeKind.Utc)
{
result1 = result1.ToUniversalTime();
}
Assert.Equal(expected, result1);
}
}
[Theory]
[MemberData(nameof(ParseExact_InvalidInputs_Fail_MemberData))]
public static void ParseExact_Span_InvalidInputs_Fail(string input, string format, CultureInfo culture, DateTimeStyles style)
{
Assert.Throws<FormatException>(() => DateTime.ParseExact(input.AsSpan(), format, culture, style));
Assert.Throws<FormatException>(() => DateTime.ParseExact(input.AsSpan(), new[] { format }, culture, style));
Assert.False(DateTime.TryParseExact(input.AsSpan(), format, culture, style, out DateTime result));
Assert.False(DateTime.TryParseExact(input.AsSpan(), new[] { format }, culture, style, out result));
}
[Theory]
[MemberData(nameof(ToString_MatchesExpected_MemberData))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/60562", TestPlatforms.Android)]
public void ToString_Invoke_ReturnsExpected(DateTime dateTime, string format, IFormatProvider provider, string expected)
{
if (provider == null)
{
Assert.Equal(expected, dateTime.ToString(format));
}
Assert.Equal(expected, dateTime.ToString(format, provider));
}
[Fact]
public void ToLongDateString_Invoke_ReturnsExpected()
{
DateTime date = DateTime.Now;
Assert.Equal(date.ToString("D"), date.ToLongDateString());
}
[Fact]
public void ToLongTimeString_Invoke_ReturnsExpected()
{
DateTime date = DateTime.Now;
Assert.Equal(date.ToString("T"), date.ToLongTimeString());
}
[Fact]
public void ToShortDateString_Invoke_ReturnsExpected()
{
DateTime date = DateTime.Now;
Assert.Equal(date.ToString("d"), date.ToShortDateString());
}
[Fact]
public void ToShortTimeString_Invoke_ReturnsExpected()
{
DateTime date = DateTime.Now;
Assert.Equal(date.ToString("t"), date.ToShortTimeString());
}
[Fact]
public void GetTypeCode_Invoke_ReturnsExpected()
{
Assert.Equal(TypeCode.DateTime, DateTime.Now.GetTypeCode());
}
[Fact]
public void ToBoolean_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToBoolean(null));
}
[Fact]
public void ToChar_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToChar(null));
}
[Fact]
public void ToSByte_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToSByte(null));
}
[Fact]
public void ToByte_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToByte(null));
}
[Fact]
public void ToInt16_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToInt16(null));
}
[Fact]
public void ToUInt16_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToUInt16(null));
}
[Fact]
public void ToInt32_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToInt32(null));
}
[Fact]
public void ToUInt32_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToUInt32(null));
}
[Fact]
public void ToInt64_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToInt64(null));
}
[Fact]
public void ToUInt64_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToUInt64(null));
}
[Fact]
public void ToSingle_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToSingle(null));
}
[Fact]
public void ToDouble_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToDouble(null));
}
[Fact]
public void ToDecimal_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToDecimal(null));
}
[Fact]
public void ToDateTime_Invoke_ReturnsExpected()
{
DateTime date = DateTime.Now;
Assert.Equal(date, ((IConvertible)date).ToDateTime(null));
}
[Fact]
public void ToType_DateTime_ReturnsExpected()
{
DateTime date = DateTime.Now;
Assert.Equal(date, ((IConvertible)date).ToType(typeof(DateTime), null));
}
[Fact]
public void GetObjectData_Invoke_ReturnsExpected()
{
ISerializable serializable = new DateTime(10, DateTimeKind.Utc);
SerializationInfo info = new SerializationInfo(typeof(DateTime), new FormatterConverter());
serializable.GetObjectData(info, new StreamingContext());
Assert.Equal(10, info.GetInt64("ticks"));
Assert.Equal(4611686018427387914, info.GetInt64("dateData"));
}
[Fact]
public void GetObjectData_NullInfo_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("info", () => ((ISerializable)DateTime.Now).GetObjectData(null, new StreamingContext()));
}
[Fact]
public void TestRoundTrippingDateTimeAndFileTime()
{
// This test ensure the round tripping of DateTime with the system file time.
// It is important to have this working on systems supporting leap seconds as the conversion wouldn't be simple
// conversion but involve some OS calls to ensure the right conversion is happening.
DateTime now = DateTime.UtcNow;
long fileTime = now.ToFileTimeUtc();
DateTime roundTrippedDateTime = DateTime.FromFileTimeUtc(fileTime);
Assert.Equal(now, roundTrippedDateTime);
now = DateTime.Now;
fileTime = now.ToFileTime();
roundTrippedDateTime = DateTime.FromFileTime(fileTime);
Assert.Equal(now, roundTrippedDateTime);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void TestTimeSynchronizationWithTheSystem()
{
// The reported time by the framework should be synchronized with the OS.
// There shouldn't be any shift by more than one second, otherwise there is something wrong.
// This test is useful when running on a system supporting leap seconds to ensure when the system
// has leap seconds, the framework reported time will still be synchronized.
SYSTEMTIME st;
SYSTEMTIME st1;
GetSystemTime(out st);
DateTime dt = DateTime.UtcNow;
GetSystemTime(out st1);
DateTime systemDateTimeNow1 = new DateTime(st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMillisecond, DateTimeKind.Utc);
DateTime systemDateTimeNow2 = new DateTime(st1.wYear, st1.wMonth, st1.wDay, st1.wHour, st1.wMinute, st1.wSecond, st1.wMillisecond, DateTimeKind.Utc);
// Usually GetSystemTime and DateTime.UtcNow calls doesn't take one second to execute, if this is not the case then
// the thread was sleeping for awhile and we cannot test reliably on that case.
TimeSpan diff = systemDateTimeNow2 - systemDateTimeNow1;
if (diff < TimeSpan.FromSeconds(1))
{
diff = dt - systemDateTimeNow1;
Assert.True(diff < TimeSpan.FromSeconds(1), $"Reported DateTime.UtcNow {dt} is shifted by more than one second then the system time {systemDateTimeNow1}");
}
}
[DllImport("Kernel32.dll")]
internal static extern void GetSystemTime(out SYSTEMTIME lpSystemTime);
[StructLayout(LayoutKind.Sequential)]
internal struct SYSTEMTIME
{
internal ushort wYear;
internal ushort wMonth;
internal ushort wDayOfWeek;
internal ushort wDay;
internal ushort wHour;
internal ushort wMinute;
internal ushort wSecond;
internal ushort wMillisecond;
}
[Theory]
[MemberData(nameof(StandardFormatSpecifiers))]
public static void TryFormat_MatchesToString(string format)
{
DateTime dt = DateTime.UtcNow;
string expected = dt.ToString(format);
// Just the right length, succeeds
Span<char> dest = new char[expected.Length];
Assert.True(dt.TryFormat(dest, out int charsWritten, format));
Assert.Equal(expected.Length, charsWritten);
Assert.Equal<char>(expected.ToCharArray(), dest.ToArray());
// Too short, fails
dest = new char[expected.Length - 1];
Assert.False(dt.TryFormat(dest, out charsWritten, format));
Assert.Equal(0, charsWritten);
// Longer than needed, succeeds
dest = new char[expected.Length + 1];
Assert.True(dt.TryFormat(dest, out charsWritten, format));
Assert.Equal(expected.Length, charsWritten);
Assert.Equal<char>(expected.ToCharArray(), dest.Slice(0, expected.Length).ToArray());
Assert.Equal(0, dest[dest.Length - 1]);
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotInvariantGlobalization))]
[MemberData(nameof(ToString_MatchesExpected_MemberData))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/60562", TestPlatforms.Android)]
public static void TryFormat_MatchesExpected(DateTime dateTime, string format, IFormatProvider provider, string expected)
{
var destination = new char[expected.Length];
Assert.False(dateTime.TryFormat(destination.AsSpan(0, destination.Length - 1), out _, format, provider));
Assert.True(dateTime.TryFormat(destination, out int charsWritten, format, provider));
Assert.Equal(destination.Length, charsWritten);
Assert.Equal(expected, new string(destination));
}
[Fact]
public static void UnixEpoch()
{
VerifyDateTime(DateTime.UnixEpoch, 1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Tests
{
public class DateTimeTests
{
[Fact]
public static void MaxValue()
{
VerifyDateTime(DateTime.MaxValue, 9999, 12, 31, 23, 59, 59, 999, DateTimeKind.Unspecified);
}
[Fact]
public static void MinValue()
{
VerifyDateTime(DateTime.MinValue, 1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified);
}
[Fact]
public static void Ctor_Long()
{
VerifyDateTime(new DateTime(999999999999999999), 3169, 11, 16, 9, 46, 39, 999, DateTimeKind.Unspecified);
}
[Fact]
public static void Ctor_Long_DateTimeKind()
{
VerifyDateTime(new DateTime(999999999999999999, DateTimeKind.Utc), 3169, 11, 16, 9, 46, 39, 999, DateTimeKind.Utc);
}
public static IEnumerable<object[]> Ctor_InvalidTicks_TestData()
{
yield return new object[] { DateTime.MinValue.Ticks - 1 };
yield return new object[] { DateTime.MaxValue.Ticks + 1 };
}
[Theory]
[MemberData(nameof(Ctor_InvalidTicks_TestData))]
public void Ctor_InvalidTicks_ThrowsArgumentOutOfRangeException(long ticks)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("ticks", () => new DateTime(ticks));
AssertExtensions.Throws<ArgumentOutOfRangeException>("ticks", () => new DateTime(ticks, DateTimeKind.Utc));
}
[Fact]
public void Ctor_Int_Int_Int()
{
var dateTime = new DateTime(2012, 6, 11);
VerifyDateTime(dateTime, 2012, 6, 11, 0, 0, 0, 0, DateTimeKind.Unspecified);
}
[Fact]
public void Ctor_Int_Int_Int_Calendar()
{
var dateTime = new DateTime(2012, 6, 11, new GregorianCalendar());
VerifyDateTime(dateTime, 2012, 6, 11, 0, 0, 0, 0, DateTimeKind.Unspecified);
}
[Fact]
public void Ctor_Int_Int_Int_Int_Int_Int()
{
var dateTime = new DateTime(2012, 12, 31, 13, 50, 10);
VerifyDateTime(dateTime, 2012, 12, 31, 13, 50, 10, 0, DateTimeKind.Unspecified);
}
[Fact]
public void Ctor_Int_Int_Int_Int_Int_Int_DateTimeKind()
{
var dateTime = new DateTime(1986, 8, 15, 10, 20, 5, DateTimeKind.Local);
VerifyDateTime(dateTime, 1986, 8, 15, 10, 20, 5, 0, DateTimeKind.Local);
}
[Fact]
public void Ctor_Int_Int_Int_Int_Int_Int_Calendar()
{
var dateTime = new DateTime(2012, 12, 31, 13, 50, 10, new GregorianCalendar());
VerifyDateTime(dateTime, 2012, 12, 31, 13, 50, 10, 0, DateTimeKind.Unspecified);
}
public static IEnumerable<object[]> Ctor_Int_Int_Int_Int_Int_Int_Int_Int_TestData()
{
yield return new object[] { 1986, 8, 15, 10, 20, 5, 600 };
yield return new object[] { 1986, 2, 28, 10, 20, 5, 600 };
yield return new object[] { 1986, 12, 31, 10, 20, 5, 600 };
yield return new object[] { 2000, 2, 28, 10, 20, 5, 600 };
yield return new object[] { 2000, 2, 29, 10, 20, 5, 600 };
yield return new object[] { 2000, 12, 31, 10, 20, 5, 600 };
yield return new object[] { 1900, 2, 28, 10, 20, 5, 600 };
yield return new object[] { 1900, 12, 31, 10, 20, 5, 600 };
}
[Theory]
[MemberData(nameof(Ctor_Int_Int_Int_Int_Int_Int_Int_Int_TestData))]
public void Ctor_Int_Int_Int_Int_Int_Int_Int(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
var dateTime = new DateTime(year, month, day, hour, minute, second, millisecond);
VerifyDateTime(dateTime, year, month, day, hour, minute, second, millisecond, DateTimeKind.Unspecified);
}
[Theory]
[MemberData(nameof(Ctor_Int_Int_Int_Int_Int_Int_Int_Int_TestData))]
public void Ctor_Int_Int_Int_Int_Int_Int_Int_Calendar(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
var dateTime = new DateTime(year, month, day, hour, minute, second, millisecond, new GregorianCalendar());
VerifyDateTime(dateTime, year, month, day, hour, minute, second, millisecond, DateTimeKind.Unspecified);
}
[Theory]
[MemberData(nameof(Ctor_Int_Int_Int_Int_Int_Int_Int_Int_TestData))]
public void Ctor_Int_Int_Int_Int_Int_Int_Int_Int_DateTimeKind(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
var dateTime = new DateTime(year, month, day, hour, minute, second, millisecond, DateTimeKind.Local);
VerifyDateTime(dateTime, year, month, day, hour, minute, second, millisecond, DateTimeKind.Local);
}
[Theory]
[MemberData(nameof(Ctor_Int_Int_Int_Int_Int_Int_Int_Int_TestData))]
public void Ctor_Int_Int_Int_Int_Int_Int_Int_Int_Calendar_DateTimeKind(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
var dateTime = new DateTime(year, month, day, hour, minute, second, millisecond, new GregorianCalendar(), DateTimeKind.Local);
VerifyDateTime(dateTime, year, month, day, hour, minute, second, millisecond, DateTimeKind.Local);
}
[Theory]
[InlineData(0)]
[InlineData(10000)]
public void Ctor_InvalidYear_ThrowsArgumentOutOfRangeException(int year)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(year, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(year, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(year, 1, 1, 1, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(year, 1, 1, 1, 1, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(year, 1, 1, 1, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(year, 1, 1, 1, 1, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(year, 1, 1, 1, 1, 1, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(year, 1, 1, 1, 1, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(year, 1, 1, 1, 1, 1, 1, new GregorianCalendar(), DateTimeKind.Utc));
}
[Theory]
[InlineData(0)]
[InlineData(13)]
public void Ctor_InvalidMonth_ThrowsArgumentOutOfRangeException(int month)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, month, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, month, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, month, 1, 1, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, month, 1, 1, 1, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, month, 1, 1, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, month, 1, 1, 1, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, month, 1, 1, 1, 1, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, month, 1, 1, 1, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, month, 1, 1, 1, 1, 1, new GregorianCalendar(), DateTimeKind.Utc));
}
[Theory]
[InlineData(0)]
[InlineData(32)]
public void Ctor_InvalidDay_ThrowsArgumentOutOfRangeException(int day)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, day));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, day, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, day, 1, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, day, 1, 1, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, day, 1, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, day, 1, 1, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, day, 1, 1, 1, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, day, 1, 1, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, day, 1, 1, 1, 1, new GregorianCalendar(), DateTimeKind.Utc));
}
[Theory]
[InlineData(-1)]
[InlineData(24)]
public void Ctor_InvalidHour_ThrowsArgumentOutOfRangeException(int hour)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, hour, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, hour, 1, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, hour, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, hour, 1, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, hour, 1, 1, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, hour, 1, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, hour, 1, 1, 1, new GregorianCalendar(), DateTimeKind.Utc));
}
[Theory]
[InlineData(-1)]
[InlineData(60)]
public void Ctor_InvalidMinute_ThrowsArgumentOutOfRangeException(int minute)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, minute, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, minute, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, minute, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, minute, 1, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, minute, 1, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, minute, 1, 1, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, minute, 1, 1, new GregorianCalendar(), DateTimeKind.Utc));
}
[Theory]
[InlineData(-1)]
[InlineData(60)]
public void Ctor_InvalidSecond_ThrowsArgumentOutOfRangeException(int second)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, second));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, second, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, second, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, second, 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, second, 1, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, second, 1, new GregorianCalendar(), DateTimeKind.Utc));
}
[Theory]
[InlineData(-1)]
[InlineData(1000)]
public void Ctor_InvalidMillisecond_ThrowsArgumentOutOfRangeException(int millisecond)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTime(1, 1, 1, 1, 1, 1, millisecond));
AssertExtensions.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTime(1, 1, 1, 1, 1, 1, millisecond, DateTimeKind.Utc));
AssertExtensions.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTime(1, 1, 1, 1, 1, 1, millisecond, new GregorianCalendar()));
AssertExtensions.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTime(1, 1, 1, 1, 1, 1, millisecond, new GregorianCalendar(), DateTimeKind.Utc));
}
[Theory]
[InlineData(DateTimeKind.Unspecified - 1)]
[InlineData(DateTimeKind.Local + 1)]
public void Ctor_InvalidDateTimeKind_ThrowsArgumentException(DateTimeKind kind)
{
AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(0, kind));
AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(1, 1, 1, 1, 1, 1, kind));
AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(1, 1, 1, 1, 1, 1, 1, kind));
AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(1, 1, 1, 1, 1, 1, 1, new GregorianCalendar(), kind));
}
[Fact]
public void Ctor_NullCalendar_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("calendar", () => new DateTime(1, 1, 1, null));
AssertExtensions.Throws<ArgumentNullException>("calendar", () => new DateTime(1, 1, 1, 1, 1, 1, null));
AssertExtensions.Throws<ArgumentNullException>("calendar", () => new DateTime(1, 1, 1, 1, 1, 1, 1, null));
AssertExtensions.Throws<ArgumentNullException>("calendar", () => new DateTime(1, 1, 1, 1, 1, 1, 1, null, DateTimeKind.Local));
}
[Theory]
[InlineData(2004, 1, 31)]
[InlineData(2004, 2, 29)]
[InlineData(2004, 3, 31)]
[InlineData(2004, 4, 30)]
[InlineData(2004, 5, 31)]
[InlineData(2004, 6, 30)]
[InlineData(2004, 7, 31)]
[InlineData(2004, 8, 31)]
[InlineData(2004, 9, 30)]
[InlineData(2004, 10, 31)]
[InlineData(2004, 11, 30)]
[InlineData(2004, 12, 31)]
[InlineData(2005, 1, 31)]
[InlineData(2005, 2, 28)]
[InlineData(2005, 3, 31)]
[InlineData(2005, 4, 30)]
[InlineData(2005, 5, 31)]
[InlineData(2005, 6, 30)]
[InlineData(2005, 7, 31)]
[InlineData(2005, 8, 31)]
[InlineData(2005, 9, 30)]
[InlineData(2005, 10, 31)]
[InlineData(2005, 11, 30)]
[InlineData(2005, 12, 31)]
public void DaysInMonth_Invoke_ReturnsExpected(int year, int month, int expected)
{
Assert.Equal(expected, DateTime.DaysInMonth(year, month));
}
[Theory]
[InlineData(0)]
[InlineData(13)]
public void DaysInMonth_InvalidMonth_ThrowsArgumentOutOfRangeException(int month)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("month", () => DateTime.DaysInMonth(1, month));
}
[Theory]
[InlineData(0)]
[InlineData(10000)]
public void DaysInMonth_InvalidYear_ThrowsArgumentOutOfRangeException(int year)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("year", () => DateTime.DaysInMonth(year, 1));
}
[Theory]
[InlineData(2004, true)]
[InlineData(2000, true)]
[InlineData(1900, false)]
[InlineData(2005, false)]
public void IsLeapYear_Invoke_ReturnsExpected(int year, bool expected)
{
Assert.Equal(expected, DateTime.IsLeapYear(year));
}
[Theory]
[InlineData(0)]
[InlineData(10000)]
public void IsLeapYear_InvalidYear_ThrowsArgumentOutOfRangeException(int year)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("year", () => DateTime.IsLeapYear(year));
}
public static IEnumerable<object[]> IsDaylightSavingTime_TestData()
{
yield return new object[] { new DateTime(2018, 11, 24, 0, 0, 0, DateTimeKind.Utc), false };
yield return new object[] { DateTime.MinValue, false };
yield return new object[] { DateTime.MaxValue, false };
}
[Theory]
[MemberData(nameof(IsDaylightSavingTime_TestData))]
public void IsDaylightSavingTime_Invoke_ReturnsExpected(DateTime date, bool expected)
{
Assert.Equal(expected, date.IsDaylightSavingTime());
}
public static IEnumerable<object[]> Add_TimeSpan_TestData()
{
yield return new object[] { new DateTime(1000), new TimeSpan(10), new DateTime(1010) };
yield return new object[] { new DateTime(1000), TimeSpan.Zero, new DateTime(1000) };
yield return new object[] { new DateTime(1000), new TimeSpan(-10), new DateTime(990) };
}
[Theory]
[MemberData(nameof(Add_TimeSpan_TestData))]
public void Add_TimeSpan_ReturnsExpected(DateTime dateTime, TimeSpan timeSpan, DateTime expected)
{
Assert.Equal(expected, dateTime.Add(timeSpan));
Assert.Equal(expected, dateTime + timeSpan);
}
public static IEnumerable<object[]> Add_TimeSpanOutOfRange_TestData()
{
yield return new object[] { DateTime.Now, TimeSpan.MaxValue };
yield return new object[] { DateTime.Now, TimeSpan.MinValue };
yield return new object[] { DateTime.MaxValue, new TimeSpan(1) };
yield return new object[] { DateTime.MinValue, new TimeSpan(-1) };
}
[Theory]
[MemberData(nameof(Add_TimeSpanOutOfRange_TestData))]
public void Add_TimeSpan_NewDateOutOfRange_ThrowsArgumentOutOfRangeException(DateTime date, TimeSpan value)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => date.Add(value));
AssertExtensions.Throws<ArgumentOutOfRangeException>("t", () => date + value);
}
public static IEnumerable<object[]> AddYears_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 10, new DateTime(1996, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -10, new DateTime(1976, 8, 15, 10, 20, 5, 70) };
}
[Theory]
[MemberData(nameof(AddYears_TestData))]
public void AddYears_Invoke_ReturnsExpected(DateTime dateTime, int years, DateTime expected)
{
Assert.Equal(expected, dateTime.AddYears(years));
}
public static IEnumerable<object[]> AddYears_OutOfRange_TestData()
{
yield return new object[] { DateTime.Now, 10001 };
yield return new object[] { DateTime.Now, -10001 };
yield return new object[] { DateTime.MaxValue, 1 };
yield return new object[] { DateTime.MinValue, -1 };
}
[Theory]
[MemberData(nameof(AddYears_OutOfRange_TestData))]
public static void AddYears_NewDateOutOfRange_ThrowsArgumentOutOfRangeException(DateTime date, int years)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => date.AddYears(years));
}
public static IEnumerable<object[]> AddMonths_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 2, new DateTime(1986, 10, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 31, 10, 20, 5, 70), 1, new DateTime(1986, 9, 30, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 9, 30, 10, 20, 5, 70), 1, new DateTime(1986, 10, 30, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -2, new DateTime(1986, 6, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1900, 2, 28, 10, 20, 5, 70), 1, new DateTime(1900, 3, 28, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1900, 1, 31, 10, 20, 5, 70), 1, new DateTime(1900, 2, 28, 10, 20, 5, 70) };
yield return new object[] { new DateTime(2000, 1, 31, 10, 20, 5, 70), 1, new DateTime(2000, 2, 29, 10, 20, 5, 70) };
yield return new object[] { new DateTime(2000, 2, 29, 10, 20, 5, 70), 1, new DateTime(2000, 3, 29, 10, 20, 5, 70) };
yield return new object[] { new DateTime(2004, 1, 31, 10, 20, 5, 70), 1, new DateTime(2004, 2, 29, 10, 20, 5, 70) };
yield return new object[] { new DateTime(2004, 2, 29, 10, 20, 5, 70), 1, new DateTime(2004, 3, 29, 10, 20, 5, 70) };
yield return new object[] { new DateTime(2000, 12, 31), 1, new DateTime(2001, 1, 31) };
}
[Theory]
[MemberData(nameof(AddMonths_TestData))]
public void AddMonths_Invoke_ReturnsExpected(DateTime dateTime, int months, DateTime expected)
{
Assert.Equal(expected, dateTime.AddMonths(months));
}
public static IEnumerable<object[]> AddMonths_OutOfRange_TestData()
{
yield return new object[] { DateTime.Now, 120001 };
yield return new object[] { DateTime.Now, -120001 };
yield return new object[] { DateTime.MaxValue, 1 };
yield return new object[] { DateTime.MinValue, -1 };
}
[Theory]
[MemberData(nameof(AddMonths_OutOfRange_TestData))]
public void AddMonths_NewDateOutOfRange_ThrowsArgumentOutOfRangeException(DateTime date, int months)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => date.AddMonths(months));
}
public static IEnumerable<object[]> AddDays_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 2, new DateTime(1986, 8, 17, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 2, new DateTime(1986, 8, 17, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -2, new DateTime(1986, 8, 13, 10, 20, 5, 70) };
}
[Theory]
[MemberData(nameof(AddDays_TestData))]
public void AddDays_Invoke_ReturnsExpected(DateTime dateTime, double days, DateTime expected)
{
Assert.Equal(expected, dateTime.AddDays(days));
}
public static IEnumerable<object[]> AddDays_OutOfRange_TestData()
{
yield return new object[] { DateTime.MaxValue, 1 };
yield return new object[] { DateTime.MinValue, -1 };
yield return new object[] { DateTime.Now, double.MaxValue };
yield return new object[] { DateTime.Now, double.MinValue };
}
[Theory]
[MemberData(nameof(AddDays_OutOfRange_TestData))]
public void AddDays_NewDateOutOfRange_ThrowsArgumentOutOfRangeException(DateTime date, double days)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => date.AddDays(days));
}
public static IEnumerable<object[]> AddHours_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 3, new DateTime(1986, 8, 15, 13, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -3, new DateTime(1986, 8, 15, 7, 20, 5, 70) };
}
[Theory]
[MemberData(nameof(AddHours_TestData))]
public void AddHours_Invoke_RetunsExpected(DateTime dateTime, double hours, DateTime expected)
{
Assert.Equal(expected, dateTime.AddHours(hours));
}
public static IEnumerable<object[]> AddHours_OutOfRange_TestData()
{
yield return new object[] { DateTime.MaxValue, 1 };
yield return new object[] { DateTime.MinValue, -1 };
yield return new object[] { DateTime.Now, double.MaxValue };
yield return new object[] { DateTime.Now, double.MinValue };
}
[Theory]
[MemberData(nameof(AddHours_OutOfRange_TestData))]
public void AddHours_NewDateOutOfRange_ThrowsArgumentOutOfRangeException(DateTime date, double hours)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => date.AddHours(hours));
}
public static IEnumerable<object[]> AddMinutes_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 5, new DateTime(1986, 8, 15, 10, 25, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -5, new DateTime(1986, 8, 15, 10, 15, 5, 70) };
}
[Theory]
[MemberData(nameof(AddMinutes_TestData))]
public void AddMinutes_Invoke_ReturnsExpected(DateTime dateTime, double minutes, DateTime expected)
{
Assert.Equal(expected, dateTime.AddMinutes(minutes));
}
public static IEnumerable<object[]> AddMinutes_OutOfRange_TestData()
{
yield return new object[] { DateTime.MaxValue, 1 };
yield return new object[] { DateTime.MinValue, -1 };
yield return new object[] { DateTime.Now, double.MaxValue };
yield return new object[] { DateTime.Now, double.MinValue };
}
[Theory]
[MemberData(nameof(AddMinutes_OutOfRange_TestData))]
public void AddMinutes_NewDateOutOfRange_ThrowsArgumentOutOfRangeException(DateTime date, double minutes)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => date.AddMinutes(minutes));
}
public static IEnumerable<object[]> AddSeconds_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 30, new DateTime(1986, 8, 15, 10, 20, 35, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -3, new DateTime(1986, 8, 15, 10, 20, 2, 70) };
}
[Theory]
[MemberData(nameof(AddSeconds_TestData))]
public void AddSeconds_Invoke_ReturnsExpected(DateTime dateTime, double seconds, DateTime expected)
{
Assert.Equal(expected, dateTime.AddSeconds(seconds));
}
public static IEnumerable<object[]> AddSeconds_OutOfRange_TestData()
{
yield return new object[] { DateTime.MaxValue, 1 };
yield return new object[] { DateTime.MinValue, -1 };
yield return new object[] { DateTime.Now, double.MaxValue };
yield return new object[] { DateTime.Now, double.MinValue };
}
[Theory]
[MemberData(nameof(AddSeconds_OutOfRange_TestData))]
public void AddSeconds_NewDateOutOfRange_ThrowsArgumentOutOfRangeException(DateTime date, double seconds)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => date.AddSeconds(seconds));
}
public static IEnumerable<object[]> AddMilliseconds_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 10, new DateTime(1986, 8, 15, 10, 20, 5, 80) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -10, new DateTime(1986, 8, 15, 10, 20, 5, 60) };
}
[Theory]
[MemberData(nameof(AddMilliseconds_TestData))]
public void AddMilliseconds_Invoke_ReturnsExpected(DateTime dateTime, double milliseconds, DateTime expected)
{
Assert.Equal(expected, dateTime.AddMilliseconds(milliseconds));
}
public static IEnumerable<object[]> AddMillseconds_OutOfRange_TestData()
{
yield return new object[] { DateTime.MaxValue, 1 };
yield return new object[] { DateTime.MinValue, -1 };
yield return new object[] { DateTime.Now, double.MaxValue };
yield return new object[] { DateTime.Now, double.MinValue };
}
[Theory]
[MemberData(nameof(AddMillseconds_OutOfRange_TestData))]
public void AddMilliseconds_NewDateOutOfRange_ThrowsArgumentOutOfRangeException(DateTime date, double milliseconds)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => date.AddMilliseconds(milliseconds));
}
public static IEnumerable<object[]> AddTicks_TestData()
{
yield return new object[] { new DateTime(1000), 10, new DateTime(1010) };
yield return new object[] { new DateTime(1000), 0, new DateTime(1000) };
yield return new object[] { new DateTime(1000), -10, new DateTime(990) };
}
[Theory]
[MemberData(nameof(AddTicks_TestData))]
public void AddTicks_Invoke_ReturnsExpected(DateTime dateTime, long ticks, DateTime expected)
{
Assert.Equal(expected, dateTime.AddTicks(ticks));
}
public static IEnumerable<object[]> AddTicks_OutOfRange_TestData()
{
yield return new object[] { DateTime.MaxValue, 1 };
yield return new object[] { DateTime.MinValue, -1 };
yield return new object[] { DateTime.Now, long.MaxValue };
yield return new object[] { DateTime.Now, long.MinValue };
}
[Theory]
[MemberData(nameof(AddTicks_OutOfRange_TestData))]
public void AddTicks_NewDateOutOfRange_ThrowsArgumentOutOfRangeException(DateTime date, long ticks)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => date.AddTicks(ticks));
}
public static IEnumerable<object[]> CompareTo_TestData()
{
yield return new object[] { new DateTime(10), new DateTime(10), 0 };
yield return new object[] { new DateTime(10), new DateTime(11), -1 };
yield return new object[] { new DateTime(10), new DateTime(9), 1 };
yield return new object[] { new DateTime(10), null, 1 };
}
[Theory]
[MemberData(nameof(CompareTo_TestData))]
public void CompareTo_Invoke_ReturnsExpected(DateTime date, object other, int expected)
{
if (other is DateTime otherDate)
{
Assert.Equal(expected, date.CompareTo(otherDate));
Assert.Equal(expected, DateTime.Compare(date, otherDate));
Assert.Equal(expected > 0, date > otherDate);
Assert.Equal(expected >= 0, date >= otherDate);
Assert.Equal(expected < 0, date < otherDate);
Assert.Equal(expected <= 0, date <= otherDate);
}
Assert.Equal(expected, date.CompareTo(other));
}
[Fact]
public void CompareTo_NotDateTime_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>(null, () => DateTime.Now.CompareTo(new object()));
}
public static IEnumerable<object[]> Equals_TestData()
{
yield return new object[] { new DateTime(10), new DateTime(10), true };
yield return new object[] { new DateTime(10), new DateTime(11), false };
yield return new object[] { new DateTime(10), new DateTime(9), false };
yield return new object[] { new DateTime(10), new object(), false };
yield return new object[] { new DateTime(10), null, false };
}
[Theory]
[MemberData(nameof(Equals_TestData))]
public void Equals_Invoke_ReturnsExpected(DateTime date, object other, bool expected)
{
if (other is DateTime otherDate)
{
Assert.Equal(expected, date.Equals(otherDate));
Assert.Equal(expected, DateTime.Equals(date, otherDate));
Assert.Equal(expected, date.GetHashCode().Equals(otherDate.GetHashCode()));
Assert.Equal(expected, date == otherDate);
Assert.Equal(!expected, date != otherDate);
}
Assert.Equal(expected, date.Equals(other));
}
[Fact]
public void DayOfWeek_Get_ReturnsExpected()
{
var dateTime = new DateTime(2012, 6, 18);
Assert.Equal(DayOfWeek.Monday, dateTime.DayOfWeek);
}
[Fact]
public void DayOfYear_Get_ReturnsExpected()
{
var dateTime = new DateTime(2012, 6, 18);
Assert.Equal(170, dateTime.DayOfYear);
}
[Fact]
public void TimeOfDay_Get_ReturnsExpected()
{
var dateTime = new DateTime(2012, 6, 18, 10, 5, 1, 0);
TimeSpan ts = dateTime.TimeOfDay;
DateTime newDate = dateTime.Subtract(ts);
Assert.Equal(new DateTime(2012, 6, 18, 0, 0, 0, 0).Ticks, newDate.Ticks);
Assert.Equal(dateTime.Ticks, newDate.Add(ts).Ticks);
}
[Fact]
public void Today_Get_ReturnsExpected()
{
DateTime today = DateTime.Today;
DateTime now = DateTime.Now;
VerifyDateTime(today, now.Year, now.Month, now.Day, 0, 0, 0, 0, DateTimeKind.Local);
today = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, DateTimeKind.Utc);
Assert.Equal(DateTimeKind.Utc, today.Kind);
Assert.False(today.IsDaylightSavingTime());
}
public static IEnumerable<object[]> Subtract_TimeSpan_TestData()
{
var dateTime = new DateTime(2012, 6, 18, 10, 5, 1, 0, DateTimeKind.Utc);
yield return new object[] { dateTime, new TimeSpan(10, 5, 1), new DateTime(2012, 6, 18, 0, 0, 0, 0, DateTimeKind.Utc) };
yield return new object[] { dateTime, new TimeSpan(-10, -5, -1), new DateTime(2012, 6, 18, 20, 10, 2, 0, DateTimeKind.Utc) };
}
[Theory]
[MemberData(nameof(Subtract_TimeSpan_TestData))]
public void Subtract_TimeSpan_ReturnsExpected(DateTime dateTime, TimeSpan timeSpan, DateTime expected)
{
Assert.Equal(expected, dateTime.Subtract(timeSpan));
Assert.Equal(expected, dateTime - timeSpan);
}
public static IEnumerable<object[]> Subtract_OutOfRangeTimeSpan_TestData()
{
yield return new object[] { DateTime.Now, TimeSpan.MinValue };
yield return new object[] { DateTime.Now, TimeSpan.MaxValue };
yield return new object[] { DateTime.MaxValue, new TimeSpan(-1) };
yield return new object[] { DateTime.MinValue, new TimeSpan(1) };
}
[Theory]
[MemberData(nameof(Subtract_OutOfRangeTimeSpan_TestData))]
public static void Subtract_OutOfRangeTimeSpan_ThrowsArgumentOutOfRangeException(DateTime date, TimeSpan value)
{
Assert.Throws<ArgumentOutOfRangeException>(() => date.Subtract(value));
Assert.Throws<ArgumentOutOfRangeException>(() => date - value);
}
public static IEnumerable<object[]> Subtract_DateTime_TestData()
{
var dateTime1 = new DateTime(1996, 6, 3, 22, 15, 0, DateTimeKind.Utc);
var dateTime2 = new DateTime(1996, 12, 6, 13, 2, 0, DateTimeKind.Utc);
var dateTime3 = new DateTime(1996, 10, 12, 8, 42, 0, DateTimeKind.Utc);
yield return new object[] { dateTime2, dateTime1, new TimeSpan(185, 14, 47, 0) };
yield return new object[] { dateTime1, dateTime2, new TimeSpan(-185, -14, -47, 0) };
yield return new object[] { dateTime1, dateTime2, new TimeSpan(-185, -14, -47, 0) };
}
[Theory]
[MemberData(nameof(Subtract_DateTime_TestData))]
public void Subtract_DateTime_ReturnsExpected(DateTime dateTime1, DateTime dateTime2, TimeSpan expected)
{
Assert.Equal(expected, dateTime1.Subtract(dateTime2));
Assert.Equal(expected, dateTime1 - dateTime2);
}
public static IEnumerable<object[]> ToOADate_TestData()
{
yield return new object[] { new DateTime(1), 0 };
yield return new object[] { new DateTime((long)10000 * 1000 * 60 * 60 * 24 - 1), 1 };
yield return new object[] { new DateTime(100, 1, 1), -657434 };
yield return new object[] { new DateTime(1889, 11, 24, 23, 59, 59, 999).AddTicks(1), -3687 };
yield return new object[] { new DateTime(1889, 11, 24, 17, 57, 30, 12), -3688.74826402778 };
yield return new object[] { new DateTime(1889, 11, 24).AddTicks(1), -3688 };
yield return new object[] { new DateTime(1899, 12, 30), 0 };
yield return new object[] { new DateTime(2018, 11, 24), 43428 };
yield return new object[] { new DateTime(2018, 11, 24, 17, 57, 30, 12), 43428.74826 };
yield return new object[] { new DateTime(2018, 11, 24, 23, 59, 59, 999).AddTicks(1), 43429 };
yield return new object[] { DateTime.MinValue, 0 };
yield return new object[] { DateTime.MaxValue, 2958466 };
}
[Theory]
[MemberData(nameof(ToOADate_TestData))]
public void ToOADate_Invoke_ReturnsExpected(DateTime date, double expected)
{
Assert.Equal(expected, date.ToOADate(), 5);
}
public static IEnumerable<object[]> ToOADate_Overflow_TestData()
{
yield return new object[] { new DateTime((long)10000 * 1000 * 60 * 60 * 24) };
yield return new object[] { new DateTime(100, 1, 1).AddTicks(-1) };
}
[Theory]
[MemberData(nameof(ToOADate_Overflow_TestData))]
public void ToOADate_SmallDate_ThrowsOverflowException(DateTime date)
{
Assert.Throws<OverflowException>(() => date.ToOADate());
}
public static IEnumerable<object[]> FromOADate_TestData()
{
yield return new object[] { -1.5, new DateTime(1899, 12, 29, 12, 0, 0) };
yield return new object[] { -1, new DateTime(1899, 12, 29) };
yield return new object[] { 0, new DateTime(1899, 12, 30) };
yield return new object[] { 1, new DateTime(1899, 12, 31) };
yield return new object[] { 1.5, new DateTime(1899, 12, 31, 12, 0, 0) };
yield return new object[] { -657434.99999999, new DateTime(100, 1, 1, 23, 59, 59, 999) };
yield return new object[] { -657434.9999999999, new DateTime(99, 12, 31) };
yield return new object[] { 2958465.999999994, new DateTime(9999, 12, 31, 23, 59, 59, 999) };
}
[Theory]
[MemberData(nameof(FromOADate_TestData))]
public void FromOADate_Invoke_ReturnsExpected(double value, DateTime expected)
{
DateTime actual = DateTime.FromOADate(value);
Assert.Equal(expected, actual);
Assert.Equal(DateTimeKind.Unspecified, actual.Kind);
}
[Theory]
[InlineData(-657435)]
[InlineData(2958466)]
[InlineData(-657434.99999999995)]
[InlineData(2958465.999999995)]
[InlineData(double.NaN)]
public void FromOADate_InvalidValue_ThrowsArgumentException(double value)
{
AssertExtensions.Throws<ArgumentException>(null, () => DateTime.FromOADate(value));
}
public static IEnumerable<object[]> ToBinary_TestData()
{
const long Ticks = 123456789101112;
DateTime local = new DateTime(Ticks, DateTimeKind.Local);
TimeSpan offset = TimeZoneInfo.Local.GetUtcOffset(local);
long localTicks = local.Ticks - offset.Ticks;
if (localTicks < 0)
{
localTicks |= 0x4000000000000000;
}
yield return new object[] { new DateTime(Ticks, DateTimeKind.Utc), Ticks | ((long)DateTimeKind.Utc << 62) };
yield return new object[] { new DateTime(Ticks, DateTimeKind.Unspecified), Ticks | (( long)DateTimeKind.Unspecified << 62) };
yield return new object[] { local, localTicks | ((long)DateTimeKind.Local << 62) };
yield return new object[] { DateTime.MaxValue, 3155378975999999999 };
yield return new object[] { DateTime.MinValue, 0 };
}
[Theory]
[MemberData(nameof(ToBinary_TestData))]
public void ToBinary_Invoke_ReturnsExpected(DateTime date, long expected)
{
Assert.Equal(expected, date.ToBinary());
}
public static IEnumerable<object[]> FromBinary_TestData()
{
yield return new object[] { new DateTime(2018, 12, 24, 17, 34, 30, 12) };
yield return new object[] { new DateTime(2018, 12, 24, 17, 34, 30, 12, DateTimeKind.Local) };
yield return new object[] { DateTime.Today };
yield return new object[] { DateTime.MinValue };
yield return new object[] { DateTime.MaxValue };
}
[Theory]
[MemberData(nameof(FromBinary_TestData))]
public void FromBinary_Invoke_ReturnsExpected(DateTime date)
{
Assert.Equal(date, DateTime.FromBinary(date.ToBinary()));
}
[Theory]
[InlineData(3155378976000000000)]
[InlineData(long.MaxValue)]
[InlineData(3155378976000000000 | ((long)DateTimeKind.Utc << 62))]
public void FromBinary_OutOfRangeTicks_ThrowsArgumentException(long dateData)
{
AssertExtensions.Throws<ArgumentException>("dateData", () => DateTime.FromBinary(dateData));
}
public static IEnumerable<object[]> ToFileTime_TestData()
{
yield return new object[] { new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc) };
yield return new object[] { new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddTicks(1) };
yield return new object[] { new DateTime(2018, 12, 24, 0, 0, 0, DateTimeKind.Utc) };
yield return new object[] { new DateTime(2018, 11, 24, 17, 57, 30, 12, DateTimeKind.Utc) };
yield return new object[] { new DateTime(2018, 12, 24, 0, 0, 0, DateTimeKind.Local) };
yield return new object[] { new DateTime(2018, 11, 24, 17, 57, 30, 12, DateTimeKind.Local) };
}
[Theory]
[MemberData(nameof(ToFileTime_TestData))]
public void ToFileTime_Invoke_ReturnsExpected(DateTime date)
{
long fileTime = date.ToFileTime();
DateTime fromFileTime = date.Kind == DateTimeKind.Utc ? DateTime.FromFileTimeUtc(fileTime) : DateTime.FromFileTime(fileTime);
Assert.Equal(date, fromFileTime);
}
public static IEnumerable<object[]> ToFileTime_Overflow_TestData()
{
yield return new object[] { DateTime.MinValue };
yield return new object[] { new DateTime(1600, 12, 31) };
}
[Theory]
[MemberData(nameof(ToFileTime_Overflow_TestData))]
public void ToFileTime_SmallDate_ThrowsArgumentOutOfRangeException(DateTime date)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => date.ToFileTime());
}
public static IEnumerable<object[]> FromFileTime_TestData()
{
yield return new object[] { 0, new DateTime(1601, 1, 1) };
yield return new object[] { 2650467743999999999, DateTime.MaxValue };
yield return new object[] { 131875558500120000, new DateTime(2018, 11, 24, 17, 57, 30, 12) };
}
[Theory]
[MemberData(nameof(FromFileTime_TestData))]
public void FromFileTime_Invoke_ReturnsExpected(long fileTime, DateTime expected)
{
DateTime actual = DateTime.FromFileTime(fileTime);
Assert.Equal(expected.ToLocalTime(), actual);
Assert.Equal(DateTimeKind.Local, actual.Kind);
}
[Theory]
[InlineData(-1)]
[InlineData(2650467744000000000)]
public void FromFileTime_OutOfRange_ThrowsArgumentOutOfRangeException(long fileTime)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("fileTime", () => DateTime.FromFileTime(fileTime));
}
public static IEnumerable<object[]> ToFileTimeUtc_TestData()
{
DateTime local = new DateTime(2018, 12, 24, 0, 0, 0, DateTimeKind.Local);
DateTime localToUtc = TimeZoneInfo.ConvertTimeToUtc(local);
yield return new object[] { new DateTime(1601, 1, 1), 0 };
yield return new object[] { new DateTime(1601, 1, 1).AddTicks(1), 1 };
yield return new object[] { new DateTime(2018, 12, 24), 131900832000000000 };
yield return new object[] { local, localToUtc.ToFileTimeUtc() };
yield return new object[] { new DateTime(2018, 11, 24, 17, 57, 30, 12), 131875558500120000 };
yield return new object[] { DateTime.MaxValue, 2650467743999999999 };
}
[Theory]
[MemberData(nameof(ToFileTimeUtc_TestData))]
public void ToFileTimeUtc_Invoke_ReturnsExpected(DateTime date, long expected)
{
Assert.Equal(expected, date.ToFileTimeUtc());
}
public static IEnumerable<object[]> ToFileTimeUtc_Overflow_TestData()
{
yield return new object[] { DateTime.MinValue };
yield return new object[] { new DateTime(1600, 12, 31) };
}
[Theory]
[MemberData(nameof(ToFileTimeUtc_Overflow_TestData))]
public void ToFileTimeUtc_SmallDate_ThrowsArgumentOutOfRangeException(DateTime date)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => date.ToFileTimeUtc());
}
public static IEnumerable<object[]> FromFileTimeUtc_TestData()
{
yield return new object[] { 0, new DateTime(1601, 1, 1) };
yield return new object[] { 2650467743999999999, DateTime.MaxValue };
yield return new object[] { 131875558500120000, new DateTime(2018, 11, 24, 17, 57, 30, 12) };
}
[Theory]
[MemberData(nameof(FromFileTimeUtc_TestData))]
public void FromFileTimeUtc_Invoke_ReturnsExpected(long fileTime, DateTime expected)
{
DateTime actual = DateTime.FromFileTimeUtc(fileTime);
Assert.Equal(expected, actual);
Assert.Equal(DateTimeKind.Utc, actual.Kind);
}
[Theory]
[InlineData(-1)]
[InlineData(2650467744000000000)]
public void FromFileTimeUtc_OutOfRange_ThrowsArgumentOutOfRangeException(long fileTime)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("fileTime", () => DateTime.FromFileTimeUtc(fileTime));
}
[Fact]
public static void Parse_String()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString();
DateTime result = DateTime.Parse(expectedString);
Assert.Equal(expectedString, result.ToString());
}
[Fact]
public static void Parse_String_FormatProvider()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString();
DateTime result = DateTime.Parse(expectedString, null);
Assert.Equal(expectedString, result.ToString());
}
[Fact]
public static void Parse_String_FormatProvider_DateTimeStyles()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString();
DateTime result = DateTime.Parse(expectedString, null, DateTimeStyles.None);
Assert.Equal(expectedString, result.ToString());
}
[Fact]
public static void Parse_Japanese()
{
var expected = new DateTime(2012, 12, 21, 10, 8, 6);
var cultureInfo = new CultureInfo("ja-JP");
string expectedString = string.Format(cultureInfo, "{0}", expected);
Assert.Equal(expected, DateTime.Parse(expectedString, cultureInfo));
}
private static bool IsNotOSXOrBrowser => !PlatformDetection.IsOSXLike && !PlatformDetection.IsBrowser;
[ConditionalTheory(nameof(IsNotOSXOrBrowser))]
[InlineData("ar")]
[InlineData("ar-EG")]
[InlineData("ar-IQ")]
[InlineData("ar-SA")]
[InlineData("ar-YE")]
public static void DateTimeParsingWithBiDiCultureTest(string cultureName)
{
DateTime dt = new DateTime(2021, 11, 30, 14, 30, 40);
CultureInfo ci = CultureInfo.GetCultureInfo(cultureName);
string formatted = dt.ToString("d", ci);
Assert.Equal(dt.Date, DateTime.Parse(formatted, ci));
formatted = dt.ToString("g", ci);
DateTime parsed = DateTime.Parse(formatted, ci);
Assert.Equal(dt.Date, parsed.Date);
Assert.Equal(dt.Hour, parsed.Hour);
Assert.Equal(dt.Minute, parsed.Minute);
}
[Fact]
public static void DateTimeParsingWithSpaceTimeSeparators()
{
DateTime dt = new DateTime(2021, 11, 30, 14, 30, 40);
CultureInfo ci = CultureInfo.GetCultureInfo("en-US");
// It is possible we find some cultures use such formats. dz-BT is example of that
string formatted = dt.ToString("yyyy/MM/dd hh mm tt", ci);
DateTime parsed = DateTime.Parse(formatted, ci);
Assert.Equal(dt.Hour, parsed.Hour);
Assert.Equal(dt.Minute, parsed.Minute);
formatted = dt.ToString("yyyy/MM/dd hh mm ss tt", ci);
parsed = DateTime.Parse(formatted, ci);
Assert.Equal(dt, parsed);
}
[Fact]
public static void Parse_InvalidArguments_Throws()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.Parse(null));
AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.Parse(null, new MyFormatter()));
AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.Parse((string)null, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
Assert.Throws<FormatException>(() => DateTime.Parse(""));
Assert.Throws<FormatException>(() => DateTime.Parse("", new MyFormatter()));
Assert.Throws<FormatException>(() => DateTime.Parse("", new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
Assert.Throws<FormatException>(() => DateTime.Parse("2020-5-7T09:37:00.0000000-07:00c"));
Assert.Throws<FormatException>(() => DateTime.Parse("2020-5-7T09:37:00.0000000-07:00c", new MyFormatter()));
Assert.Throws<FormatException>(() => DateTime.Parse("2020-5-7T09:37:00.0000000-07:00c", new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
Assert.Throws<FormatException>(() => DateTime.Parse("2020-5-7T09:37:00.0000000+00:00#"));
Assert.Throws<FormatException>(() => DateTime.Parse("2020-5-7T09:37:00.0000000+00:00#", new MyFormatter()));
Assert.Throws<FormatException>(() => DateTime.Parse("2020-5-7T09:37:00.0000000+00:00#", new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
Assert.Throws<FormatException>(() => DateTime.Parse("2020-5-7T09:37:00.0000000+00:00#\0"));
Assert.Throws<FormatException>(() => DateTime.Parse("2020-5-7T09:37:00.0000000+00:00#\0", new MyFormatter()));
Assert.Throws<FormatException>(() => DateTime.Parse("2020-5-7T09:37:00.0000000+00:00#\0", new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
}
[Theory]
[InlineData(null)]
[InlineData("")]
public static void TryParse_NullOrEmptyString_ReturnsFalse(string input)
{
Assert.False(DateTime.TryParse(input, out DateTime result));
Assert.False(DateTime.TryParse(input, new MyFormatter(), DateTimeStyles.None, out result));
}
[Fact]
public static void ParseExact_InvalidArguments_Throws()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.ParseExact(null, "d", new MyFormatter()));
AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.ParseExact((string)null, "d", new MyFormatter(), DateTimeStyles.None));
AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.ParseExact((string)null, new[] { "d" }, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
Assert.Throws<FormatException>(() => DateTime.ParseExact("", "d", new MyFormatter()));
Assert.Throws<FormatException>(() => DateTime.ParseExact("", "d", new MyFormatter(), DateTimeStyles.None));
Assert.Throws<FormatException>(() => DateTime.ParseExact("", new[] { "d" }, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
AssertExtensions.Throws<ArgumentNullException>("format", () => DateTime.ParseExact("123", null, new MyFormatter()));
AssertExtensions.Throws<ArgumentNullException>("format", () => DateTime.ParseExact("123", (string)null, new MyFormatter(), DateTimeStyles.None));
AssertExtensions.Throws<ArgumentNullException>("formats", () => DateTime.ParseExact("123", (string[])null, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
Assert.Throws<FormatException>(() => DateTime.ParseExact("123", "", new MyFormatter()));
Assert.Throws<FormatException>(() => DateTime.ParseExact("123", "", new MyFormatter(), DateTimeStyles.None));
Assert.Throws<FormatException>(() => DateTime.ParseExact("123", new string[0], new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
Assert.Throws<FormatException>(() => DateTime.ParseExact("123", new string[] { null }, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
Assert.Throws<FormatException>(() => DateTime.ParseExact("123", new[] { "" }, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
}
[Fact]
public static void TryParseExact_InvalidArguments_ReturnsFalse()
{
Assert.False(DateTime.TryParseExact((string)null, "d", new MyFormatter(), DateTimeStyles.None, out DateTime result));
Assert.False(DateTime.TryParseExact((string)null, new[] { "d" }, new MyFormatter(), DateTimeStyles.None, out result));
Assert.False(DateTime.TryParseExact("", "d", new MyFormatter(), DateTimeStyles.None, out result));
Assert.False(DateTime.TryParseExact("", new[] { "d" }, new MyFormatter(), DateTimeStyles.None, out result));
Assert.False(DateTime.TryParseExact("abc", (string)null, new MyFormatter(), DateTimeStyles.None, out result));
Assert.False(DateTime.TryParseExact("abc", (string[])null, new MyFormatter(), DateTimeStyles.None, out result));
Assert.False(DateTime.TryParseExact("abc", "", new MyFormatter(), DateTimeStyles.None, out result));
Assert.False(DateTime.TryParseExact("abc", new string[0], new MyFormatter(), DateTimeStyles.None, out result));
Assert.False(DateTime.TryParseExact("abc", new string[] { null }, new MyFormatter(), DateTimeStyles.None, out result));
Assert.False(DateTime.TryParseExact("abc", new[] { "" }, new MyFormatter(), DateTimeStyles.None, out result));
Assert.False(DateTime.TryParseExact("abc", new[] { "" }, new MyFormatter(), DateTimeStyles.None, out result));
}
[Fact]
public static void TryParse_String()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("g");
DateTime result;
Assert.True(DateTime.TryParse(expectedString, out result));
Assert.Equal(expectedString, result.ToString("g"));
}
[Fact]
public static void TryParse_String_FormatProvider_DateTimeStyles_U()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("u");
DateTime result;
Assert.True(DateTime.TryParse(expectedString, null, DateTimeStyles.AdjustToUniversal, out result));
Assert.Equal(expectedString, result.ToString("u"));
}
[Fact]
public static void TryParse_String_FormatProvider_DateTimeStyles_G()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("g");
DateTime result;
Assert.True(DateTime.TryParse(expectedString, null, DateTimeStyles.AdjustToUniversal, out result));
Assert.Equal(expectedString, result.ToString("g"));
}
[Fact]
public static void TryParse_TimeDesignators_NetCore()
{
DateTime result;
Assert.True(DateTime.TryParse("4/21 5am", new CultureInfo("en-US"), DateTimeStyles.None, out result));
Assert.Equal(4, result.Month);
Assert.Equal(21, result.Day);
Assert.Equal(5, result.Hour);
Assert.True(DateTime.TryParse("4/21 5pm", new CultureInfo("en-US"), DateTimeStyles.None, out result));
Assert.Equal(4, result.Month);
Assert.Equal(21, result.Day);
Assert.Equal(17, result.Hour);
}
public static IEnumerable<object[]> StandardFormatSpecifiers()
{
yield return new object[] { "d" };
yield return new object[] { "D" };
yield return new object[] { "f" };
yield return new object[] { "F" };
yield return new object[] { "g" };
yield return new object[] { "G" };
yield return new object[] { "m" };
yield return new object[] { "M" };
yield return new object[] { "o" };
yield return new object[] { "O" };
yield return new object[] { "r" };
yield return new object[] { "R" };
yield return new object[] { "s" };
yield return new object[] { "t" };
yield return new object[] { "T" };
yield return new object[] { "u" };
yield return new object[] { "U" };
yield return new object[] { "y" };
yield return new object[] { "Y" };
}
[Theory]
[MemberData(nameof(StandardFormatSpecifiers))]
public static void ParseExact_ToStringThenParseExactRoundtrip_Success(string standardFormat)
{
var r = new Random(42);
for (int i = 0; i < 200; i++) // test with a bunch of random dates
{
DateTime dt = new DateTime(DateTime.MinValue.Ticks + (long)(r.NextDouble() * (DateTime.MaxValue.Ticks - DateTime.MinValue.Ticks)), DateTimeKind.Unspecified);
string expected = dt.ToString(standardFormat);
Assert.Equal(expected, DateTime.ParseExact(expected, standardFormat, null).ToString(standardFormat));
Assert.Equal(expected, DateTime.ParseExact(expected, standardFormat, null, DateTimeStyles.None).ToString(standardFormat));
Assert.Equal(expected, DateTime.ParseExact(expected, new[] { standardFormat }, null, DateTimeStyles.None).ToString(standardFormat));
Assert.Equal(expected, DateTime.ParseExact(expected, new[] { standardFormat }, null, DateTimeStyles.AllowWhiteSpaces).ToString(standardFormat));
Assert.True(DateTime.TryParseExact(expected, standardFormat, null, DateTimeStyles.None, out DateTime actual));
Assert.Equal(expected, actual.ToString(standardFormat));
Assert.True(DateTime.TryParseExact(expected, new[] { standardFormat }, null, DateTimeStyles.None, out actual));
Assert.Equal(expected, actual.ToString(standardFormat));
// Should also parse with Parse, though may not round trip exactly
DateTime.Parse(expected);
}
}
public static IEnumerable<object[]> InvalidFormatSpecifierRoundtripPairs()
{
yield return new object[] { "d", "f" };
yield return new object[] { "o", "r" };
yield return new object[] { "u", "y" };
}
[Theory]
[MemberData(nameof(InvalidFormatSpecifierRoundtripPairs))]
public static void ParseExact_ToStringThenParseExact_RoundtripWithOtherFormat_Fails(string toStringFormat, string parseFormat)
{
DateTime dt = DateTime.Now;
string expected = dt.ToString(toStringFormat);
Assert.Throws<FormatException>(() => DateTime.ParseExact(expected, parseFormat, null));
Assert.Throws<FormatException>(() => DateTime.ParseExact(expected, parseFormat, null, DateTimeStyles.None));
Assert.Throws<FormatException>(() => DateTime.ParseExact(expected, new[] { parseFormat }, null, DateTimeStyles.None));
Assert.False(DateTime.TryParseExact(expected, parseFormat, null, DateTimeStyles.None, out DateTime result));
Assert.False(DateTime.TryParseExact(expected, new[] { parseFormat }, null, DateTimeStyles.None, out result));
}
[Theory]
[MemberData(nameof(ParseExact_TestData_R))]
public static void ParseExact_String_String_FormatProvider_DateTimeStyles_R(DateTime dt, string input)
{
Assert.Equal(DateTimeKind.Unspecified, DateTime.ParseExact(input, "r", null).Kind);
Assert.Equal(dt.ToString("r"), DateTime.ParseExact(input, "r", null).ToString("r"));
Assert.Equal(dt.ToString("r"), DateTime.ParseExact(input, "r", null, DateTimeStyles.None).ToString("r"));
const string Whitespace = " \t\r\n ";
Assert.Equal(dt.ToString("r"), DateTime.ParseExact(Whitespace + input, "r", null, DateTimeStyles.AllowLeadingWhite).ToString("r"));
Assert.Equal(dt.ToString("r"), DateTime.ParseExact(input + Whitespace, "r", null, DateTimeStyles.AllowTrailingWhite).ToString("r"));
Assert.Equal(dt.ToString("r"), DateTime.ParseExact(
Whitespace +
input +
Whitespace, "r", null, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite).ToString("r"));
Assert.Equal(dt.ToString("r"), DateTime.ParseExact(
input.Substring(0, 4) +
Whitespace +
input.Substring(4), "r", null, DateTimeStyles.AllowInnerWhite).ToString("r"));
Assert.Equal(dt.ToString("r"), DateTime.ParseExact(
Whitespace +
input.Substring(0, 4) +
Whitespace +
input.Substring(4) +
Whitespace, "r", null, DateTimeStyles.AllowWhiteSpaces).ToString("r"));
}
public static IEnumerable<object[]> ParseExact_TestData_R()
{
// Lowest, highest, and random DateTime in lower, upper, and normal casing
var pairs = new(DateTime, string)[]
{
(DateTime.MaxValue, "Fri, 31 Dec 9999 23:59:59"),
(DateTime.MinValue, "Mon, 01 Jan 0001 00:00:00"),
(new DateTime(1906, 8, 15, 7, 24, 5, 300), "Wed, 15 Aug 1906 07:24:05"),
};
foreach ((DateTime, string) pair in pairs)
{
yield return new object[] { pair.Item1, pair.Item2 + " GMT" };
yield return new object[] { pair.Item1, pair.Item2.ToLowerInvariant() + " GMT" };
yield return new object[] { pair.Item1, pair.Item2.ToUpperInvariant() + " GMT" };
}
// All months
DateTime dt = DateTime.UtcNow;
for (int i = 0; i < 12; i++)
{
dt = dt.AddMonths(1);
yield return new object[] { dt, dt.ToString("R") };
}
// All days
for (int i = 0; i < 7; i++)
{
dt = dt.AddDays(1);
yield return new object[] { dt, dt.ToString("R") };
}
}
[Theory]
[MemberData(nameof(ParseExact_TestData_InvalidData_R))]
public static void ParseExact_InvalidData_R(string invalidString)
{
Assert.Throws<FormatException>(() => DateTime.ParseExact(invalidString, "r", null));
Assert.Throws<FormatException>(() => DateTime.ParseExact(invalidString, "r", null, DateTimeStyles.None));
Assert.Throws<FormatException>(() => DateTime.ParseExact(invalidString, new string[] { "r" }, null, DateTimeStyles.None));
}
public static IEnumerable<object[]> ParseExact_TestData_InvalidData_R()
{
yield return new object[] { "Thu, 15 Aug 1906 07:24:05 GMT" }; // invalid day of week
yield return new object[] { "Ste, 15 Aug 1906 07:24:05 GMT" }; // invalid day of week
yield return new object[] { "We, 15 Aug 1906 07:24:05 GMT" }; // too short day of week
yield return new object[] { "Wedn, 15 Aug 1906 07:24:05 GMT" }; // too long day of week
yield return new object[] { "Wed, 32 Aug 1906 07:24:05 GMT" }; // too large day
yield return new object[] { "Wed, -1 Aug 1906 07:24:05 GMT" }; // too small day
yield return new object[] { "Wed, 15 Au 1906 07:24:05 GMT" }; // too small month
yield return new object[] { "Wed, 15 August 1906 07:24:05 GMT" }; // too large month
yield return new object[] { "Wed, 15 Aug -1 07:24:05 GMT" }; // too small year
yield return new object[] { "Wed, 15 Aug 10000 07:24:05 GMT" }; // too large year
yield return new object[] { "Wed, 15 Aug 1906 24:24:05 GMT" }; // too large hour
yield return new object[] { "Wed, 15 Aug 1906 07:60:05 GMT" }; // too large minute
yield return new object[] { "Wed, 15 Aug 1906 07:24:60 GMT" }; // too large second
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 STE" }; // invalid timezone
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 GM" }; // too short timezone
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 GMTT" }; // too long timezone
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 gmt" }; // wrong casing
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 Z" }; // zulu invalid
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 UTC" }; // UTC invalid
yield return new object[] { " Wed, 15 Aug 1906 07:24:05 GMT" }; // whitespace before
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 GMT " }; // whitespace after
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 GMT" }; // extra whitespace middle
yield return new object[] { "Wed, 15 Aug 1906 07: 24:05 GMT" }; // extra whitespace middle
yield return new object[] { "Wed,\t15 Aug 1906 07:24:05 GMT" }; // wrong whitespace for first space
yield return new object[] { "Wed, 15\tAug 1906 07:24:05 GMT" }; // wrong whitespace for second space
yield return new object[] { "Wed, 15 Aug\t1906 07:24:05 GMT" }; // wrong whitespace for third space
yield return new object[] { "Wed, 15 Aug 1906\t07:24:05 GMT" }; // wrong whitespace for fourth space
yield return new object[] { "Wed, 15 Aug 1906 07:24:05\tGMT" }; // wrong whitespace for fifth space
yield return new object[] { "Wed; 15 Aug 1906 07:24:05 GMT" }; // wrong comma
yield return new object[] { "Wed\x642C 15 Aug 1906 07:24:05 GMT" }; // wrong comma
yield return new object[] { "Wed, 15 Aug 1906 07;24:05 GMT" }; // wrong first colon
yield return new object[] { "Wed, 15 Aug 1906 07:24;05 GMT" }; // wrong second colon
yield return new object[] { "\x2057ed, 15 Aug 1906 07:24:05 GMT" }; // invalid characters to validate ASCII checks on day of week
yield return new object[] { "W\x5765d, 15 Aug 1906 07:24:05 GMT" }; // invalid characters to validate ASCII checks on day of week
yield return new object[] { "We\x6564, 15 Aug 1906 07:24:05 GMT" }; // invalid characters to validate ASCII checks on day of week
yield return new object[] { "Wed, 15 \x2041ug 1906 07:24:05 GMT" }; // invalid characters to validate ASCII checks on month
yield return new object[] { "Wed, 15 A\x4175g 1906 07:24:05 GMT" }; // invalid characters to validate ASCII checks on month
yield return new object[] { "Wed, 15 Au\x7567 1906 07:24:05 GMT" }; // invalid characters to validate ASCII checks on month
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 \x2047MT" }; // invalid characters to validate ASCII checks on GMT
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 G\x474DT" }; // invalid characters to validate ASCII checks on GMT
yield return new object[] { "Wed, 15 Aug 1906 07:24:05 GM\x4D54" }; // invalid characters to validate ASCII checks on GMT
yield return new object[] { "Wed, A5 Aug 1906 07:24:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 1A Aug 1906 07:24:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug A906 07:24:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug 1A06 07:24:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug 19A6 07:24:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug 190A 07:24:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug 1906 A7:24:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug 1906 0A:24:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug 1906 07:A4:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug 1906 07:2A:05 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug 1906 07:24:A5 GMT" }; // invalid digits
yield return new object[] { "Wed, 15 Aug 1906 07:24:0A GMT" }; // invalid digits
}
[Theory]
[MemberData(nameof(ParseExact_TestData_O))]
public static void ParseExact_String_String_FormatProvider_DateTimeStyles_O(DateTime dt, string input)
{
string expectedString;
if (input.Length == 27) // no timezone
{
Assert.Equal(DateTimeKind.Unspecified, DateTime.ParseExact(input, "o", null).Kind);
expectedString = dt.ToString("o");
}
else // "Z" or +/- offset
{
Assert.Equal(DateTimeKind.Local, DateTime.ParseExact(input, "o", null).Kind);
expectedString = dt.ToLocalTime().ToString("o");
}
Assert.Equal(expectedString, DateTime.ParseExact(input, "o", null).ToString("o"));
Assert.Equal(expectedString, DateTime.ParseExact(input, "o", null, DateTimeStyles.None).ToString("o"));
const string Whitespace = " \t\r\n ";
Assert.Equal(expectedString, DateTime.ParseExact(Whitespace + input, "o", null, DateTimeStyles.AllowLeadingWhite).ToString("o"));
Assert.Equal(expectedString, DateTime.ParseExact(input + Whitespace, "o", null, DateTimeStyles.AllowTrailingWhite).ToString("o"));
Assert.Equal(expectedString, DateTime.ParseExact(
Whitespace +
input +
Whitespace, "o", null, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite).ToString("o"));
Assert.Equal(expectedString, DateTime.ParseExact(
input.Substring(0, 27) +
Whitespace +
input.Substring(27), "o", null, DateTimeStyles.AllowInnerWhite).ToString("o"));
Assert.Equal(expectedString, DateTime.ParseExact(
Whitespace +
input.Substring(0, 27) +
Whitespace +
input.Substring(27) +
Whitespace, "o", null, DateTimeStyles.AllowWhiteSpaces).ToString("o"));
}
public static IEnumerable<object[]> ParseExact_TestData_O()
{
// Arbitrary DateTime in each of Unspecified, Utc, and Local kinds.
foreach (DateTimeKind kind in new[] { DateTimeKind.Unspecified, DateTimeKind.Utc, DateTimeKind.Local })
{
var dt = new DateTime(1234567891234567891, kind);
yield return new object[] { dt, dt.ToString("o") };
}
// Min and max in each of Unspecified, Utc, and Local kinds.
foreach (DateTime dt in new[] { DateTime.MinValue, DateTime.MaxValue })
{
yield return new object[] { dt, dt.ToString("o") };
yield return new object[] { dt.ToUniversalTime(), dt.ToUniversalTime().ToString("o") };
yield return new object[] { dt.ToLocalTime(), dt.ToLocalTime().ToString("o") };
}
// 1-digit offset hour is accepted due to legacy/compat
yield return new object[] { new DateTime(636664076235238523, DateTimeKind.Utc), "2018-07-05T18:36:43.5238523+1:23" };
}
[Theory]
[MemberData(nameof(ParseExact_TestData_InvalidData_O))]
public static void ParseExact_InvalidData_O(string invalidString)
{
Assert.Throws<FormatException>(() => DateTime.ParseExact(invalidString, "o", null));
Assert.Throws<FormatException>(() => DateTime.ParseExact(invalidString, "o", null, DateTimeStyles.None));
Assert.Throws<FormatException>(() => DateTime.ParseExact(invalidString, new string[] { "o" }, null, DateTimeStyles.None));
}
public static IEnumerable<object[]> ParseExact_TestData_InvalidData_O()
{
yield return new object[] { " 2018-07-05T18:36:43.5238523" }; // whitespace before
yield return new object[] { " 2018-07-05T18:36:43.5238523Z" }; // whitespace before
yield return new object[] { " 2018-07-05T18:36:43.5238523+00:00" }; // whitespace before
yield return new object[] { "2018-07-05T18:36:43.5238523 " }; // whitespace after
yield return new object[] { "2018-07-05T18:36:43.5238523Z " }; // whitespace after
yield return new object[] { "2018-07-05T18:36:43.5238523+00:00 " }; // whitespace after
yield return new object[] { "2018-07-05T18:36:43.5238523 Z" }; // whitespace inside
yield return new object[] { "2018-07-05T18:36:43.5238523 +00:00" }; // whitespace inside
yield return new object[] { "201-07-05T18:36:43.5238523" }; // too short year
yield return new object[] { "20181-07-05T18:36:43.5238523" }; // too long year
yield return new object[] { "2018-7-05T18:36:43.5238523" }; // too short month
yield return new object[] { "2018-017-05T18:36:43.5238523" }; // too long month
yield return new object[] { "2018-07-5T18:36:43.5238523" }; // too short day
yield return new object[] { "2018-07-015T18:36:43.5238523" }; // too long day
yield return new object[] { "2018-07-05T018:36:43.5238523" }; // too long hour
yield return new object[] { "2018-07-05T8:36:43.5238523" }; // too short hour
yield return new object[] { "2018-07-05T18:6:43.5238523" }; // too short minute
yield return new object[] { "2018-07-05T18:036:43.5238523" }; // too long minute
yield return new object[] { "2018-07-05T18:06:3.5238523" }; // too short second
yield return new object[] { "2018-07-05T18:36:043.5238523" }; // too long second
yield return new object[] { "2018-07-05T18:06:03.238523" }; // too short fraction
yield return new object[] { "2018-07-05T18:36:43.15238523" }; // too long fraction
yield return new object[] { "2018-07-05T18:36:43.5238523+001:00" }; // too long offset hour
yield return new object[] { "2018-07-05T18:36:43.5238523+01:0" }; // too short offset minute
yield return new object[] { "2018-07-05T18:36:43.5238523+01:000" }; // too long offset minute
yield return new object[] { "2018=07-05T18:36:43.5238523" }; // invalid first hyphen
yield return new object[] { "2018-07=05T18:36:43.5238523" }; // invalid second hyphen
yield return new object[] { "2018-07-05A18:36:43.5238523" }; // invalid T
yield return new object[] { "2018-07-05T18;36:43.5238523" }; // invalid first colon
yield return new object[] { "2018-07-05T18:36;43.5238523" }; // invalid second colon
yield return new object[] { "2018-07-05T18:36:43,5238523" }; // invalid period
yield return new object[] { "2018-07-05T18:36:43.5238523,00:00" }; // invalid +/-/Z
yield return new object[] { "2018-07-05T18:36:43.5238523+00;00" }; // invalid third colon
yield return new object[] { "2018-07-05T18:36:43.5238523+1;00" }; // invalid colon with 1-digit offset hour
yield return new object[] { "a018-07-05T18:36:43.5238523" }; // invalid digits
yield return new object[] { "2a18-07-05T18:36:43.5238523" }; // invalid digits
yield return new object[] { "20a8-07-05T18:36:43.5238523" }; // invalid digits
yield return new object[] { "201a-07-05T18:36:43.5238523" }; // invalid digits
yield return new object[] { "2018-a7-05T18:36:43.5238523" }; // invalid digits
yield return new object[] { "2018-0a-05T18:36:43.5238523" }; // invalid digits
yield return new object[] { "2018-07-a5T18:36:43.5238523" }; // invalid digits
yield return new object[] { "2018-07-0aT18:36:43.5238523" }; // invalid digits
yield return new object[] { "2018-07-05Ta8:36:43.5238523" }; // invalid digits
yield return new object[] { "2018-07-05T1a:36:43.5238523" }; // invalid digits
yield return new object[] { "2018-07-05T18:a6:43.5238523" }; // invalid digits
yield return new object[] { "2018-07-05T18:3a:43.5238523" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:a3.5238523" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:4a.5238523" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.a238523" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.5a38523" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.52a8523" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.523a523" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.5238a23" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.52385a3" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.523852a" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.5238523+a0:00" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.5238523+0a:00" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.5238523+00:a0" }; // invalid digits
yield return new object[] { "2018-07-05T18:36:43.5238523+00:0a" }; // invalid digits
}
[Fact]
public static void ParseExact_String_String_FormatProvider_DateTimeStyles_CustomFormatProvider()
{
var formatter = new MyFormatter();
string dateBefore = DateTime.Now.ToString();
DateTime dateAfter = DateTime.ParseExact(dateBefore, "G", formatter, DateTimeStyles.AdjustToUniversal);
Assert.Equal(dateBefore, dateAfter.ToString());
}
[Fact]
public static void ParseExact_String_StringArray_FormatProvider_DateTimeStyles()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("g");
var formats = new string[] { "g" };
DateTime result = DateTime.ParseExact(expectedString, formats, null, DateTimeStyles.AdjustToUniversal);
Assert.Equal(expectedString, result.ToString("g"));
}
[Fact]
public static void TryParseExact_String_String_FormatProvider_DateTimeStyles_NullFormatProvider()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("g");
DateTime resulted;
Assert.True(DateTime.TryParseExact(expectedString, "g", null, DateTimeStyles.AdjustToUniversal, out resulted));
Assert.Equal(expectedString, resulted.ToString("g"));
}
[Fact]
public static void TryParseExact_String_StringArray_FormatProvider_DateTimeStyles()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("g");
var formats = new string[] { "g" };
DateTime result;
Assert.True(DateTime.TryParseExact(expectedString, formats, null, DateTimeStyles.AdjustToUniversal, out result));
Assert.Equal(expectedString, result.ToString("g"));
}
[Fact]
// Regression test for https://github.com/dotnet/runtime/issues/9565
public static void TryParseExact_EmptyAMPMDesignator()
{
var englishCulture = new CultureInfo("en-US");
englishCulture.DateTimeFormat.AMDesignator = "";
englishCulture.DateTimeFormat.PMDesignator = "";
Assert.False(DateTime.TryParseExact(" ", "%t", englishCulture, DateTimeStyles.None, out _));
}
[Fact]
public static void ParseExact_EscapedSingleQuotes()
{
DateTimeFormatInfo formatInfo;
if (PlatformDetection.IsBrowser)
{
formatInfo = DateTimeFormatInfo.GetInstance(new CultureInfo("id-ID"));
}
else
{
formatInfo = DateTimeFormatInfo.GetInstance(new CultureInfo("mt-MT"));
}
const string format = @"dddd, d' ta\' 'MMMM yyyy";
DateTime expected = new DateTime(1999, 2, 28, 17, 00, 01);
string formatted = expected.ToString(format, formatInfo);
DateTime actual = DateTime.ParseExact(formatted, format, formatInfo);
Assert.Equal(expected.Date, actual.Date);
}
[Theory]
[InlineData("fi-FI")]
[InlineData("nb-NO")]
[InlineData("nb-SJ")]
[InlineData("sr-Cyrl-XK")]
[InlineData("sr-Latn-ME")]
[InlineData("sr-Latn-RS")]
[InlineData("sr-Latn-XK")]
public static void Parse_SpecialCultures(string cultureName)
{
// Test DateTime parsing with cultures which has the date separator and time separator are same
CultureInfo cultureInfo;
try
{
cultureInfo = new CultureInfo(cultureName);
}
catch (CultureNotFoundException)
{
// Ignore un-supported culture in current platform
return;
}
var dateTime = new DateTime(2015, 11, 20, 11, 49, 50);
string dateString = dateTime.ToString(cultureInfo.DateTimeFormat.ShortDatePattern, cultureInfo);
DateTime parsedDate;
Assert.True(DateTime.TryParse(dateString, cultureInfo, DateTimeStyles.None, out parsedDate));
if (cultureInfo.DateTimeFormat.ShortDatePattern.Contains("yyyy") || HasDifferentDateTimeSeparators(cultureInfo.DateTimeFormat))
{
Assert.Equal(dateTime.Date, parsedDate);
}
else
{
// When the date separator and time separator are the same, DateTime.TryParse cannot
// tell the difference between a short date like dd.MM.yy and a short time
// like HH.mm.ss. So it assumes that if it gets 03.04.11, that must be a time
// and uses the current date to construct the date time.
DateTime now = DateTime.Now;
Assert.Equal(new DateTime(now.Year, now.Month, now.Day, dateTime.Day, dateTime.Month, dateTime.Year % 100), parsedDate);
}
dateString = dateTime.ToString(cultureInfo.DateTimeFormat.LongDatePattern, cultureInfo);
Assert.True(DateTime.TryParse(dateString, cultureInfo, DateTimeStyles.None, out parsedDate));
Assert.Equal(dateTime.Date, parsedDate);
dateString = dateTime.ToString(cultureInfo.DateTimeFormat.FullDateTimePattern, cultureInfo);
Assert.True(DateTime.TryParse(dateString, cultureInfo, DateTimeStyles.None, out parsedDate));
Assert.Equal(dateTime, parsedDate);
dateString = dateTime.ToString(cultureInfo.DateTimeFormat.LongTimePattern, cultureInfo);
Assert.True(DateTime.TryParse(dateString, cultureInfo, DateTimeStyles.None, out parsedDate));
Assert.Equal(dateTime.TimeOfDay, parsedDate.TimeOfDay);
}
private static bool HasDifferentDateTimeSeparators(DateTimeFormatInfo dateTimeFormat)
{
// Since .NET Core doesn't expose DateTimeFormatInfo DateSeparator and TimeSeparator properties,
// this method gets the separators using DateTime.ToString by passing in the invariant separators.
// The invariant separators will then get turned into the culture's separators by ToString,
// which are then compared.
var dateTime = new DateTime(2015, 11, 24, 17, 57, 29);
string separators = dateTime.ToString("/@:", dateTimeFormat);
int delimiterIndex = separators.IndexOf('@');
string dateSeparator = separators.Substring(0, delimiterIndex);
string timeSeparator = separators.Substring(delimiterIndex + 1);
return dateSeparator != timeSeparator;
}
[Fact]
public static void GetDateTimeFormats()
{
var allStandardFormats = new char[]
{
'd', 'D', 'f', 'F', 'g', 'G',
'm', 'M', 'o', 'O', 'r', 'R',
's', 't', 'T', 'u', 'U', 'y', 'Y',
};
var dateTime = new DateTime(2009, 7, 28, 5, 23, 15);
var formats = new List<string>();
foreach (char format in allStandardFormats)
{
string[] dates = dateTime.GetDateTimeFormats(format);
Assert.True(dates.Length > 0);
DateTime parsedDate;
Assert.True(DateTime.TryParseExact(dates[0], format.ToString(), CultureInfo.CurrentCulture, DateTimeStyles.None, out parsedDate));
formats.AddRange(dates);
}
List<string> actualFormats = dateTime.GetDateTimeFormats().ToList();
Assert.Equal(formats.OrderBy(t => t), actualFormats.OrderBy(t => t));
actualFormats = dateTime.GetDateTimeFormats(CultureInfo.CurrentCulture).ToList();
Assert.Equal(formats.OrderBy(t => t), actualFormats.OrderBy(t => t));
}
[Fact]
public static void GetDateTimeFormats_FormatSpecifier_InvalidFormat()
{
var dateTime = new DateTime(2009, 7, 28, 5, 23, 15);
Assert.Throws<FormatException>(() => dateTime.GetDateTimeFormats('x')); // No such format
}
private static void VerifyDateTime(DateTime dateTime, int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind)
{
Assert.Equal(year, dateTime.Year);
Assert.Equal(month, dateTime.Month);
Assert.Equal(day, dateTime.Day);
Assert.Equal(hour, dateTime.Hour);
Assert.Equal(minute, dateTime.Minute);
Assert.Equal(second, dateTime.Second);
Assert.Equal(millisecond, dateTime.Millisecond);
Assert.Equal(kind, dateTime.Kind);
}
private class MyFormatter : IFormatProvider
{
public object GetFormat(Type formatType)
{
return typeof(IFormatProvider) == formatType ? this : null;
}
}
[Fact]
public static void InvalidDateTimeStyles()
{
string strDateTime = "Thursday, August 31, 2006 1:14";
string[] formats = new string[] { "f" };
IFormatProvider provider = new CultureInfo("en-US");
DateTimeStyles style = DateTimeStyles.AssumeLocal | DateTimeStyles.AssumeUniversal;
AssertExtensions.Throws<ArgumentException>("style", () => DateTime.ParseExact(strDateTime, formats, provider, style));
}
[Fact]
public static void TestTryParseAtBoundaries()
{
Assert.True(DateTime.TryParse("9999-12-31T23:59:59.9999999", out var maxDateTime),
"DateTime parsing expected to succeed at the boundary DateTime.MaxValue");
Assert.Equal(DateTime.MaxValue, maxDateTime);
Assert.False(DateTime.TryParse("9999-12-31T23:59:59.999999999Z", out var dateTime),
"DateTime parsing expected to throw with any dates greater than DateTime.MaxValue");
}
public static IEnumerable<object[]> Parse_ValidInput_Succeeds_MemberData()
{
yield return new object[] { "1234 12", CultureInfo.InvariantCulture, new DateTime(1234, 12, 1, 0, 0, 0) };
yield return new object[] { "12 1234", CultureInfo.InvariantCulture, new DateTime(1234, 12, 1, 0, 0, 0) };
yield return new object[] { "12 1234 11", CultureInfo.InvariantCulture, new DateTime(1234, 12, 11, 0, 0, 0) };
yield return new object[] { "1234 12 13", CultureInfo.InvariantCulture, new DateTime(1234, 12, 13, 0, 0, 0) };
yield return new object[] { "12 13 1234", CultureInfo.InvariantCulture, new DateTime(1234, 12, 13, 0, 0, 0) };
yield return new object[] { "1 1 1", CultureInfo.InvariantCulture, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "2 2 2Z", CultureInfo.InvariantCulture, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2002, 2, 2, 0, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
yield return new object[] { "#10/10/2095#\0", CultureInfo.InvariantCulture, new DateTime(2095, 10, 10, 0, 0, 0) };
yield return new object[] { "2020-5-7T09:37:00.0000000+00:00\0", CultureInfo.InvariantCulture, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2020, 5, 7, 9, 37, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
yield return new object[] { "#2020-5-7T09:37:00.0000000+00:00#", CultureInfo.InvariantCulture, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2020, 5, 7, 9, 37, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
yield return new object[] { "#2020-5-7T09:37:00.0000000+00:00#\0", CultureInfo.InvariantCulture, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2020, 5, 7, 9, 37, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
yield return new object[] { "2020-5-7T09:37:00.0000000+00:00", CultureInfo.InvariantCulture, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2020, 5, 7, 9, 37, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
if (PlatformDetection.IsNotInvariantGlobalization)
{
DateTime today = DateTime.Today;
var hebrewCulture = new CultureInfo("he-IL");
hebrewCulture.DateTimeFormat.Calendar = new HebrewCalendar();
yield return new object[] { today.ToString(hebrewCulture), hebrewCulture, today };
CultureInfo culture;
if (PlatformDetection.IsBrowser)
{
culture = new CultureInfo("pl-PL");
}
else
{
culture = new CultureInfo("mn-MN");
}
yield return new object[] { today.ToString(culture), culture, today };
}
}
[Theory]
[MemberData(nameof(Parse_ValidInput_Succeeds_MemberData))]
public static void Parse_ValidInput_Succeeds(string input, CultureInfo culture, DateTime? expected)
{
Assert.Equal(expected, DateTime.Parse(input, culture));
}
public static IEnumerable<object[]> ParseExact_ValidInput_Succeeds_MemberData()
{
foreach (DateTimeStyles style in new[] { DateTimeStyles.None, DateTimeStyles.AllowWhiteSpaces })
{
yield return new object[] { "9", "%d", CultureInfo.InvariantCulture, style, new DateTime(DateTime.Now.Year, 1, 9, 0, 0, 0) };
yield return new object[] { "15", "dd", CultureInfo.InvariantCulture, style, new DateTime(DateTime.Now.Year, 1, 15, 0, 0, 0) };
yield return new object[] { "9", "%M", CultureInfo.InvariantCulture, style, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "09", "MM", CultureInfo.InvariantCulture, style, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "Sep", "MMM", CultureInfo.InvariantCulture, style, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "September", "MMMM", CultureInfo.InvariantCulture, style, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "1", "%y", CultureInfo.InvariantCulture, style, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "01", "yy", CultureInfo.InvariantCulture, style, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "2001", "yyyy", CultureInfo.InvariantCulture, style, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "3", "%H", CultureInfo.InvariantCulture, style, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "03", "HH", CultureInfo.InvariantCulture, style, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "3A", "ht", CultureInfo.InvariantCulture, style, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "03A", "hht", CultureInfo.InvariantCulture, style, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "3P", "ht", CultureInfo.InvariantCulture, style, DateTime.Today + TimeSpan.FromHours(12 + 3) };
yield return new object[] { "03P", "hht", CultureInfo.InvariantCulture, style, DateTime.Today + TimeSpan.FromHours(12 + 3) };
yield return new object[] { "2017-10-11 01:23:45Z", "u", CultureInfo.InvariantCulture, style, new DateTime(2017, 10, 11, 1, 23, 45) };
yield return new object[] { "9/8/2017 10:11:12 AM", "M/d/yyyy HH':'mm':'ss tt", CultureInfo.InvariantCulture, style, new DateTime(2017, 9, 8, 10, 11, 12) };
yield return new object[] { "9/8/2017 20:11:12 PM", "M/d/yyyy HH':'mm':'ss tt", CultureInfo.InvariantCulture, style, new DateTime(2017, 9, 8, 20, 11, 12) };
yield return new object[] { "Fri, 08 Sep 2017 11:18:19 -0000", "ddd, d MMM yyyy H:m:s zzz", new CultureInfo("en-US"), DateTimeStyles.AllowInnerWhite, new DateTime(2017, 9, 8, 11, 18, 19, DateTimeKind.Utc) };
yield return new object[] { "1234-05-06T07:00:00.8Z", "yyyy-MM-dd'T'HH:mm:ss.FFF'Z'", CultureInfo.InvariantCulture, style, new DateTime(1234, 5, 6, 7, 0, 0, 800) };
yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ss.FFF'Z'", CultureInfo.InvariantCulture, style, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ssFFF'Z'", CultureInfo.InvariantCulture, style, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ssFFF'Z'", CultureInfo.InvariantCulture, style, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ssFFFZ", CultureInfo.InvariantCulture, style, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1234, 5, 6, 7, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
yield return new object[] { "1234-05-06T07:00:00GMT", "yyyy-MM-dd'T'HH:mm:ssFFFZ", CultureInfo.InvariantCulture, style, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1234, 5, 6, 7, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
}
yield return new object[] { "9", "\" \"%d", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(DateTime.Now.Year, 1, 9, 0, 0, 0) };
yield return new object[] { "15", "\' \'dd", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(DateTime.Now.Year, 1, 15, 0, 0, 0) };
yield return new object[] { "9", "\" \"%M", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "09", "\" \"MM", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "Sep", "\" \"MMM", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "September", "\' \'MMMM", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "1", "\' \'%y", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "01", "\" \"yy", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "2001", "\" \"yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "3", "\" \"%H", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "03", "\" \"HH", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "3A", "\" \"ht", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "03A", "\" \"hht", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "3P", "\' \'ht", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, DateTime.Today + TimeSpan.FromHours(12 + 3) };
yield return new object[] { "03P", "\" \"hht", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, DateTime.Today + TimeSpan.FromHours(12 + 3) };
yield return new object[] { "2017-10-11 01:23:45Z", "u", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(2017, 10, 11, 1, 23, 45) };
yield return new object[] { "9/8/2017 10:11:12 AM", "\' \'M/d/yyyy HH':'mm':'ss tt", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(2017, 9, 8, 10, 11, 12) };
yield return new object[] { "9/8/2017 20:11:12 PM", "\" \"M/d/yyyy HH':'mm':'ss tt", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(2017, 9, 8, 20, 11, 12) };
yield return new object[] { "1234-05-06T07:00:00.8Z", "\" \"yyyy-MM-dd'T'HH:mm:ss.FFF'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(1234, 5, 6, 7, 0, 0, 800) };
yield return new object[] { "1234-05-06T07:00:00Z", "\" \"yyyy-MM-dd'T'HH:mm:ss.FFF'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
yield return new object[] { "1234-05-06T07:00:00Z", "\' \'yyyy-MM-dd'T'HH:mm:ssFFF'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
yield return new object[] { "1234-05-06T07:00:00Z", "\' \'yyyy-MM-dd'T'HH:mm:ssFFF'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
yield return new object[] { "1234-05-06T07:00:00Z", "\" \"yyyy-MM-dd'T'HH:mm:ssFFFZ", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1234, 5, 6, 7, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
yield return new object[] { "1234-05-06T07:00:00GMT", "\" \"yyyy-MM-dd'T'HH:mm:ssFFFZ", CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1234, 5, 6, 7, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
yield return new object[] { "9", "%d\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(DateTime.Now.Year, 1, 9, 0, 0, 0) };
yield return new object[] { "15", "dd\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(DateTime.Now.Year, 1, 15, 0, 0, 0) };
yield return new object[] { "9", "%M\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "09", "MM\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "Sep", "MMM\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "September", "MMMM\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
yield return new object[] { "1", "%y\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "01", "yy\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "2001", "yyyy\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(2001, 1, 1, 0, 0, 0) };
yield return new object[] { "3", "%H\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "03", "HH\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "3A", "ht\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "03A", "hht\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, DateTime.Today + TimeSpan.FromHours(3) };
yield return new object[] { "3P", "ht\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, DateTime.Today + TimeSpan.FromHours(12 + 3) };
yield return new object[] { "03P", "hht\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, DateTime.Today + TimeSpan.FromHours(12 + 3) };
yield return new object[] { "2017-10-11 01:23:45Z", "u", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(2017, 10, 11, 1, 23, 45) };
yield return new object[] { "9/8/2017 10:11:12 AM", "M/d/yyyy HH':'mm':'ss tt\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(2017, 9, 8, 10, 11, 12) };
yield return new object[] { "9/8/2017 20:11:12 PM", "M/d/yyyy HH':'mm':'ss tt\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(2017, 9, 8, 20, 11, 12) };
yield return new object[] { "1234-05-06T07:00:00.8Z", "yyyy-MM-dd'T'HH:mm:ss.FFF'Z'\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(1234, 5, 6, 7, 0, 0, 800) };
yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ss.FFF'Z'\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ssFFF'Z'\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ssFFF'Z'\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ssFFFZ\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1234, 5, 6, 7, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
yield return new object[] { "1234-05-06T07:00:00GMT", "yyyy-MM-dd'T'HH:mm:ssFFFZ\" \"", CultureInfo.InvariantCulture, DateTimeStyles.AllowTrailingWhite, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1234, 5, 6, 7, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
yield return new object[] { "9/8/2017 10:11:12 AM ", "M/d/yyyy HH':'mm':'ss tt\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, new DateTime(2017, 9, 8, 10, 11, 12) };
yield return new object[] { "9/8/2017 10:11:12 AM ", "M/d/yyyy HH':'mm':'ss tt\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, new DateTime(2017, 9, 8, 10, 11, 12) };
yield return new object[] { "9/ 8 /2017 10:11:12 AM ", "M/d/yyyy HH':'mm':'ss tt\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, new DateTime(2017, 9, 8, 10, 11, 12) };
yield return new object[] { " 9 /8/2017 10:11:12 AM", "M/d/yyyy HH':'mm':'ss tt\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, new DateTime(2017, 9, 8, 10, 11, 12) };
yield return new object[] { "9/8/2017 10 : 11 : 12 AM", "M/d/yyyy HH':'mm':'ss tt\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, new DateTime(2017, 9, 8, 10, 11, 12) };
yield return new object[] { " 9 / 8 / 2017 10 : 11 : 12 AM", "M/d/yyyy HH':'mm':'ss tt\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, new DateTime(2017, 9, 8, 10, 11, 12) };
yield return new object[] { " 9 / 8 / 2017 10 : 11 : 12 AM", "M/d/yyyy HH':'mm':'ss tt\' \'", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, new DateTime(2017, 9, 8, 10, 11, 12) };
if (PlatformDetection.IsNotInvariantGlobalization)
{
var hebrewCulture = new CultureInfo("he-IL");
hebrewCulture.DateTimeFormat.Calendar = new HebrewCalendar();
DateTime today = DateTime.Today;
foreach (string pattern in hebrewCulture.DateTimeFormat.GetAllDateTimePatterns())
{
yield return new object[] { today.ToString(pattern, hebrewCulture), pattern, hebrewCulture, DateTimeStyles.None, null };
}
}
}
[Theory]
[MemberData(nameof(ParseExact_ValidInput_Succeeds_MemberData))]
public static void ParseExact_ValidInput_Succeeds(string input, string format, CultureInfo culture, DateTimeStyles style, DateTime? expected)
{
DateTime result1 = DateTime.ParseExact(input, format, culture, style);
DateTime result2 = DateTime.ParseExact(input, new[] { format }, culture, style);
Assert.True(DateTime.TryParseExact(input, format, culture, style, out DateTime result3));
Assert.True(DateTime.TryParseExact(input, new[] { format }, culture, style, out DateTime result4));
Assert.Equal(result1, result2);
Assert.Equal(result1, result3);
Assert.Equal(result1, result4);
if (expected != null) // some inputs don't roundtrip well
{
// Normalize values to make comparison easier
if (expected.Value.Kind != DateTimeKind.Utc)
{
expected = expected.Value.ToUniversalTime();
}
if (result1.Kind != DateTimeKind.Utc)
{
result1 = result1.ToUniversalTime();
}
Assert.Equal(expected, result1);
}
}
public static IEnumerable<object[]> ParseExact_InvalidInputs_Fail_MemberData()
{
yield return new object[] { "6/28/2004 13:00:00 AM", "M/d/yyyy HH':'mm':'ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "6/28/2004 03:00:00 PM", "M/d/yyyy HH':'mm':'ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "1", "dd", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "99", "dd", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "123", "dd", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "1", "mm", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "99", "mm", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "123", "mm", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "1", "ss", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "99", "ss", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "123", "ss", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "1", "MM", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "99", "MM", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "Fep", "MMM", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "Jantember", "MMMM", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "123", "YY", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "12345", "YYYY", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "1", "HH", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "99", "HH", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "123", "HH", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "1", "hh", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "99", "hh", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "123", "hh", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "1", "ff", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "123", "ff", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "123456", "fffff", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "1234", "fffff", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "AM", "t", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "PM", "t", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "PM", "ttt", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "AAM", "tt", CultureInfo.InvariantCulture, DateTimeStyles.None };
yield return new object[] { "CM", "tt", CultureInfo.InvariantCulture, DateTimeStyles.None };
}
[Theory]
[MemberData(nameof(ParseExact_InvalidInputs_Fail_MemberData))]
public static void ParseExact_InvalidInputs_Fail(string input, string format, CultureInfo culture, DateTimeStyles style)
{
Assert.Throws<FormatException>(() => DateTime.ParseExact(input, format, culture, style));
Assert.Throws<FormatException>(() => DateTime.ParseExact(input, new[] { format }, culture, style));
Assert.False(DateTime.TryParseExact(input, format, culture, style, out DateTime result));
Assert.False(DateTime.TryParseExact(input, new[] { format }, culture, style, out result));
}
public static IEnumerable<object[]> ToString_MatchesExpected_MemberData()
{
// Randomly generated data on .NET Framework with:
// using System;
// class Program
// {
// static void Main()
// {
// var rand = new Random(42);
// var bytes = new byte[8];
// int i = 0;
// while (i < 40)
// {
// DateTimeKind kind = rand.Next(2) == 0 ? DateTimeKind.Utc : DateTimeKind.Unspecified;
// string format;
// switch (rand.Next(4))
// {
// case 0: format = "o"; break;
// case 1: format = "O"; break;
// case 2: format = "r"; break;
// default: format = "R"; break;
// }
//
// try
// {
// rand.NextBytes(bytes);
// long seed = BitConverter.ToInt64(bytes, 0);
// var dt = new DateTime(seed, kind);
// Console.WriteLine($"yield return new object[] {{ new DateTime({seed}, DateTimeKind.{kind}), \"{format}\", null, \"{dt.ToString(format)}\" }};");
// i++;
// }
// catch { }
// }
// }
//}
yield return new object[] { new DateTime(2688006240964947440, DateTimeKind.Utc), "O", null, "8518-12-15T08:01:36.4947440Z" };
yield return new object[] { new DateTime(2461197105169450509, DateTimeKind.Utc), "r", null, "Sun, 23 Mar 7800 18:15:16 GMT" };
yield return new object[] { new DateTime(71363981510699949, DateTimeKind.Unspecified), "R", null, "Fri, 23 Feb 0227 04:49:11 GMT" };
yield return new object[] { new DateTime(1678426538898407093, DateTimeKind.Unspecified), "R", null, "Fri, 22 Sep 5319 07:24:49 GMT" };
yield return new object[] { new DateTime(2689041307785948711, DateTimeKind.Utc), "o", null, "8522-03-27T07:52:58.5948711Z" };
yield return new object[] { new DateTime(996610247053299209, DateTimeKind.Unspecified), "r", null, "Thu, 19 Feb 3159 01:58:25 GMT" };
yield return new object[] { new DateTime(3105391438361510074, DateTimeKind.Unspecified), "R", null, "Fri, 06 Aug 9841 01:17:16 GMT" };
yield return new object[] { new DateTime(946433487657072106, DateTimeKind.Utc), "R", null, "Mon, 17 Feb 3000 03:06:05 GMT" };
yield return new object[] { new DateTime(2521748413631767931, DateTimeKind.Unspecified), "R", null, "Sat, 08 Feb 7992 07:02:43 GMT" };
yield return new object[] { new DateTime(49349519375012969, DateTimeKind.Utc), "R", null, "Fri, 20 May 0157 11:58:57 GMT" };
yield return new object[] { new DateTime(796677276139881359, DateTimeKind.Utc), "o", null, "2525-07-28T04:20:13.9881359Z" };
yield return new object[] { new DateTime(3022911536338429542, DateTimeKind.Unspecified), "R", null, "Mon, 24 Mar 9580 04:53:53 GMT" };
yield return new object[] { new DateTime(1144652135553351618, DateTimeKind.Utc), "R", null, "Tue, 04 Apr 3628 20:39:15 GMT" };
yield return new object[] { new DateTime(2570858096011770291, DateTimeKind.Unspecified), "o", null, "8147-09-23T04:53:21.1770291" };
yield return new object[] { new DateTime(15695724649124585, DateTimeKind.Unspecified), "R", null, "Tue, 27 Sep 0050 08:21:04 GMT" };
yield return new object[] { new DateTime(1503933934291527034, DateTimeKind.Unspecified), "O", null, "4766-10-12T06:37:09.1527034" };
yield return new object[] { new DateTime(2688603665097410101, DateTimeKind.Unspecified), "r", null, "Tue, 05 Nov 8520 19:08:29 GMT" };
yield return new object[] { new DateTime(1310336900529542610, DateTimeKind.Unspecified), "r", null, "Tue, 17 Apr 4153 15:14:12 GMT" };
yield return new object[] { new DateTime(2313720085584182693, DateTimeKind.Unspecified), "O", null, "7332-11-20T18:22:38.4182693" };
yield return new object[] { new DateTime(2291958603891779335, DateTimeKind.Unspecified), "o", null, "7263-12-05T20:46:29.1779335" };
yield return new object[] { new DateTime(262036413643976979, DateTimeKind.Unspecified), "o", null, "0831-05-12T21:16:04.3976979" };
yield return new object[] { new DateTime(684781207384421044, DateTimeKind.Utc), "O", null, "2170-12-26T20:12:18.4421044Z" };
yield return new object[] { new DateTime(1444462249169683325, DateTimeKind.Utc), "r", null, "Mon, 27 Apr 4578 07:21:56 GMT" };
yield return new object[] { new DateTime(1155518137384061537, DateTimeKind.Unspecified), "r", null, "Sun, 10 Sep 3662 06:02:18 GMT" };
yield return new object[] { new DateTime(2333390479532380569, DateTimeKind.Unspecified), "O", null, "7395-03-22T10:12:33.2380569" };
yield return new object[] { new DateTime(2217528014591554502, DateTimeKind.Unspecified), "R", null, "Sat, 26 Jan 7028 08:24:19 GMT" };
yield return new object[] { new DateTime(2764551324904480205, DateTimeKind.Utc), "O", null, "8761-07-08T04:21:30.4480205Z" };
yield return new object[] { new DateTime(2880903932678729712, DateTimeKind.Utc), "O", null, "9130-03-23T13:14:27.8729712Z" };
yield return new object[] { new DateTime(507699902578704433, DateTimeKind.Utc), "O", null, "1609-11-02T15:04:17.8704433Z" };
yield return new object[] { new DateTime(2429953022324426129, DateTimeKind.Utc), "O", null, "7701-03-20T15:03:52.4426129Z" };
yield return new object[] { new DateTime(603147512164908366, DateTimeKind.Unspecified), "O", null, "1912-04-20T09:33:36.4908366" };
yield return new object[] { new DateTime(2900400428644841236, DateTimeKind.Utc), "R", null, "Thu, 02 Jan 9192 22:34:24 GMT" };
yield return new object[] { new DateTime(1710845568474490805, DateTimeKind.Utc), "O", null, "5422-06-16T08:00:47.4490805Z" };
yield return new object[] { new DateTime(2988999715803714268, DateTimeKind.Utc), "r", null, "Sun, 06 Oct 9472 09:53:00 GMT" };
yield return new object[] { new DateTime(1068133489112689365, DateTimeKind.Utc), "r", null, "Wed, 12 Oct 3385 14:41:51 GMT" };
yield return new object[] { new DateTime(798784044525059284, DateTimeKind.Unspecified), "R", null, "Mon, 31 Mar 2532 13:40:52 GMT" };
yield return new object[] { new DateTime(2561736813034040593, DateTimeKind.Utc), "O", null, "8118-10-28T03:55:03.4040593Z" };
yield return new object[] { new DateTime(1677975383149674547, DateTimeKind.Utc), "o", null, "5318-04-18T03:18:34.9674547Z" };
yield return new object[] { new DateTime(1101778442151366156, DateTimeKind.Utc), "O", null, "3492-05-25T12:43:35.1366156Z" };
yield return new object[] { new DateTime(221550163152616218, DateTimeKind.Utc), "r", null, "Sun, 25 Jan 0703 19:11:55 GMT" };
// Year patterns
if (PlatformDetection.IsNotInvariantGlobalization)
{
var enUS = new CultureInfo("en-US");
var thTH = new CultureInfo("th-TH");
yield return new object[] { new DateTime(1234, 5, 6), "yy", enUS, "34" };
yield return new object[] { DateTime.MaxValue, "yy", thTH, "42" };
for (int i = 3; i < 20; i++)
{
yield return new object[] { new DateTime(1234, 5, 6), new string('y', i), enUS, 1234.ToString("D" + i) };
yield return new object[] { DateTime.MaxValue, new string('y', i), thTH, 10542.ToString("D" + i) };
}
}
else
{
var invariant = new CultureInfo("");
yield return new object[] { new DateTime(1234, 5, 6), "yy", invariant, "34" };
for (int i = 3; i < 20; i++)
{
yield return new object[] { new DateTime(1234, 5, 6), new string('y', i), invariant, 1234.ToString("D" + i) };
}
}
}
[Theory]
[MemberData(nameof(Parse_ValidInput_Succeeds_MemberData))]
public static void Parse_Span_ValidInput_Succeeds(string input, CultureInfo culture, DateTime? expected)
{
Assert.Equal(expected, DateTime.Parse(input.AsSpan(), culture));
}
[Theory]
[MemberData(nameof(ParseExact_ValidInput_Succeeds_MemberData))]
public static void ParseExact_Span_ValidInput_Succeeds(string input, string format, CultureInfo culture, DateTimeStyles style, DateTime? expected)
{
DateTime result1 = DateTime.ParseExact(input.AsSpan(), format, culture, style);
DateTime result2 = DateTime.ParseExact(input.AsSpan(), new[] { format }, culture, style);
Assert.True(DateTime.TryParseExact(input.AsSpan(), format, culture, style, out DateTime result3));
Assert.True(DateTime.TryParseExact(input.AsSpan(), new[] { format }, culture, style, out DateTime result4));
Assert.Equal(result1, result2);
Assert.Equal(result1, result3);
Assert.Equal(result1, result4);
if (expected != null) // some inputs don't roundtrip well
{
// Normalize values to make comparison easier
if (expected.Value.Kind != DateTimeKind.Utc)
{
expected = expected.Value.ToUniversalTime();
}
if (result1.Kind != DateTimeKind.Utc)
{
result1 = result1.ToUniversalTime();
}
Assert.Equal(expected, result1);
}
}
[Theory]
[MemberData(nameof(ParseExact_InvalidInputs_Fail_MemberData))]
public static void ParseExact_Span_InvalidInputs_Fail(string input, string format, CultureInfo culture, DateTimeStyles style)
{
Assert.Throws<FormatException>(() => DateTime.ParseExact(input.AsSpan(), format, culture, style));
Assert.Throws<FormatException>(() => DateTime.ParseExact(input.AsSpan(), new[] { format }, culture, style));
Assert.False(DateTime.TryParseExact(input.AsSpan(), format, culture, style, out DateTime result));
Assert.False(DateTime.TryParseExact(input.AsSpan(), new[] { format }, culture, style, out result));
}
[Theory]
[MemberData(nameof(ToString_MatchesExpected_MemberData))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/60562", TestPlatforms.Android)]
public void ToString_Invoke_ReturnsExpected(DateTime dateTime, string format, IFormatProvider provider, string expected)
{
if (provider == null)
{
Assert.Equal(expected, dateTime.ToString(format));
}
Assert.Equal(expected, dateTime.ToString(format, provider));
}
[Fact]
public void ToLongDateString_Invoke_ReturnsExpected()
{
DateTime date = DateTime.Now;
Assert.Equal(date.ToString("D"), date.ToLongDateString());
}
[Fact]
public void ToLongTimeString_Invoke_ReturnsExpected()
{
DateTime date = DateTime.Now;
Assert.Equal(date.ToString("T"), date.ToLongTimeString());
}
[Fact]
public void ToShortDateString_Invoke_ReturnsExpected()
{
DateTime date = DateTime.Now;
Assert.Equal(date.ToString("d"), date.ToShortDateString());
}
[Fact]
public void ToShortTimeString_Invoke_ReturnsExpected()
{
DateTime date = DateTime.Now;
Assert.Equal(date.ToString("t"), date.ToShortTimeString());
}
[Fact]
public void GetTypeCode_Invoke_ReturnsExpected()
{
Assert.Equal(TypeCode.DateTime, DateTime.Now.GetTypeCode());
}
[Fact]
public void ToBoolean_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToBoolean(null));
}
[Fact]
public void ToChar_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToChar(null));
}
[Fact]
public void ToSByte_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToSByte(null));
}
[Fact]
public void ToByte_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToByte(null));
}
[Fact]
public void ToInt16_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToInt16(null));
}
[Fact]
public void ToUInt16_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToUInt16(null));
}
[Fact]
public void ToInt32_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToInt32(null));
}
[Fact]
public void ToUInt32_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToUInt32(null));
}
[Fact]
public void ToInt64_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToInt64(null));
}
[Fact]
public void ToUInt64_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToUInt64(null));
}
[Fact]
public void ToSingle_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToSingle(null));
}
[Fact]
public void ToDouble_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToDouble(null));
}
[Fact]
public void ToDecimal_Invoke_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => ((IConvertible)DateTime.Now).ToDecimal(null));
}
[Fact]
public void ToDateTime_Invoke_ReturnsExpected()
{
DateTime date = DateTime.Now;
Assert.Equal(date, ((IConvertible)date).ToDateTime(null));
}
[Fact]
public void ToType_DateTime_ReturnsExpected()
{
DateTime date = DateTime.Now;
Assert.Equal(date, ((IConvertible)date).ToType(typeof(DateTime), null));
}
[Fact]
public void GetObjectData_Invoke_ReturnsExpected()
{
ISerializable serializable = new DateTime(10, DateTimeKind.Utc);
SerializationInfo info = new SerializationInfo(typeof(DateTime), new FormatterConverter());
serializable.GetObjectData(info, new StreamingContext());
Assert.Equal(10, info.GetInt64("ticks"));
Assert.Equal(4611686018427387914, info.GetInt64("dateData"));
}
[Fact]
public void GetObjectData_NullInfo_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("info", () => ((ISerializable)DateTime.Now).GetObjectData(null, new StreamingContext()));
}
[Fact]
public void TestRoundTrippingDateTimeAndFileTime()
{
// This test ensure the round tripping of DateTime with the system file time.
// It is important to have this working on systems supporting leap seconds as the conversion wouldn't be simple
// conversion but involve some OS calls to ensure the right conversion is happening.
DateTime now = DateTime.UtcNow;
long fileTime = now.ToFileTimeUtc();
DateTime roundTrippedDateTime = DateTime.FromFileTimeUtc(fileTime);
Assert.Equal(now, roundTrippedDateTime);
now = DateTime.Now;
fileTime = now.ToFileTime();
roundTrippedDateTime = DateTime.FromFileTime(fileTime);
Assert.Equal(now, roundTrippedDateTime);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void TestTimeSynchronizationWithTheSystem()
{
// The reported time by the framework should be synchronized with the OS.
// There shouldn't be any shift by more than one second, otherwise there is something wrong.
// This test is useful when running on a system supporting leap seconds to ensure when the system
// has leap seconds, the framework reported time will still be synchronized.
SYSTEMTIME st;
SYSTEMTIME st1;
GetSystemTime(out st);
DateTime dt = DateTime.UtcNow;
GetSystemTime(out st1);
DateTime systemDateTimeNow1 = new DateTime(st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMillisecond, DateTimeKind.Utc);
DateTime systemDateTimeNow2 = new DateTime(st1.wYear, st1.wMonth, st1.wDay, st1.wHour, st1.wMinute, st1.wSecond, st1.wMillisecond, DateTimeKind.Utc);
// Usually GetSystemTime and DateTime.UtcNow calls doesn't take one second to execute, if this is not the case then
// the thread was sleeping for awhile and we cannot test reliably on that case.
TimeSpan diff = systemDateTimeNow2 - systemDateTimeNow1;
if (diff < TimeSpan.FromSeconds(1))
{
diff = dt - systemDateTimeNow1;
Assert.True(diff < TimeSpan.FromSeconds(1), $"Reported DateTime.UtcNow {dt} is shifted by more than one second then the system time {systemDateTimeNow1}");
}
}
[DllImport("Kernel32.dll")]
internal static extern void GetSystemTime(out SYSTEMTIME lpSystemTime);
[StructLayout(LayoutKind.Sequential)]
internal struct SYSTEMTIME
{
internal ushort wYear;
internal ushort wMonth;
internal ushort wDayOfWeek;
internal ushort wDay;
internal ushort wHour;
internal ushort wMinute;
internal ushort wSecond;
internal ushort wMillisecond;
}
[Theory]
[MemberData(nameof(StandardFormatSpecifiers))]
public static void TryFormat_MatchesToString(string format)
{
DateTime dt = DateTime.UtcNow;
string expected = dt.ToString(format);
// Just the right length, succeeds
Span<char> dest = new char[expected.Length];
Assert.True(dt.TryFormat(dest, out int charsWritten, format));
Assert.Equal(expected.Length, charsWritten);
Assert.Equal<char>(expected.ToCharArray(), dest.ToArray());
// Too short, fails
dest = new char[expected.Length - 1];
Assert.False(dt.TryFormat(dest, out charsWritten, format));
Assert.Equal(0, charsWritten);
// Longer than needed, succeeds
dest = new char[expected.Length + 1];
Assert.True(dt.TryFormat(dest, out charsWritten, format));
Assert.Equal(expected.Length, charsWritten);
Assert.Equal<char>(expected.ToCharArray(), dest.Slice(0, expected.Length).ToArray());
Assert.Equal(0, dest[dest.Length - 1]);
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotInvariantGlobalization))]
[MemberData(nameof(ToString_MatchesExpected_MemberData))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/60562", TestPlatforms.Android)]
public static void TryFormat_MatchesExpected(DateTime dateTime, string format, IFormatProvider provider, string expected)
{
var destination = new char[expected.Length];
Assert.False(dateTime.TryFormat(destination.AsSpan(0, destination.Length - 1), out _, format, provider));
Assert.True(dateTime.TryFormat(destination, out int charsWritten, format, provider));
Assert.Equal(destination.Length, charsWritten);
Assert.Equal(expected, new string(destination));
}
[Fact]
public static void UnixEpoch()
{
VerifyDateTime(DateTime.UnixEpoch, 1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
}
}
}
| -1 |
dotnet/runtime
| 66,362 |
Updating Unicode files to use 14.0.0
|
fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
joperezr
| 2022-03-08T22:15:44Z | 2022-03-10T22:28:36Z |
c069fa20aa9b2c2ce0482587198dea216ba9dd8d
|
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
Updating Unicode files to use 14.0.0. fixes https://github.com/dotnet/runtime/issues/44423
cc: @GrabYourPitchforks @tarekgh @stephentoub
As part https://github.com/dotnet/runtime/issues/61048 I needed to generate a casing table using the latest Unicode data (14.0) which wasn't yet being consumed by dotnet/runtime. This change will make the required changes to update to 14.0 so that in a follow-up I can add the required changes that will generate the casing table for Regex that I require. I basically followed the steps outlined both in the GenUnicodeProp readme as well as the STEW tools project to make these changes and then tested locally that both the Globalization and the STEW tests passed after the changes. Please let me know if I'm missing anything else as part of this change.
|
./src/libraries/System.Dynamic.Runtime/tests/Dynamic.NamedAndOptional/Conformance.dynamic.namedandoptional.decl.inheritance.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 ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit01.inherit01
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(dynamic i = null)
{
return i ?? 1;
}
}
public class Derived : Parent
{
public override int Foo(dynamic i = default(dynamic))
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit01a.inherit01a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 1)
{
return (int)i;
}
}
public class Derived : Parent
{
public override int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit02.inherit02
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(dynamic i)
{
return 1;
}
}
public class Derived : Parent
{
public override int Foo(dynamic i = null)
{
return 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit02a.inherit02a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i)
{
return (int)i;
}
}
public class Derived : Parent
{
public override int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit03a.inherit03a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 0)
{
return (int)1;
}
}
public class Derived : Parent
{
public override int Foo(int? i)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
try
{
p.Foo();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgCount, e.Message, "Foo", "0");
if (ret)
return 0;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit04.inherit04
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual dynamic Foo(dynamic i = null)
{
return 0;
}
}
public class Derived : Parent
{
public new dynamic Foo(dynamic i)
{
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit04a.inherit04a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 0)
{
return (int)i;
}
}
public class Derived : Parent
{
public new int Foo(int? i)
{
return (int)1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit05.inherit05
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Derived : Parent
{
public new dynamic Foo(dynamic i = null)
{
return 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit05a.inherit05a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 1)
{
return 1;
}
}
public class Derived : Parent
{
public new int Foo(int? i = 0)
{
return 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit06.inherit06
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Child : Parent
{
public override dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Derived : Child
{
public override dynamic Foo(dynamic i = null)
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit06a.inherit06a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 0)
{
return 1;
}
}
public class Child : Parent
{
public override int Foo(int? i = 2)
{
return 1;
}
}
public class Derived : Child
{
public override int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit07.inherit07
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Child : Parent
{
public virtual new dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Derived : Child
{
public override dynamic Foo(dynamic i = null)
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit07a.inherit07a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 1)
{
return 1;
}
}
public class Child : Parent
{
public virtual new int Foo(int? i = 20)
{
return 1;
}
}
public class Derived : Child
{
public override int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit08.inherit08
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Child : Parent
{
public override dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Derived : Child
{
public new dynamic Foo(dynamic i = null)
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit08a.inherit08a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 1)
{
return 1;
}
}
public class Child : Parent
{
public override int Foo(int? i = 1)
{
return 1;
}
}
public class Derived : Child
{
public new int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit09.inherit09
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
dynamic Foo(dynamic i = null);
}
public class Derived : Parent
{
public dynamic Foo(dynamic i = null)
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit09a.inherit09a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 1);
}
public class Derived : Parent
{
public int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit10.inherit10
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(dynamic i);
}
public class Derived : Parent
{
public int Foo(dynamic i = null)
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit10a.inherit10a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i);
}
public class Derived : Parent
{
public int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit11a.inherit11a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 0);
}
public class Derived : Parent
{
public int Foo(int? i)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
try
{
p.Foo();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgCount, e.Message, "Foo", "0");
if (ret)
return 0;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit12a.inherit12a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(14,17\).*CS0109</Expects>
public interface Parent
{
int Foo(int? i = 0);
}
public class Derived : Parent
{
public new int Foo(int? i)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
try
{
p.Foo();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgCount, e.Message, "Foo", "0");
if (ret)
return 0;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit13.inherit13
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
dynamic Foo(int i = 1);
}
public class Derived : Parent
{
public dynamic Foo(int i = 0)
{
return i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit13a.inherit13a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 1);
}
public class Derived : Parent
{
public int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit14.inherit14
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
dynamic Foo(int i = 1);
}
public class Child : Parent
{
public virtual dynamic Foo(int i = 0)
{
return i - 2;
}
}
public class Derived : Child
{
public override dynamic Foo(int i = 0)
{
return i + 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Child c = new Child();
Derived p = new Derived();
return p.Foo() + c.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit14a.inherit14a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 1);
}
public class Child : Parent
{
public virtual int Foo(int? i = 0)
{
return (int)i - 2;
}
}
public class Derived : Child
{
public override int Foo(int? i = 0)
{
return (int)i + 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic c = new Child();
dynamic p = new Derived();
return p.Foo() + c.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit15.inherit15
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(13,29\).*CS0109</Expects>
public interface Parent
{
dynamic Foo(int i = 1);
}
public class Child : Parent
{
public virtual new dynamic Foo(int i = 1)
{
return 1;
}
}
public class Derived : Child
{
public override dynamic Foo(int i = 0)
{
return i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit15a.inherit15a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(13,25\).*CS0109</Expects>
public interface Parent
{
int Foo(int? i = 1);
}
public class Child : Parent
{
public virtual new int Foo(int? i = 1)
{
return 1;
}
}
public class Derived : Child
{
public override int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit19.inherit19
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
dynamic Foo(dynamic i = null);
}
public struct Derived : Parent
{
public dynamic Foo(dynamic i = null)
{
return 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit19a.inherit19a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 1);
}
public struct Derived : Parent
{
public int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit20.inherit20
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
dynamic Foo(dynamic i = null);
}
public struct Derived : Parent
{
public dynamic Foo(dynamic i)
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit20a.inherit20a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 0);
}
public struct Derived : Parent
{
public int Foo(int? i)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p1 = new Derived();
dynamic p = p1;
return ((Parent)p).Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit21.inherit21
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
dynamic Foo(dynamic i = null);
}
public class Child : Parent
{
public virtual dynamic Foo(dynamic i = null)
{
return i ?? 0 - 2;
}
}
public class Derived : Child
{
public override dynamic Foo(dynamic i = null)
{
return i ?? 0 + 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Child c = new Child();
Derived p = new Derived();
return p.Foo() + c.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit21a.inherit21a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 0);
}
public class Child : Parent
{
public virtual int Foo(int? i = 0)
{
return (int)i - 2;
}
}
public class Derived : Child
{
public override int Foo(int? i = 0)
{
return (int)i + 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic c = new Child();
dynamic p = new Derived();
return p.Foo() + c.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit22.inherit22
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(dynamic i = null);
}
public struct Derived : Parent
{
public int Foo(dynamic i = null)
{
return 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit22a.inherit22a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 0);
}
public struct Derived : Parent
{
public int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p1 = new Derived();
dynamic p = p1;
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit23.inherit23
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(dynamic i = null);
}
public class Derived : Parent
{
public int Foo(dynamic i = null)
{
return i - 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Derived();
return p.Foo(1);
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit23a.inherit23a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 1);
}
public class Derived : Parent
{
public int Foo(int? i = 0)
{
return (int)i - 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p1 = new Derived();
dynamic p = p1;
dynamic d = 1;
return p.Foo(d);
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit24a.inherit24a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 0);
}
public struct Derived : Parent
{
public int Foo(int? i)
{
return i.Value;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
try
{
p.Foo();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgCount, e.Message, "Foo", "0");
if (ret)
return 0;
}
return 1;
}
}
//</Code>
}
|
// 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 ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit01.inherit01
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(dynamic i = null)
{
return i ?? 1;
}
}
public class Derived : Parent
{
public override int Foo(dynamic i = default(dynamic))
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit01a.inherit01a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 1)
{
return (int)i;
}
}
public class Derived : Parent
{
public override int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit02.inherit02
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(dynamic i)
{
return 1;
}
}
public class Derived : Parent
{
public override int Foo(dynamic i = null)
{
return 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit02a.inherit02a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i)
{
return (int)i;
}
}
public class Derived : Parent
{
public override int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit03a.inherit03a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 0)
{
return (int)1;
}
}
public class Derived : Parent
{
public override int Foo(int? i)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
try
{
p.Foo();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgCount, e.Message, "Foo", "0");
if (ret)
return 0;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit04.inherit04
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual dynamic Foo(dynamic i = null)
{
return 0;
}
}
public class Derived : Parent
{
public new dynamic Foo(dynamic i)
{
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit04a.inherit04a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 0)
{
return (int)i;
}
}
public class Derived : Parent
{
public new int Foo(int? i)
{
return (int)1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit05.inherit05
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Derived : Parent
{
public new dynamic Foo(dynamic i = null)
{
return 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit05a.inherit05a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 1)
{
return 1;
}
}
public class Derived : Parent
{
public new int Foo(int? i = 0)
{
return 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit06.inherit06
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Child : Parent
{
public override dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Derived : Child
{
public override dynamic Foo(dynamic i = null)
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit06a.inherit06a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 0)
{
return 1;
}
}
public class Child : Parent
{
public override int Foo(int? i = 2)
{
return 1;
}
}
public class Derived : Child
{
public override int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit07.inherit07
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Child : Parent
{
public virtual new dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Derived : Child
{
public override dynamic Foo(dynamic i = null)
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit07a.inherit07a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 1)
{
return 1;
}
}
public class Child : Parent
{
public virtual new int Foo(int? i = 20)
{
return 1;
}
}
public class Derived : Child
{
public override int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit08.inherit08
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Child : Parent
{
public override dynamic Foo(dynamic i = null)
{
return 1;
}
}
public class Derived : Child
{
public new dynamic Foo(dynamic i = null)
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit08a.inherit08a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public class Parent
{
public virtual int Foo(int? i = 1)
{
return 1;
}
}
public class Child : Parent
{
public override int Foo(int? i = 1)
{
return 1;
}
}
public class Derived : Child
{
public new int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit09.inherit09
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
dynamic Foo(dynamic i = null);
}
public class Derived : Parent
{
public dynamic Foo(dynamic i = null)
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit09a.inherit09a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 1);
}
public class Derived : Parent
{
public int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit10.inherit10
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(dynamic i);
}
public class Derived : Parent
{
public int Foo(dynamic i = null)
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit10a.inherit10a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i);
}
public class Derived : Parent
{
public int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit11a.inherit11a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 0);
}
public class Derived : Parent
{
public int Foo(int? i)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
try
{
p.Foo();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgCount, e.Message, "Foo", "0");
if (ret)
return 0;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit12a.inherit12a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(14,17\).*CS0109</Expects>
public interface Parent
{
int Foo(int? i = 0);
}
public class Derived : Parent
{
public new int Foo(int? i)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
try
{
p.Foo();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgCount, e.Message, "Foo", "0");
if (ret)
return 0;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit13.inherit13
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
dynamic Foo(int i = 1);
}
public class Derived : Parent
{
public dynamic Foo(int i = 0)
{
return i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit13a.inherit13a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 1);
}
public class Derived : Parent
{
public int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit14.inherit14
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
dynamic Foo(int i = 1);
}
public class Child : Parent
{
public virtual dynamic Foo(int i = 0)
{
return i - 2;
}
}
public class Derived : Child
{
public override dynamic Foo(int i = 0)
{
return i + 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Child c = new Child();
Derived p = new Derived();
return p.Foo() + c.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit14a.inherit14a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 1);
}
public class Child : Parent
{
public virtual int Foo(int? i = 0)
{
return (int)i - 2;
}
}
public class Derived : Child
{
public override int Foo(int? i = 0)
{
return (int)i + 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic c = new Child();
dynamic p = new Derived();
return p.Foo() + c.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit15.inherit15
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(13,29\).*CS0109</Expects>
public interface Parent
{
dynamic Foo(int i = 1);
}
public class Child : Parent
{
public virtual new dynamic Foo(int i = 1)
{
return 1;
}
}
public class Derived : Child
{
public override dynamic Foo(int i = 0)
{
return i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit15a.inherit15a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(13,25\).*CS0109</Expects>
public interface Parent
{
int Foo(int? i = 1);
}
public class Child : Parent
{
public virtual new int Foo(int? i = 1)
{
return 1;
}
}
public class Derived : Child
{
public override int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit19.inherit19
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
dynamic Foo(dynamic i = null);
}
public struct Derived : Parent
{
public dynamic Foo(dynamic i = null)
{
return 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Derived p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit19a.inherit19a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 1);
}
public struct Derived : Parent
{
public int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit20.inherit20
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
dynamic Foo(dynamic i = null);
}
public struct Derived : Parent
{
public dynamic Foo(dynamic i)
{
return i ?? 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit20a.inherit20a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 0);
}
public struct Derived : Parent
{
public int Foo(int? i)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p1 = new Derived();
dynamic p = p1;
return ((Parent)p).Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit21.inherit21
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
dynamic Foo(dynamic i = null);
}
public class Child : Parent
{
public virtual dynamic Foo(dynamic i = null)
{
return i ?? 0 - 2;
}
}
public class Derived : Child
{
public override dynamic Foo(dynamic i = null)
{
return i ?? 0 + 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Child c = new Child();
Derived p = new Derived();
return p.Foo() + c.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit21a.inherit21a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 0);
}
public class Child : Parent
{
public virtual int Foo(int? i = 0)
{
return (int)i - 2;
}
}
public class Derived : Child
{
public override int Foo(int? i = 0)
{
return (int)i + 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic c = new Child();
dynamic p = new Derived();
return p.Foo() + c.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit22.inherit22
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(dynamic i = null);
}
public struct Derived : Parent
{
public int Foo(dynamic i = null)
{
return 0;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Derived();
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit22a.inherit22a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 0);
}
public struct Derived : Parent
{
public int Foo(int? i = 0)
{
return (int)i;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p1 = new Derived();
dynamic p = p1;
return p.Foo();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit23.inherit23
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(dynamic i = null);
}
public class Derived : Parent
{
public int Foo(dynamic i = null)
{
return i - 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Derived();
return p.Foo(1);
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit23a.inherit23a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 1);
}
public class Derived : Parent
{
public int Foo(int? i = 0)
{
return (int)i - 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p1 = new Derived();
dynamic p = p1;
dynamic d = 1;
return p.Foo(d);
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.inheritance.inherit24a.inherit24a
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
// <Description>Simple Declaration of a inheritance chain with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public interface Parent
{
int Foo(int? i = 0);
}
public struct Derived : Parent
{
public int Foo(int? i)
{
return i.Value;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Derived();
try
{
p.Foo();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgCount, e.Message, "Foo", "0");
if (ret)
return 0;
}
return 1;
}
}
//</Code>
}
| -1 |
dotnet/runtime
| 66,360 |
Add tests for `comhost` with managed host
|
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained).
This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing:
cc @AaronRobinsonMSFT @jkoritzinsky
|
elinor-fung
| 2022-03-08T21:34:54Z | 2022-03-10T04:52:18Z |
f091e5585a6c2798ea15174261338b2f186c6be4
|
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
|
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained).
This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing:
cc @AaronRobinsonMSFT @jkoritzinsky
|
./docs/workflow/testing/host/testing.md
|
# Building and running host tests
The [host tests](/src/installer/tests) use [xunit](http://xunit.github.io/) for their testing framework.
## Building tests
To build the host tests, first build the product:
1. Build CoreCLR and libraries (`clr` and `libs` subsets):
```
build.cmd/sh -subset clr+libs -c Release
```
* [CoreCLR](../../building/coreclr/README.md) build instructions
* [Libraries](../../building/libraries/README.md) build instructions
2. Build the host and packs:
```
build.cmd/sh -subset host+packs.product -runtimeConfiguration Release -librariesConfiguration Release
```
If using a configuration other than Release for CoreCLR/libraries, specify the desired configuration in the `-runtimeConfiguration`/`-librariesConfiguration` arguments.
### Building all tests
The host tests are part of the `host` subset by default, so building the `host` subset also builds the host test. To build just the host tests:
```
build.cmd/sh -subset host.tests -runtimeConfiguration Release -librariesConfiguration Release
```
### Building specific tests
A specific test project can also be directly built. For example:
```
dotnet build src\installer\tests\HostActivation.Tests
```
## Test context
The host tests depend on:
1. Product binaries in a directory layout matching that of a .NET install
2. Restored [test projects](/src/installer/tests/Assets/TestProjects) which will be built and run by the tests
3. TestContextVariables.txt file with property and value pairs which will be read by the tests
When [running all tests](#running-all-tests), the build is configured such that these are created/performed before the start of the test run.
In order to create (or update) these dependencies without running all tests, the build targets that create them - RefreshProjectTestAssets and SetupTestContextVariables - can be directly run for the desired test project. For example:
```
dotnet build src\installer\tests\HostActivation.Tests -t:RefreshProjectTestAssets;SetupTestContextVariables -p:RuntimeConfiguration=Release -p:LibrariesConfiguration=Release
```
## Running tests
### Running all tests
To run all host tests:
```
build.cmd/sh -subset host.tests -test
```
By default, the above command will also build the tests before running them. To run the tests without building them, specify `-testnobuild`.
### Running specific tests
If all tests have not been previously run, make sure the [test context](#test-context) is set up for the test library.
Tests from a specific test project can be run using [`dotnet test`](https://docs.microsoft.com/dotnet/core/tools/dotnet-test) targeting the built test binary. For example:
```
dotnet test artifacts/bin/HostActivation.Tests/Debug/net5.0/HostActivation.Tests.dll --filter category!=failing
```
To filter to specific tests within the test library, use the [filter options](https://docs.microsoft.com/dotnet/core/tools/dotnet-test#filter-option-details) available for `dotnet test`. For example:
```
dotnet test artifacts/bin/HostActivation.Tests/Debug/net5.0/HostActivation.Tests.dll --filter DependencyResolution&category!=failing
```
The `category!=failing` is to respect the [filtering traits](../libraries/filtering-tests.md) used by the runtime repo.
### Visual Studio
The [Microsoft.DotNet.CoreSetup.sln](/src/installer/Microsoft.DotNet.CoreSetup.sln) can be used to run and debug host tests through Visual Studio. When using the solution, the product should have already been [built](#building-tests) and the [test context](#test-context) set up.
### Preserving test artifacts
In order to test the hosting components, the tests launch a separate process (e.g. `dotnet`, apphost, native host) and validate the expected output (standard output and error) of the launched process. This usually involves copying or creating test artifacts in the form of an application to run or a .NET install to run against. The tests will delete these artifacts after the test finishes. To allow inspection or usage after the test finishes, set the environment variable `PRESERVE_TEST_RUNS=1` to avoid deleting the test artifacts.
|
# Building and running host tests
The [host tests](/src/installer/tests) use [xunit](http://xunit.github.io/) for their testing framework.
## Building tests
To build the host tests, first build the product:
1. Build CoreCLR and libraries (`clr` and `libs` subsets):
```
build.cmd/sh -subset clr+libs -c Release
```
* [CoreCLR](../../building/coreclr/README.md) build instructions
* [Libraries](../../building/libraries/README.md) build instructions
2. Build the host and packs:
```
build.cmd/sh -subset host+packs.product -runtimeConfiguration Release -librariesConfiguration Release
```
If using a configuration other than Release for CoreCLR/libraries, specify the desired configuration in the `-runtimeConfiguration`/`-librariesConfiguration` arguments.
### Building all tests
The host tests are part of the `host` subset by default, so building the `host` subset also builds the host test. To build just the host tests:
```
build.cmd/sh -subset host.tests -runtimeConfiguration Release -librariesConfiguration Release
```
### Building specific tests
A specific test project can also be directly built. For example:
```
dotnet build src\installer\tests\HostActivation.Tests
```
## Test context
The host tests depend on:
1. Product binaries in a directory layout matching that of a .NET install
2. Restored [test projects](/src/installer/tests/Assets/TestProjects) which will be built and run by the tests
3. TestContextVariables.txt file with property and value pairs which will be read by the tests
When [running all tests](#running-all-tests), the build is configured such that these are created/performed before the start of the test run.
In order to create (or update) these dependencies without running all tests, the build targets that create them - RefreshProjectTestAssets and SetupTestContextVariables - can be directly run for the desired test project. For example:
```
dotnet build src\installer\tests\HostActivation.Tests -t:RefreshProjectTestAssets;SetupTestContextVariables -p:RuntimeConfiguration=Release -p:LibrariesConfiguration=Release
```
## Running tests
### Running all tests
To run all host tests:
```
build.cmd/sh -subset host.tests -test
```
By default, the above command will also build the tests before running them. To run the tests without building them, specify `-testnobuild`.
### Running specific tests
If all tests have not been previously run, make sure the [test context](#test-context) is set up for the test library.
Tests from a specific test project can be run using [`dotnet test`](https://docs.microsoft.com/dotnet/core/tools/dotnet-test) targeting the built test binary. For example:
```
dotnet test artifacts/bin/HostActivation.Tests/Debug/net5.0/HostActivation.Tests.dll --filter category!=failing
```
To filter to specific tests within the test library, use the [filter options](https://docs.microsoft.com/dotnet/core/tools/dotnet-test#filter-option-details) available for `dotnet test`. For example:
```
dotnet test artifacts/bin/HostActivation.Tests/Debug/net5.0/HostActivation.Tests.dll --filter "DependencyResolution&category!=failing"
```
The `category!=failing` is to respect the [filtering traits](../libraries/filtering-tests.md) used by the runtime repo.
### Visual Studio
The [Microsoft.DotNet.CoreSetup.sln](/src/installer/Microsoft.DotNet.CoreSetup.sln) can be used to run and debug host tests through Visual Studio. When using the solution, the product should have already been [built](#building-tests) and the [test context](#test-context) set up.
### Preserving test artifacts
In order to test the hosting components, the tests launch a separate process (e.g. `dotnet`, apphost, native host) and validate the expected output (standard output and error) of the launched process. This usually involves copying or creating test artifacts in the form of an application to run or a .NET install to run against. The tests will delete these artifacts after the test finishes. To allow inspection or usage after the test finishes, set the environment variable `PRESERVE_TEST_RUNS=1` to avoid deleting the test artifacts.
| 1 |
dotnet/runtime
| 66,360 |
Add tests for `comhost` with managed host
|
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained).
This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing:
cc @AaronRobinsonMSFT @jkoritzinsky
|
elinor-fung
| 2022-03-08T21:34:54Z | 2022-03-10T04:52:18Z |
f091e5585a6c2798ea15174261338b2f186c6be4
|
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
|
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained).
This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing:
cc @AaronRobinsonMSFT @jkoritzinsky
|
./src/installer/tests/Assets/TestProjects/ManagedHost/ManagedHost.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;
namespace ComClient
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
throw new Exception("Invalid number of arguments passed");
}
switch (args[0])
{
case "ijwhost":
{
// args: ... <ijw_library_path> <entry_point>
if (args.Length != 3)
{
throw new Exception("Invalid number of arguments passed");
}
IjwTest(args[1], args[2]);
break;
}
default:
throw new ArgumentException("Unknown scenario");
}
}
private static unsafe void IjwTest(string libraryPath, string entryPointName)
{
Console.WriteLine($"Invoking {entryPointName} in '{libraryPath}'");
IntPtr library = NativeLibrary.Load(libraryPath);
IntPtr export = NativeLibrary.GetExport(library, entryPointName);
// Test is assuming __cdecl, no argument,s and void return for simplicity
delegate* unmanaged[Cdecl]<void> entryPoint = (delegate* unmanaged[Cdecl]<void>)export;
entryPoint();
}
}
}
|
// 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;
namespace ComClient
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
throw new Exception("Invalid number of arguments passed");
}
switch (args[0])
{
case "comhost":
{
// args: ... <clsid>
if (args.Length != 2)
{
throw new Exception("Invalid number of arguments passed");
}
ComTest(args[1]);
break;
}
case "ijwhost":
{
// args: ... <ijw_library_path> <entry_point>
if (args.Length != 3)
{
throw new Exception("Invalid number of arguments passed");
}
IjwTest(args[1], args[2]);
break;
}
default:
throw new ArgumentException("Unknown scenario");
}
}
private static unsafe void ComTest(string clsidString)
{
Console.WriteLine($"Activating class ID {clsidString}");
Guid clsid = Guid.Parse(clsidString);
Type t = Type.GetTypeFromCLSID(clsid);
var server = Activator.CreateInstance(t);
Console.WriteLine($"Activation of {clsidString} succeeded.");
}
private static unsafe void IjwTest(string libraryPath, string entryPointName)
{
Console.WriteLine($"Invoking {entryPointName} in '{libraryPath}'");
IntPtr library = NativeLibrary.Load(libraryPath);
IntPtr export = NativeLibrary.GetExport(library, entryPointName);
// Test is assuming __cdecl, no argument,s and void return for simplicity
delegate* unmanaged[Cdecl]<void> entryPoint = (delegate* unmanaged[Cdecl]<void>)export;
entryPoint();
}
}
}
| 1 |
dotnet/runtime
| 66,360 |
Add tests for `comhost` with managed host
|
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained).
This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing:
cc @AaronRobinsonMSFT @jkoritzinsky
|
elinor-fung
| 2022-03-08T21:34:54Z | 2022-03-10T04:52:18Z |
f091e5585a6c2798ea15174261338b2f186c6be4
|
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
|
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained).
This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing:
cc @AaronRobinsonMSFT @jkoritzinsky
|
./src/installer/tests/Assets/TestProjects/ManagedHost/ManagedHost.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>$(NetCoreAppCurrent)</TargetFramework>
<RuntimeFrameworkVersion>$(MNAVersion)</RuntimeFrameworkVersion>
<RuntimeIdentifier>$(TestTargetRid)</RuntimeIdentifier>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>$(NetCoreAppCurrent)</TargetFramework>
<RuntimeFrameworkVersion>$(MNAVersion)</RuntimeFrameworkVersion>
<RuntimeIdentifier>$(TestTargetRid)</RuntimeIdentifier>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplicationManifest Condition="'$(RegFreeCom)' == 'true'">App.manifest</ApplicationManifest>
</PropertyGroup>
</Project>
| 1 |
dotnet/runtime
| 66,360 |
Add tests for `comhost` with managed host
|
Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained).
This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing:
cc @AaronRobinsonMSFT @jkoritzinsky
|
elinor-fung
| 2022-03-08T21:34:54Z | 2022-03-10T04:52:18Z |
f091e5585a6c2798ea15174261338b2f186c6be4
|
78083e7dd0d688c47c6bfbf2538e8032c0c023ae
|
Add tests for `comhost` with managed host. Add tests using `comhost` (reg-free) loaded by managed host (framework-dependent and self-contained).
This should resolve https://github.com/dotnet/runtime/issues/3452 finally :grimacing:
cc @AaronRobinsonMSFT @jkoritzinsky
|
./src/installer/tests/HostActivation.Tests/NativeHosting/Comhost.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection.Metadata;
using System.Runtime.InteropServices;
using Microsoft.DotNet.Cli.Build.Framework;
using Microsoft.NET.HostModel.ComHost;
using Xunit;
namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.NativeHosting
{
public class Comhost : IClassFixture<Comhost.SharedTestState>
{
private readonly SharedTestState sharedState;
public Comhost(SharedTestState sharedTestState)
{
sharedState = sharedTestState;
}
[Theory]
[PlatformSpecific(TestPlatforms.Windows)] // COM activation is only supported on Windows
[InlineData(1, true)]
[InlineData(10, true)]
[InlineData(10, false)]
public void ActivateClass(int count, bool synchronous)
{
string [] args = {
"comhost",
synchronous ? "synchronous" : "concurrent",
$"{count}",
sharedState.ComHostPath,
sharedState.ClsidString
};
CommandResult result = sharedState.CreateNativeHostCommand(args, sharedState.ComLibraryFixture.BuiltDotnet.BinPath)
.Execute();
result.Should().Pass()
.And.HaveStdOutContaining("New instance of Server created");
for (var i = 1; i <= count; ++i)
{
result.Should().HaveStdOutContaining($"Activation of {sharedState.ClsidString} succeeded. {i} of {count}");
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // COM activation is only supported on Windows
public void ActivateClass_IgnoreAppLocalHostFxr()
{
using (var fixture = sharedState.ComLibraryFixture.Copy())
{
File.WriteAllText(Path.Combine(fixture.TestProject.BuiltApp.Location, "hostfxr.dll"), string.Empty);
var comHostWithAppLocalFxr = Path.Combine(
fixture.TestProject.BuiltApp.Location,
$"{ fixture.TestProject.AssemblyName }.comhost.dll");
string[] args = {
"comhost",
"synchronous",
"1",
comHostWithAppLocalFxr,
sharedState.ClsidString
};
CommandResult result = sharedState.CreateNativeHostCommand(args, fixture.BuiltDotnet.BinPath)
.Execute();
result.Should().Pass()
.And.HaveStdOutContaining("New instance of Server created")
.And.HaveStdOutContaining($"Activation of {sharedState.ClsidString} succeeded.")
.And.HaveStdErrContaining("Using environment variable DOTNET_ROOT");
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // COM activation is only supported on Windows
public void ActivateClass_ValidateIErrorInfoResult()
{
using (var fixture = sharedState.ComLibraryFixture.Copy())
{
string missingRuntimeConfig = Path.Combine(fixture.TestProject.BuiltApp.Location,
$"{ fixture.TestProject.AssemblyName }.runtimeconfig.json");
File.Delete(missingRuntimeConfig);
var comHost = Path.Combine(
fixture.TestProject.BuiltApp.Location,
$"{ fixture.TestProject.AssemblyName }.comhost.dll");
string[] args = {
"comhost",
"errorinfo",
"1",
comHost,
sharedState.ClsidString
};
CommandResult result = sharedState.CreateNativeHostCommand(args, fixture.BuiltDotnet.BinPath)
.Execute();
result.Should().Pass()
.And.HaveStdOutContaining($"The specified runtimeconfig.json [{missingRuntimeConfig}] does not exist");
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // COM activation is only supported on Windows
public void LoadTypeLibraries()
{
using (var fixture = sharedState.ComLibraryFixture.Copy())
{
var comHost = Path.Combine(
fixture.TestProject.BuiltApp.Location,
$"{ fixture.TestProject.AssemblyName }.comhost.dll");
string[] args = {
"comhost",
"typelib",
"2",
comHost,
sharedState.ClsidString
};
CommandResult result = sharedState.CreateNativeHostCommand(args, fixture.BuiltDotnet.BinPath)
.Execute();
result.Should().Pass()
.And.HaveStdOutContaining("Loading default type library succeeded.")
.And.HaveStdOutContaining("Loading type library 1 succeeded.")
.And.HaveStdOutContaining("Loading type library 2 succeeded.");
}
}
public class SharedTestState : SharedTestStateBase
{
public string ComHostPath { get; }
public string ClsidString { get; } = "{438968CE-5950-4FBC-90B0-E64691350DF5}";
public TestProjectFixture ComLibraryFixture { get; }
public string ClsidMapPath { get; }
public IReadOnlyDictionary<int, string> TypeLibraries { get; }
public SharedTestState()
{
if (!OperatingSystem.IsWindows())
{
// COM activation is only supported on Windows
return;
}
ComLibraryFixture = new TestProjectFixture("ComLibrary", RepoDirectories)
.EnsureRestored()
.BuildProject();
// Create a .clsidmap from the assembly
ClsidMapPath = Path.Combine(BaseDirectory, $"{ ComLibraryFixture.TestProject.AssemblyName }.clsidmap");
using (var assemblyStream = new FileStream(ComLibraryFixture.TestProject.AppDll, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.Read))
using (var peReader = new System.Reflection.PortableExecutable.PEReader(assemblyStream))
{
if (peReader.HasMetadata)
{
MetadataReader reader = peReader.GetMetadataReader();
ClsidMap.Create(reader, ClsidMapPath);
}
}
// Use the locally built comhost to create a comhost with the embedded .clsidmap
ComHostPath = Path.Combine(
ComLibraryFixture.TestProject.BuiltApp.Location,
$"{ ComLibraryFixture.TestProject.AssemblyName }.comhost.dll");
// Include the test type libraries in the ComHost tests.
TypeLibraries = new Dictionary<int, string>
{
{ 1, Path.Combine(RepoDirectories.Artifacts, "corehost_test", "Server.tlb") },
{ 2, Path.Combine(RepoDirectories.Artifacts, "corehost_test", "Nested.tlb") }
};
ComHost.Create(
Path.Combine(RepoDirectories.HostArtifacts, "comhost.dll"),
ComHostPath,
ClsidMapPath,
TypeLibraries);
}
protected override void Dispose(bool disposing)
{
if (ComLibraryFixture != null)
ComLibraryFixture.Dispose();
base.Dispose(disposing);
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection.Metadata;
using System.Runtime.InteropServices;
using Microsoft.DotNet.Cli.Build.Framework;
using Microsoft.NET.HostModel.ComHost;
using Xunit;
namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.NativeHosting
{
[PlatformSpecific(TestPlatforms.Windows)] // COM activation is only supported on Windows
public class Comhost : IClassFixture<Comhost.SharedTestState>
{
private readonly SharedTestState sharedState;
public Comhost(SharedTestState sharedTestState)
{
sharedState = sharedTestState;
}
[Theory]
[InlineData(1, true)]
[InlineData(10, true)]
[InlineData(10, false)]
public void ActivateClass(int count, bool synchronous)
{
string [] args = {
"comhost",
synchronous ? "synchronous" : "concurrent",
$"{count}",
sharedState.ComHostPath,
sharedState.ClsidString
};
CommandResult result = sharedState.CreateNativeHostCommand(args, sharedState.ComLibraryFixture.BuiltDotnet.BinPath)
.Execute();
result.Should().Pass()
.And.HaveStdOutContaining("New instance of Server created");
for (var i = 1; i <= count; ++i)
{
result.Should().HaveStdOutContaining($"Activation of {sharedState.ClsidString} succeeded. {i} of {count}");
}
}
[Fact]
public void ActivateClass_IgnoreAppLocalHostFxr()
{
using (var fixture = sharedState.ComLibraryFixture.Copy())
{
File.WriteAllText(Path.Combine(fixture.TestProject.BuiltApp.Location, "hostfxr.dll"), string.Empty);
var comHostWithAppLocalFxr = Path.Combine(
fixture.TestProject.BuiltApp.Location,
$"{ fixture.TestProject.AssemblyName }.comhost.dll");
string[] args = {
"comhost",
"synchronous",
"1",
comHostWithAppLocalFxr,
sharedState.ClsidString
};
CommandResult result = sharedState.CreateNativeHostCommand(args, fixture.BuiltDotnet.BinPath)
.Execute();
result.Should().Pass()
.And.HaveStdOutContaining("New instance of Server created")
.And.HaveStdOutContaining($"Activation of {sharedState.ClsidString} succeeded.")
.And.HaveStdErrContaining("Using environment variable DOTNET_ROOT");
}
}
[Fact]
public void ActivateClass_ValidateIErrorInfoResult()
{
using (var fixture = sharedState.ComLibraryFixture.Copy())
{
string missingRuntimeConfig = Path.Combine(fixture.TestProject.BuiltApp.Location,
$"{ fixture.TestProject.AssemblyName }.runtimeconfig.json");
File.Delete(missingRuntimeConfig);
var comHost = Path.Combine(
fixture.TestProject.BuiltApp.Location,
$"{ fixture.TestProject.AssemblyName }.comhost.dll");
string[] args = {
"comhost",
"errorinfo",
"1",
comHost,
sharedState.ClsidString
};
CommandResult result = sharedState.CreateNativeHostCommand(args, fixture.BuiltDotnet.BinPath)
.Execute();
result.Should().Pass()
.And.HaveStdOutContaining($"The specified runtimeconfig.json [{missingRuntimeConfig}] does not exist");
}
}
[Fact]
public void LoadTypeLibraries()
{
using (var fixture = sharedState.ComLibraryFixture.Copy())
{
var comHost = Path.Combine(
fixture.TestProject.BuiltApp.Location,
$"{ fixture.TestProject.AssemblyName }.comhost.dll");
string[] args = {
"comhost",
"typelib",
"2",
comHost,
sharedState.ClsidString
};
CommandResult result = sharedState.CreateNativeHostCommand(args, fixture.BuiltDotnet.BinPath)
.Execute();
result.Should().Pass()
.And.HaveStdOutContaining("Loading default type library succeeded.")
.And.HaveStdOutContaining("Loading type library 1 succeeded.")
.And.HaveStdOutContaining("Loading type library 2 succeeded.");
}
}
public class SharedTestState : SharedTestStateBase
{
public string ComHostPath { get; }
public string ClsidString { get; } = "{438968CE-5950-4FBC-90B0-E64691350DF5}";
public TestProjectFixture ComLibraryFixture { get; }
public string ClsidMapPath { get; }
public IReadOnlyDictionary<int, string> TypeLibraries { get; }
public SharedTestState()
{
if (!OperatingSystem.IsWindows())
{
// COM activation is only supported on Windows
return;
}
ComLibraryFixture = new TestProjectFixture("ComLibrary", RepoDirectories)
.EnsureRestored()
.BuildProject();
// Create a .clsidmap from the assembly
ClsidMapPath = Path.Combine(BaseDirectory, $"{ ComLibraryFixture.TestProject.AssemblyName }.clsidmap");
using (var assemblyStream = new FileStream(ComLibraryFixture.TestProject.AppDll, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.Read))
using (var peReader = new System.Reflection.PortableExecutable.PEReader(assemblyStream))
{
if (peReader.HasMetadata)
{
MetadataReader reader = peReader.GetMetadataReader();
ClsidMap.Create(reader, ClsidMapPath);
}
}
// Use the locally built comhost to create a comhost with the embedded .clsidmap
ComHostPath = Path.Combine(
ComLibraryFixture.TestProject.BuiltApp.Location,
$"{ ComLibraryFixture.TestProject.AssemblyName }.comhost.dll");
// Include the test type libraries in the ComHost tests.
TypeLibraries = new Dictionary<int, string>
{
{ 1, Path.Combine(RepoDirectories.Artifacts, "corehost_test", "Server.tlb") },
{ 2, Path.Combine(RepoDirectories.Artifacts, "corehost_test", "Nested.tlb") }
};
ComHost.Create(
Path.Combine(RepoDirectories.HostArtifacts, "comhost.dll"),
ComHostPath,
ClsidMapPath,
TypeLibraries);
}
protected override void Dispose(bool disposing)
{
if (ComLibraryFixture != null)
ComLibraryFixture.Dispose();
base.Dispose(disposing);
}
}
}
}
| 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.